clang 23.0.0git
SemaExpr.cpp
Go to the documentation of this file.
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "TreeTransform.h"
15#include "UsedDeclVisitor.h"
19#include "clang/AST/ASTLambda.h"
21#include "clang/AST/Attr.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclObjC.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/ExprCXX.h"
30#include "clang/AST/ExprObjC.h"
34#include "clang/AST/Type.h"
35#include "clang/AST/TypeLoc.h"
46#include "clang/Sema/DeclSpec.h"
51#include "clang/Sema/Lookup.h"
52#include "clang/Sema/Overload.h"
54#include "clang/Sema/Scope.h"
57#include "clang/Sema/SemaARM.h"
58#include "clang/Sema/SemaCUDA.h"
60#include "clang/Sema/SemaHLSL.h"
61#include "clang/Sema/SemaObjC.h"
64#include "clang/Sema/Template.h"
65#include "llvm/ADT/STLExtras.h"
66#include "llvm/ADT/StringExtras.h"
67#include "llvm/Support/ConvertUTF.h"
68#include "llvm/Support/SaveAndRestore.h"
69#include "llvm/Support/TimeProfiler.h"
70#include "llvm/Support/TypeSize.h"
71#include <limits>
72#include <optional>
73
74using namespace clang;
75using namespace sema;
76
77bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
78 // See if this is an auto-typed variable whose initializer we are parsing.
79 if (ParsingInitForAutoVars.count(D))
80 return false;
81
82 // See if this is a deleted function.
83 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84 if (FD->isDeleted())
85 return false;
86
87 // If the function has a deduced return type, and we can't deduce it,
88 // then we can't use it either.
89 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
90 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
91 return false;
92
93 // See if this is an aligned allocation/deallocation function that is
94 // unavailable.
95 if (TreatUnavailableAsInvalid &&
97 return false;
98 }
99
100 // See if this function is unavailable.
101 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
102 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
103 return false;
104
106 return false;
107
108 return true;
109}
110
112 // Warn if this is used but marked unused.
113 if (const auto *A = D->getAttr<UnusedAttr>()) {
114 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
115 // should diagnose them.
116 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
117 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
118 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
119 if (DC && !DC->hasAttr<UnusedAttr>())
120 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
121 }
122 }
123}
124
126 assert(Decl && Decl->isDeleted());
127
128 if (Decl->isDefaulted()) {
129 // If the method was explicitly defaulted, point at that declaration.
130 if (!Decl->isImplicit())
131 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
132
133 // Try to diagnose why this special member function was implicitly
134 // deleted. This might fail, if that reason no longer applies.
136 return;
137 }
138
139 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
140 if (Ctor && Ctor->isInheritingConstructor())
142
143 Diag(Decl->getLocation(), diag::note_availability_specified_here)
144 << Decl << 1;
145}
146
147/// Determine whether a FunctionDecl was ever declared with an
148/// explicit storage class.
150 for (auto *I : D->redecls()) {
151 if (I->getStorageClass() != SC_None)
152 return true;
153 }
154 return false;
155}
156
157/// Check whether we're in an extern inline function and referring to a
158/// variable or function with internal linkage (C11 6.7.4p3).
159///
160/// This is only a warning because we used to silently accept this code, but
161/// in many cases it will not behave correctly. This is not enabled in C++ mode
162/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
163/// and so while there may still be user mistakes, most of the time we can't
164/// prove that there are errors.
166 const NamedDecl *D,
167 SourceLocation Loc) {
168 // This is disabled under C++; there are too many ways for this to fire in
169 // contexts where the warning is a false positive, or where it is technically
170 // correct but benign.
171 //
172 // WG14 N3622 which removed the constraint entirely in C2y. It is left
173 // enabled in earlier language modes because this is a constraint in those
174 // language modes. But in C2y mode, we still want to issue the "incompatible
175 // with previous standards" diagnostic, too.
176 if (S.getLangOpts().CPlusPlus)
177 return;
178
179 // Check if this is an inlined function or method.
180 FunctionDecl *Current = S.getCurFunctionDecl();
181 if (!Current)
182 return;
183 if (!Current->isInlined())
184 return;
185 if (!Current->isExternallyVisible())
186 return;
187
188 // Check if the decl has internal linkage.
190 return;
191
192 // Downgrade from ExtWarn to Extension if
193 // (1) the supposedly external inline function is in the main file,
194 // and probably won't be included anywhere else.
195 // (2) the thing we're referencing is a pure function.
196 // (3) the thing we're referencing is another inline function.
197 // This last can give us false negatives, but it's better than warning on
198 // wrappers for simple C library functions.
199 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
200 unsigned DiagID;
201 if (S.getLangOpts().C2y)
202 DiagID = diag::warn_c2y_compat_internal_in_extern_inline;
203 else if ((UsedFn && (UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>())) ||
205 DiagID = diag::ext_internal_in_extern_inline_quiet;
206 else
207 DiagID = diag::ext_internal_in_extern_inline;
208
209 S.Diag(Loc, DiagID) << /*IsVar=*/!UsedFn << D;
211 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
212 << D;
213}
214
216 const FunctionDecl *First = Cur->getFirstDecl();
217
218 // Suggest "static" on the function, if possible.
220 SourceLocation DeclBegin = First->getSourceRange().getBegin();
221 Diag(DeclBegin, diag::note_convert_inline_to_static)
222 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
223 }
224}
225
227 const ObjCInterfaceDecl *UnknownObjCClass,
228 bool ObjCPropertyAccess,
229 bool AvoidPartialAvailabilityChecks,
230 ObjCInterfaceDecl *ClassReceiver,
231 bool SkipTrailingRequiresClause) {
232 SourceLocation Loc = Locs.front();
234 // If there were any diagnostics suppressed by template argument deduction,
235 // emit them now.
236 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
237 if (Pos != SuppressedDiagnostics.end()) {
238 for (const auto &[DiagLoc, PD] : Pos->second) {
239 DiagnosticBuilder Builder(Diags.Report(DiagLoc, PD.getDiagID()));
240 PD.Emit(Builder);
241 }
242 // Clear out the list of suppressed diagnostics, so that we don't emit
243 // them again for this specialization. However, we don't obsolete this
244 // entry from the table, because we want to avoid ever emitting these
245 // diagnostics again.
246 Pos->second.clear();
247 }
248
249 // C++ [basic.start.main]p3:
250 // The function 'main' shall not be used within a program.
251 if (cast<FunctionDecl>(D)->isMain())
252 Diag(Loc, diag::ext_main_used);
253
255 }
256
257 // See if this is an auto-typed variable whose initializer we are parsing.
258 if (ParsingInitForAutoVars.count(D)) {
259 if (isa<BindingDecl>(D)) {
260 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
261 << D->getDeclName();
262 } else {
263 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
264 << diag::ParsingInitFor::Var << D->getDeclName()
265 << cast<VarDecl>(D)->getType();
266 }
267 return true;
268 }
269
270 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
271 // See if this is a deleted function.
272 if (FD->isDeleted()) {
273 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
274 if (Ctor && Ctor->isInheritingConstructor())
275 Diag(Loc, diag::err_deleted_inherited_ctor_use)
276 << Ctor->getParent()
277 << Ctor->getInheritedConstructor().getConstructor()->getParent();
278 else {
279 StringLiteral *Msg = FD->getDeletedMessage();
280 Diag(Loc, diag::err_deleted_function_use)
281 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
282 }
284 return true;
285 }
286
287 // [expr.prim.id]p4
288 // A program that refers explicitly or implicitly to a function with a
289 // trailing requires-clause whose constraint-expression is not satisfied,
290 // other than to declare it, is ill-formed. [...]
291 //
292 // See if this is a function with constraints that need to be satisfied.
293 // Check this before deducing the return type, as it might instantiate the
294 // definition.
295 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
296 ConstraintSatisfaction Satisfaction;
297 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
298 /*ForOverloadResolution*/ true))
299 // A diagnostic will have already been generated (non-constant
300 // constraint expression, for example)
301 return true;
302 if (!Satisfaction.IsSatisfied) {
303 Diag(Loc,
304 diag::err_reference_to_function_with_unsatisfied_constraints)
305 << D;
306 DiagnoseUnsatisfiedConstraint(Satisfaction);
307 return true;
308 }
309 }
310
311 // If the function has a deduced return type, and we can't deduce it,
312 // then we can't use it either.
313 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
314 DeduceReturnType(FD, Loc))
315 return true;
316
317 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
318 return true;
319
320 }
321
322 if (auto *Concept = dyn_cast<ConceptDecl>(D);
324 return true;
325
326 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
327 // Lambdas are only default-constructible or assignable in C++2a onwards.
328 if (MD->getParent()->isLambda() &&
330 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
331 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
332 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
334 }
335 }
336
337 auto getReferencedObjCProp = [](const NamedDecl *D) ->
338 const ObjCPropertyDecl * {
339 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
340 return MD->findPropertyDecl();
341 return nullptr;
342 };
343 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
344 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
345 return true;
346 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
347 return true;
348 }
349
350 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
351 // Only the variables omp_in and omp_out are allowed in the combiner.
352 // Only the variables omp_priv and omp_orig are allowed in the
353 // initializer-clause.
354 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
355 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
356 isa<VarDecl>(D)) {
357 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
359 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
360 return true;
361 }
362
363 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
364 // List-items in map clauses on this construct may only refer to the declared
365 // variable var and entities that could be referenced by a procedure defined
366 // at the same location.
367 // [OpenMP 5.2] Also allow iterator declared variables.
368 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
369 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
370 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
372 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
373 return true;
374 }
375
376 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
377 Diag(Loc, diag::err_use_of_empty_using_if_exists);
378 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
379 return true;
380 }
381
382 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
383 AvoidPartialAvailabilityChecks, ClassReceiver);
384
385 DiagnoseUnusedOfDecl(*this, D, Loc);
386
388
389 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
390 if (getLangOpts().getFPEvalMethod() !=
392 PP.getLastFPEvalPragmaLocation().isValid() &&
393 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
394 Diag(D->getLocation(),
395 diag::err_type_available_only_in_default_eval_method)
396 << D->getName();
397 }
398
399 if (auto *VD = dyn_cast<ValueDecl>(D))
400 checkTypeSupport(VD->getType(), Loc, VD);
401
402 if (LangOpts.SYCLIsDevice ||
403 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
404 if (!Context.getTargetInfo().isTLSSupported())
405 if (const auto *VD = dyn_cast<VarDecl>(D))
406 if (VD->getTLSKind() != VarDecl::TLS_None)
407 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
408 }
409
410 if (LangOpts.SYCLIsDevice && isa<FunctionDecl>(D))
411 SYCL().CheckDeviceUseOfDecl(D, Loc);
412
413 return false;
414}
415
417 ArrayRef<Expr *> Args) {
418 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
419 if (!Attr)
420 return;
421
422 // The number of formal parameters of the declaration.
423 unsigned NumFormalParams;
424
425 // The kind of declaration. This is also an index into a %select in
426 // the diagnostic.
427 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
428
429 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
430 NumFormalParams = MD->param_size();
431 CalleeKind = CK_Method;
432 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
433 NumFormalParams = FD->param_size();
434 CalleeKind = CK_Function;
435 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
436 QualType Ty = VD->getType();
437 const FunctionType *Fn = nullptr;
438 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
439 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
440 if (!Fn)
441 return;
442 CalleeKind = CK_Function;
443 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
444 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
445 CalleeKind = CK_Block;
446 } else {
447 return;
448 }
449
450 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
451 NumFormalParams = proto->getNumParams();
452 else
453 NumFormalParams = 0;
454 } else {
455 return;
456 }
457
458 // "NullPos" is the number of formal parameters at the end which
459 // effectively count as part of the variadic arguments. This is
460 // useful if you would prefer to not have *any* formal parameters,
461 // but the language forces you to have at least one.
462 unsigned NullPos = Attr->getNullPos();
463 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
464 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
465
466 // The number of arguments which should follow the sentinel.
467 unsigned NumArgsAfterSentinel = Attr->getSentinel();
468
469 // If there aren't enough arguments for all the formal parameters,
470 // the sentinel, and the args after the sentinel, complain.
471 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
472 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
473 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
474 return;
475 }
476
477 // Otherwise, find the sentinel expression.
478 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
479 if (!SentinelExpr)
480 return;
481 if (SentinelExpr->isValueDependent())
482 return;
483 if (Context.isSentinelNullExpr(SentinelExpr))
484 return;
485
486 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
487 // or 'NULL' if those are actually defined in the context. Only use
488 // 'nil' for ObjC methods, where it's much more likely that the
489 // variadic arguments form a list of object pointers.
490 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
491 std::string NullValue;
492 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
493 NullValue = "nil";
494 else if (getLangOpts().CPlusPlus11)
495 NullValue = "nullptr";
496 else if (PP.isMacroDefined("NULL"))
497 NullValue = "NULL";
498 else
499 NullValue = "(void*) 0";
500
501 if (MissingNilLoc.isInvalid())
502 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
503 else
504 Diag(MissingNilLoc, diag::warn_missing_sentinel)
505 << int(CalleeKind)
506 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
507 Diag(D->getLocation(), diag::note_sentinel_here)
508 << int(CalleeKind) << Attr->getRange();
509}
510
512 return E ? E->getSourceRange() : SourceRange();
513}
514
515//===----------------------------------------------------------------------===//
516// Standard Promotions and Conversions
517//===----------------------------------------------------------------------===//
518
519/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
521 // Handle any placeholder expressions which made it here.
522 if (E->hasPlaceholderType()) {
524 if (result.isInvalid()) return ExprError();
525 E = result.get();
526 }
527
528 QualType Ty = E->getType();
529 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
530
531 if (Ty->isFunctionType()) {
532 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
533 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
535 return ExprError();
536
537 E = ImpCastExprToType(E, Context.getPointerType(Ty),
538 CK_FunctionToPointerDecay).get();
539 } else if (Ty->isArrayType()) {
540 // In C90 mode, arrays only promote to pointers if the array expression is
541 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
542 // type 'array of type' is converted to an expression that has type 'pointer
543 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
544 // that has type 'array of type' ...". The relevant change is "an lvalue"
545 // (C90) to "an expression" (C99).
546 //
547 // C++ 4.2p1:
548 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
549 // T" can be converted to an rvalue of type "pointer to T".
550 //
551 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
552 ExprResult Res = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
553 CK_ArrayToPointerDecay);
554 if (Res.isInvalid())
555 return ExprError();
556 E = Res.get();
557 }
558 }
559 return E;
560}
561
563 // Check to see if we are dereferencing a null pointer. If so,
564 // and if not volatile-qualified, this is undefined behavior that the
565 // optimizer will delete, so warn about it. People sometimes try to use this
566 // to get a deterministic trap and are surprised by clang's behavior. This
567 // only handles the pattern "*null", which is a very syntactic check.
568 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
569 if (UO && UO->getOpcode() == UO_Deref &&
570 UO->getSubExpr()->getType()->isPointerType()) {
571 const LangAS AS =
572 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
573 if ((!isTargetAddressSpace(AS) ||
574 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
575 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
577 !UO->getType().isVolatileQualified()) {
578 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
579 S.PDiag(diag::warn_indirection_through_null)
580 << UO->getSubExpr()->getSourceRange());
581 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
582 S.PDiag(diag::note_indirection_through_null));
583 }
584 }
585}
586
587static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
588 SourceLocation AssignLoc,
589 const Expr* RHS) {
590 const ObjCIvarDecl *IV = OIRE->getDecl();
591 if (!IV)
592 return;
593
594 DeclarationName MemberName = IV->getDeclName();
596 if (!Member || !Member->isStr("isa"))
597 return;
598
599 const Expr *Base = OIRE->getBase();
600 QualType BaseType = Base->getType();
601 if (OIRE->isArrow())
602 BaseType = BaseType->getPointeeType();
603 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
604 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
605 ObjCInterfaceDecl *ClassDeclared = nullptr;
606 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
607 if (!ClassDeclared->getSuperClass()
608 && (*ClassDeclared->ivar_begin()) == IV) {
609 if (RHS) {
610 NamedDecl *ObjectSetClass =
612 &S.Context.Idents.get("object_setClass"),
614 if (ObjectSetClass) {
615 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
616 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
618 "object_setClass(")
620 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
621 << FixItHint::CreateInsertion(RHSLocEnd, ")");
622 }
623 else
624 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
625 } else {
626 NamedDecl *ObjectGetClass =
628 &S.Context.Idents.get("object_getClass"),
630 if (ObjectGetClass)
631 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
633 "object_getClass(")
635 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
636 else
637 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
638 }
639 S.Diag(IV->getLocation(), diag::note_ivar_decl);
640 }
641 }
642}
643
645 // Handle any placeholder expressions which made it here.
646 if (E->hasPlaceholderType()) {
648 if (result.isInvalid()) return ExprError();
649 E = result.get();
650 }
651
652 // C++ [conv.lval]p1:
653 // A glvalue of a non-function, non-array type T can be
654 // converted to a prvalue.
655 if (!E->isGLValue()) return E;
656
657 QualType T = E->getType();
658 assert(!T.isNull() && "r-value conversion on typeless expression?");
659
660 // lvalue-to-rvalue conversion cannot be applied to types that decay to
661 // pointers (i.e. function or array types).
662 if (T->canDecayToPointerType())
663 return E;
664
665 // We don't want to throw lvalue-to-rvalue casts on top of
666 // expressions of certain types in C++.
667 // In HLSL LvaluetoRvalue conversion is allowed on records.
668 if (getLangOpts().CPlusPlus) {
669 if (T == Context.OverloadTy || (T->isRecordType() && !getLangOpts().HLSL) ||
670 (T->isDependentType() && !T->isAnyPointerType() &&
671 !T->isMemberPointerType()))
672 return E;
673 }
674
675 // The C standard is actually really unclear on this point, and
676 // DR106 tells us what the result should be but not why. It's
677 // generally best to say that void types just doesn't undergo
678 // lvalue-to-rvalue at all. Note that expressions of unqualified
679 // 'void' type are never l-values, but qualified void can be.
680 if (T->isVoidType())
681 return E;
682
683 // OpenCL usually rejects direct accesses to values of 'half' type.
684 if (getLangOpts().OpenCL &&
685 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
686 T->isHalfType()) {
687 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
688 << 0 << T;
689 return ExprError();
690 }
691
693 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
694 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
695 &Context.Idents.get("object_getClass"),
697 if (ObjectGetClass)
698 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
699 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
701 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
702 else
703 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
704 }
705 else if (const ObjCIvarRefExpr *OIRE =
706 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
707 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
708
709 // C++ [conv.lval]p1:
710 // [...] If T is a non-class type, the type of the prvalue is the
711 // cv-unqualified version of T. Otherwise, the type of the
712 // rvalue is T.
713 //
714 // C99 6.3.2.1p2:
715 // If the lvalue has qualified type, the value has the unqualified
716 // version of the type of the lvalue; otherwise, the value has the
717 // type of the lvalue.
718 if (T.hasQualifiers())
719 T = T.getUnqualifiedType();
720
721 // Under the MS ABI, lock down the inheritance model now.
722 if (T->isMemberPointerType() &&
723 Context.getTargetInfo().getCXXABI().isMicrosoft())
724 (void)isCompleteType(E->getExprLoc(), T);
725
727 if (Res.isInvalid())
728 return Res;
729 E = Res.get();
730
731 // Loading a __weak object implicitly retains the value, so we need a cleanup to
732 // balance that.
734 Cleanup.setExprNeedsCleanups(true);
735
737 Cleanup.setExprNeedsCleanups(true);
738
740 return ExprError();
741
742 // C++ [conv.lval]p3:
743 // If T is cv std::nullptr_t, the result is a null pointer constant.
744 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
745 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
747
748 // C11 6.3.2.1p2:
749 // ... if the lvalue has atomic type, the value has the non-atomic version
750 // of the type of the lvalue ...
751 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
752 T = Atomic->getValueType().getUnqualifiedType();
753 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
754 nullptr, VK_PRValue, FPOptionsOverride());
755 }
756
757 return Res;
758}
759
762 if (Res.isInvalid())
763 return ExprError();
764 Res = DefaultLvalueConversion(Res.get());
765 if (Res.isInvalid())
766 return ExprError();
767 return Res;
768}
769
771 QualType Ty = E->getType();
772 ExprResult Res = E;
773 // Only do implicit cast for a function type, but not for a pointer
774 // to function type.
775 if (Ty->isFunctionType()) {
776 Res = ImpCastExprToType(E, Context.getPointerType(Ty),
777 CK_FunctionToPointerDecay);
778 if (Res.isInvalid())
779 return ExprError();
780 }
781 Res = DefaultLvalueConversion(Res.get());
782 if (Res.isInvalid())
783 return ExprError();
784 return Res.get();
785}
786
787/// UsualUnaryFPConversions - Promotes floating-point types according to the
788/// current language semantics.
790 QualType Ty = E->getType();
791 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
792
793 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
794 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
795 (getLangOpts().getFPEvalMethod() !=
797 PP.getLastFPEvalPragmaLocation().isValid())) {
798 switch (EvalMethod) {
799 default:
800 llvm_unreachable("Unrecognized float evaluation method");
801 break;
803 llvm_unreachable("Float evaluation method should be set by now");
804 break;
806 if (Context.getFloatingTypeOrder(Context.DoubleTy, Ty) > 0)
807 // Widen the expression to double.
808 return Ty->isComplexType()
810 Context.getComplexType(Context.DoubleTy),
811 CK_FloatingComplexCast)
812 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
813 break;
815 if (Context.getFloatingTypeOrder(Context.LongDoubleTy, Ty) > 0)
816 // Widen the expression to long double.
817 return Ty->isComplexType()
819 E, Context.getComplexType(Context.LongDoubleTy),
820 CK_FloatingComplexCast)
821 : ImpCastExprToType(E, Context.LongDoubleTy,
822 CK_FloatingCast);
823 break;
824 }
825 }
826
827 // Half FP have to be promoted to float unless it is natively supported
828 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
829 return ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast);
830
831 return E;
832}
833
834/// UsualUnaryConversions - Performs various conversions that are common to most
835/// operators (C99 6.3). The conversions of array and function types are
836/// sometimes suppressed. For example, the array->pointer conversion doesn't
837/// apply if the array is an argument to the sizeof or address (&) operators.
838/// In these instances, this routine should *not* be called.
840 // First, convert to an r-value.
842 if (Res.isInvalid())
843 return ExprError();
844
845 // Promote floating-point types.
846 Res = UsualUnaryFPConversions(Res.get());
847 if (Res.isInvalid())
848 return ExprError();
849 E = Res.get();
850
851 QualType Ty = E->getType();
852 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
853
854 // Try to perform integral promotions if the object has a theoretically
855 // promotable type.
857 // C99 6.3.1.1p2:
858 //
859 // The following may be used in an expression wherever an int or
860 // unsigned int may be used:
861 // - an object or expression with an integer type whose integer
862 // conversion rank is less than or equal to the rank of int
863 // and unsigned int.
864 // - A bit-field of type _Bool, int, signed int, or unsigned int.
865 //
866 // If an int can represent all values of the original type, the
867 // value is converted to an int; otherwise, it is converted to an
868 // unsigned int. These are called the integer promotions. All
869 // other types are unchanged by the integer promotions.
870
871 QualType PTy = Context.isPromotableBitField(E);
872 if (!PTy.isNull()) {
873 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
874 return E;
875 }
876 if (Context.isPromotableIntegerType(Ty)) {
877 QualType PT = Context.getPromotedIntegerType(Ty);
878 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
879 return E;
880 }
881 }
882 return E;
883}
884
885/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
886/// do not have a prototype. Arguments that have type float or __fp16
887/// are promoted to double. All other argument types are converted by
888/// UsualUnaryConversions().
890 QualType Ty = E->getType();
891 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
892
894 if (Res.isInvalid())
895 return ExprError();
896 E = Res.get();
897
898 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
899 // promote to double.
900 // Note that default argument promotion applies only to float (and
901 // half/fp16); it does not apply to _Float16.
902 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
903 if (BTy && (BTy->getKind() == BuiltinType::Half ||
904 BTy->getKind() == BuiltinType::Float)) {
905 if (getLangOpts().OpenCL &&
906 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
907 if (BTy->getKind() == BuiltinType::Half) {
908 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
909 }
910 } else {
911 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
912 }
913 }
914 if (BTy &&
915 getLangOpts().getExtendIntArgs() ==
917 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
918 Context.getTypeSizeInChars(BTy) <
919 Context.getTypeSizeInChars(Context.LongLongTy)) {
920 E = (Ty->isUnsignedIntegerType())
921 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
922 .get()
923 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
924 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
925 "Unexpected typesize for LongLongTy");
926 }
927
928 // C++ performs lvalue-to-rvalue conversion as a default argument
929 // promotion, even on class types, but note:
930 // C++11 [conv.lval]p2:
931 // When an lvalue-to-rvalue conversion occurs in an unevaluated
932 // operand or a subexpression thereof the value contained in the
933 // referenced object is not accessed. Otherwise, if the glvalue
934 // has a class type, the conversion copy-initializes a temporary
935 // of type T from the glvalue and the result of the conversion
936 // is a prvalue for the temporary.
937 // FIXME: add some way to gate this entire thing for correctness in
938 // potentially potentially evaluated contexts.
942 E->getExprLoc(), E);
943 if (Temp.isInvalid())
944 return ExprError();
945 E = Temp.get();
946 }
947
948 // C++ [expr.call]p7, per CWG722:
949 // An argument that has (possibly cv-qualified) type std::nullptr_t is
950 // converted to void* ([conv.ptr]).
951 // (This does not apply to C23 nullptr)
953 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
954
955 return E;
956}
957
959 if (Ty->isIncompleteType()) {
960 // C++11 [expr.call]p7:
961 // After these conversions, if the argument does not have arithmetic,
962 // enumeration, pointer, pointer to member, or class type, the program
963 // is ill-formed.
964 //
965 // Since we've already performed null pointer conversion, array-to-pointer
966 // decay and function-to-pointer decay, the only such type in C++ is cv
967 // void. This also handles initializer lists as variadic arguments.
968 if (Ty->isVoidType())
969 return VarArgKind::Invalid;
970
971 if (Ty->isObjCObjectType())
972 return VarArgKind::Invalid;
973 return VarArgKind::Valid;
974 }
975
977 return VarArgKind::Invalid;
978
979 if (Context.getTargetInfo().getTriple().isWasm() &&
981 return VarArgKind::Invalid;
982 }
983
984 if (Ty.isCXX98PODType(Context))
985 return VarArgKind::Valid;
986
987 // C++11 [expr.call]p7:
988 // Passing a potentially-evaluated argument of class type (Clause 9)
989 // having a non-trivial copy constructor, a non-trivial move constructor,
990 // or a non-trivial destructor, with no corresponding parameter,
991 // is conditionally-supported with implementation-defined semantics.
994 if (!Record->hasNonTrivialCopyConstructor() &&
995 !Record->hasNonTrivialMoveConstructor() &&
996 !Record->hasNonTrivialDestructor())
998
999 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
1000 return VarArgKind::Valid;
1001
1002 if (Ty->isObjCObjectType())
1003 return VarArgKind::Invalid;
1004
1005 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1006 return VarArgKind::Valid;
1007
1008 if (getLangOpts().MSVCCompat)
1010
1011 if (getLangOpts().HLSL && Ty->getAs<HLSLAttributedResourceType>())
1012 return VarArgKind::Valid;
1013
1014 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1015 // permitted to reject them. We should consider doing so.
1016 return VarArgKind::Undefined;
1017}
1018
1020 // Don't allow one to pass an Objective-C interface to a vararg.
1021 const QualType &Ty = E->getType();
1022 VarArgKind VAK = isValidVarArgType(Ty);
1023
1024 // Complain about passing non-POD types through varargs.
1025 switch (VAK) {
1028 E->getBeginLoc(), nullptr,
1029 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1030 [[fallthrough]];
1031 case VarArgKind::Valid:
1032 if (Ty->isRecordType()) {
1033 // This is unlikely to be what the user intended. If the class has a
1034 // 'c_str' member function, the user probably meant to call that.
1035 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1036 PDiag(diag::warn_pass_class_arg_to_vararg)
1037 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1038 }
1039 break;
1040
1043 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1044 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1045 << getLangOpts().CPlusPlus11 << Ty << CT);
1046 break;
1047
1050 Diag(E->getBeginLoc(),
1051 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1052 << Ty << CT;
1053 else if (Ty->isObjCObjectType())
1054 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1055 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1056 << Ty << CT);
1057 else
1058 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1059 << isa<InitListExpr>(E) << Ty << CT;
1060 break;
1061 }
1062}
1063
1065 FunctionDecl *FDecl) {
1066 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1067 // Strip the unbridged-cast placeholder expression off, if applicable.
1068 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1069 (CT == VariadicCallType::Method ||
1070 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1071 E = ObjC().stripARCUnbridgedCast(E);
1072
1073 // Otherwise, do normal placeholder checking.
1074 } else {
1075 ExprResult ExprRes = CheckPlaceholderExpr(E);
1076 if (ExprRes.isInvalid())
1077 return ExprError();
1078 E = ExprRes.get();
1079 }
1080 }
1081
1083 if (ExprRes.isInvalid())
1084 return ExprError();
1085
1086 // Copy blocks to the heap.
1087 if (ExprRes.get()->getType()->isBlockPointerType())
1088 maybeExtendBlockObject(ExprRes);
1089
1090 E = ExprRes.get();
1091
1092 // Diagnostics regarding non-POD argument types are
1093 // emitted along with format string checking in Sema::CheckFunctionCall().
1095 // Turn this into a trap.
1096 CXXScopeSpec SS;
1097 SourceLocation TemplateKWLoc;
1098 UnqualifiedId Name;
1099 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1100 E->getBeginLoc());
1101 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1102 /*HasTrailingLParen=*/true,
1103 /*IsAddressOfOperand=*/false);
1104 if (TrapFn.isInvalid())
1105 return ExprError();
1106
1107 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1108 E->getEndLoc());
1109 if (Call.isInvalid())
1110 return ExprError();
1111
1112 ExprResult Comma =
1113 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1114 if (Comma.isInvalid())
1115 return ExprError();
1116 return Comma.get();
1117 }
1118
1119 if (!getLangOpts().CPlusPlus &&
1121 diag::err_call_incomplete_argument))
1122 return ExprError();
1123
1124 return E;
1125}
1126
1127/// Convert complex integers to complex floats and real integers to
1128/// real floats as required for complex arithmetic. Helper function of
1129/// UsualArithmeticConversions()
1130///
1131/// \return false if the integer expression is an integer type and is
1132/// successfully converted to the (complex) float type.
1134 ExprResult &ComplexExpr,
1135 QualType IntTy,
1136 QualType ComplexTy,
1137 bool SkipCast) {
1138 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1139 if (SkipCast) return false;
1140 if (IntTy->isIntegerType()) {
1141 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1142 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1143 } else {
1144 assert(IntTy->isComplexIntegerType());
1145 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1146 CK_IntegralComplexToFloatingComplex);
1147 }
1148 return false;
1149}
1150
1151// This handles complex/complex, complex/float, or float/complex.
1152// When both operands are complex, the shorter operand is converted to the
1153// type of the longer, and that is the type of the result. This corresponds
1154// to what is done when combining two real floating-point operands.
1155// The fun begins when size promotion occur across type domains.
1156// From H&S 6.3.4: When one operand is complex and the other is a real
1157// floating-point type, the less precise type is converted, within it's
1158// real or complex domain, to the precision of the other type. For example,
1159// when combining a "long double" with a "double _Complex", the
1160// "double _Complex" is promoted to "long double _Complex".
1162 QualType ShorterType,
1163 QualType LongerType,
1164 bool PromotePrecision) {
1165 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1167 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1168
1169 if (PromotePrecision) {
1170 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1171 Shorter =
1172 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1173 } else {
1174 if (LongerIsComplex)
1175 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1176 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1177 }
1178 }
1179 return Result;
1180}
1181
1182/// Handle arithmetic conversion with complex types. Helper function of
1183/// UsualArithmeticConversions()
1185 ExprResult &RHS, QualType LHSType,
1186 QualType RHSType, bool IsCompAssign) {
1187 // Handle (complex) integer types.
1188 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1189 /*SkipCast=*/false))
1190 return LHSType;
1191 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1192 /*SkipCast=*/IsCompAssign))
1193 return RHSType;
1194
1195 // Compute the rank of the two types, regardless of whether they are complex.
1196 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1197 if (Order < 0)
1198 // Promote the precision of the LHS if not an assignment.
1199 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1200 /*PromotePrecision=*/!IsCompAssign);
1201 // Promote the precision of the RHS unless it is already the same as the LHS.
1202 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1203 /*PromotePrecision=*/Order > 0);
1204}
1205
1206/// Handle arithmetic conversion from integer to float. Helper function
1207/// of UsualArithmeticConversions()
1209 ExprResult &IntExpr,
1210 QualType FloatTy, QualType IntTy,
1211 bool ConvertFloat, bool ConvertInt) {
1212 if (IntTy->isIntegerType()) {
1213 if (ConvertInt)
1214 // Convert intExpr to the lhs floating point type.
1215 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1216 CK_IntegralToFloating);
1217 return FloatTy;
1218 }
1219
1220 // Convert both sides to the appropriate complex float.
1221 assert(IntTy->isComplexIntegerType());
1222 QualType result = S.Context.getComplexType(FloatTy);
1223
1224 // _Complex int -> _Complex float
1225 if (ConvertInt)
1226 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1227 CK_IntegralComplexToFloatingComplex);
1228
1229 // float -> _Complex float
1230 if (ConvertFloat)
1231 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1232 CK_FloatingRealToComplex);
1233
1234 return result;
1235}
1236
1237/// Handle arithmethic conversion with floating point types. Helper
1238/// function of UsualArithmeticConversions()
1240 ExprResult &RHS, QualType LHSType,
1241 QualType RHSType, bool IsCompAssign) {
1242 bool LHSFloat = LHSType->isRealFloatingType();
1243 bool RHSFloat = RHSType->isRealFloatingType();
1244
1245 // N1169 4.1.4: If one of the operands has a floating type and the other
1246 // operand has a fixed-point type, the fixed-point operand
1247 // is converted to the floating type [...]
1248 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1249 if (LHSFloat)
1250 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1251 else if (!IsCompAssign)
1252 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1253 return LHSFloat ? LHSType : RHSType;
1254 }
1255
1256 // If we have two real floating types, convert the smaller operand
1257 // to the bigger result.
1258 if (LHSFloat && RHSFloat) {
1259 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1260 if (order > 0) {
1261 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1262 return LHSType;
1263 }
1264
1265 assert(order < 0 && "illegal float comparison");
1266 if (!IsCompAssign)
1267 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1268 return RHSType;
1269 }
1270
1271 if (LHSFloat) {
1272 // Half FP has to be promoted to float unless it is natively supported
1273 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1274 LHSType = S.Context.FloatTy;
1275
1276 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1277 /*ConvertFloat=*/!IsCompAssign,
1278 /*ConvertInt=*/ true);
1279 }
1280 assert(RHSFloat);
1281 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1282 /*ConvertFloat=*/ true,
1283 /*ConvertInt=*/!IsCompAssign);
1284}
1285
1286/// Diagnose attempts to convert between __float128, __ibm128 and
1287/// long double if there is no support for such conversion.
1288/// Helper function of UsualArithmeticConversions().
1289static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1290 QualType RHSType) {
1291 // No issue if either is not a floating point type.
1292 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1293 return false;
1294
1295 // No issue if both have the same 128-bit float semantics.
1296 auto *LHSComplex = LHSType->getAs<ComplexType>();
1297 auto *RHSComplex = RHSType->getAs<ComplexType>();
1298
1299 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1300 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1301
1302 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1303 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1304
1305 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1306 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1307 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1308 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1309 return false;
1310
1311 return true;
1312}
1313
1314typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1315
1316namespace {
1317/// These helper callbacks are placed in an anonymous namespace to
1318/// permit their use as function template parameters.
1319ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1320 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1321}
1322
1323ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1324 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1325 CK_IntegralComplexCast);
1326}
1327}
1328
1329/// Handle integer arithmetic conversions. Helper function of
1330/// UsualArithmeticConversions()
1331template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1333 ExprResult &RHS, QualType LHSType,
1334 QualType RHSType, bool IsCompAssign) {
1335 // The rules for this case are in C99 6.3.1.8
1336 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1337 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1338 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1339 if (LHSSigned == RHSSigned) {
1340 // Same signedness; use the higher-ranked type
1341 if (order >= 0) {
1342 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1343 return LHSType;
1344 } else if (!IsCompAssign)
1345 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1346 return RHSType;
1347 } else if (order != (LHSSigned ? 1 : -1)) {
1348 // The unsigned type has greater than or equal rank to the
1349 // signed type, so use the unsigned type
1350 if (RHSSigned) {
1351 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1352 return LHSType;
1353 } else if (!IsCompAssign)
1354 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1355 return RHSType;
1356 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1357 // The two types are different widths; if we are here, that
1358 // means the signed type is larger than the unsigned type, so
1359 // use the signed type.
1360 if (LHSSigned) {
1361 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1362 return LHSType;
1363 } else if (!IsCompAssign)
1364 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1365 return RHSType;
1366 } else {
1367 // The signed type is higher-ranked than the unsigned type,
1368 // but isn't actually any bigger (like unsigned int and long
1369 // on most 32-bit systems). Use the unsigned type corresponding
1370 // to the signed type.
1371 QualType result =
1372 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1373 RHS = (*doRHSCast)(S, RHS.get(), result);
1374 if (!IsCompAssign)
1375 LHS = (*doLHSCast)(S, LHS.get(), result);
1376 return result;
1377 }
1378}
1379
1380/// Handle conversions with GCC complex int extension. Helper function
1381/// of UsualArithmeticConversions()
1383 ExprResult &RHS, QualType LHSType,
1384 QualType RHSType,
1385 bool IsCompAssign) {
1386 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1387 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1388
1389 if (LHSComplexInt && RHSComplexInt) {
1390 QualType LHSEltType = LHSComplexInt->getElementType();
1391 QualType RHSEltType = RHSComplexInt->getElementType();
1392 QualType ScalarType =
1394 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1395
1396 return S.Context.getComplexType(ScalarType);
1397 }
1398
1399 if (LHSComplexInt) {
1400 QualType LHSEltType = LHSComplexInt->getElementType();
1401 QualType ScalarType =
1403 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1405 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1406 CK_IntegralRealToComplex);
1407
1408 return ComplexType;
1409 }
1410
1411 assert(RHSComplexInt);
1412
1413 QualType RHSEltType = RHSComplexInt->getElementType();
1414 QualType ScalarType =
1416 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1418
1419 if (!IsCompAssign)
1420 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1421 CK_IntegralRealToComplex);
1422 return ComplexType;
1423}
1424
1426 ExprResult &RHS,
1427 QualType LHSType,
1428 QualType RHSType,
1429 bool IsCompAssign) {
1430
1431 const auto *LhsOBT = LHSType->getAs<OverflowBehaviorType>();
1432 const auto *RhsOBT = RHSType->getAs<OverflowBehaviorType>();
1433
1434 assert(LHSType->isIntegerType() && RHSType->isIntegerType() &&
1435 "Non-integer type conversion not supported for OverflowBehaviorTypes");
1436
1437 bool LHSHasTrap =
1438 LhsOBT && LhsOBT->getBehaviorKind() ==
1439 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1440 bool RHSHasTrap =
1441 RhsOBT && RhsOBT->getBehaviorKind() ==
1442 OverflowBehaviorType::OverflowBehaviorKind::Trap;
1443 bool LHSHasWrap =
1444 LhsOBT && LhsOBT->getBehaviorKind() ==
1445 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1446 bool RHSHasWrap =
1447 RhsOBT && RhsOBT->getBehaviorKind() ==
1448 OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1449
1450 QualType LHSUnderlyingType = LhsOBT ? LhsOBT->getUnderlyingType() : LHSType;
1451 QualType RHSUnderlyingType = RhsOBT ? RhsOBT->getUnderlyingType() : RHSType;
1452
1453 std::optional<OverflowBehaviorType::OverflowBehaviorKind> DominantBehavior;
1454 if (LHSHasTrap || RHSHasTrap)
1455 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Trap;
1456 else if (LHSHasWrap || RHSHasWrap)
1457 DominantBehavior = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
1458
1459 QualType LHSConvType = LHSUnderlyingType;
1460 QualType RHSConvType = RHSUnderlyingType;
1461 if (DominantBehavior) {
1462 if (!LhsOBT || LhsOBT->getBehaviorKind() != *DominantBehavior)
1463 LHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1464 LHSUnderlyingType);
1465 else
1466 LHSConvType = LHSType;
1467
1468 if (!RhsOBT || RhsOBT->getBehaviorKind() != *DominantBehavior)
1469 RHSConvType = S.Context.getOverflowBehaviorType(*DominantBehavior,
1470 RHSUnderlyingType);
1471 else
1472 RHSConvType = RHSType;
1473 }
1474
1476 S, LHS, RHS, LHSConvType, RHSConvType, IsCompAssign);
1477}
1478
1479/// Return the rank of a given fixed point or integer type. The value itself
1480/// doesn't matter, but the values must be increasing with proper increasing
1481/// rank as described in N1169 4.1.1.
1482static unsigned GetFixedPointRank(QualType Ty) {
1483 const auto *BTy = Ty->getAs<BuiltinType>();
1484 assert(BTy && "Expected a builtin type.");
1485
1486 switch (BTy->getKind()) {
1487 case BuiltinType::ShortFract:
1488 case BuiltinType::UShortFract:
1489 case BuiltinType::SatShortFract:
1490 case BuiltinType::SatUShortFract:
1491 return 1;
1492 case BuiltinType::Fract:
1493 case BuiltinType::UFract:
1494 case BuiltinType::SatFract:
1495 case BuiltinType::SatUFract:
1496 return 2;
1497 case BuiltinType::LongFract:
1498 case BuiltinType::ULongFract:
1499 case BuiltinType::SatLongFract:
1500 case BuiltinType::SatULongFract:
1501 return 3;
1502 case BuiltinType::ShortAccum:
1503 case BuiltinType::UShortAccum:
1504 case BuiltinType::SatShortAccum:
1505 case BuiltinType::SatUShortAccum:
1506 return 4;
1507 case BuiltinType::Accum:
1508 case BuiltinType::UAccum:
1509 case BuiltinType::SatAccum:
1510 case BuiltinType::SatUAccum:
1511 return 5;
1512 case BuiltinType::LongAccum:
1513 case BuiltinType::ULongAccum:
1514 case BuiltinType::SatLongAccum:
1515 case BuiltinType::SatULongAccum:
1516 return 6;
1517 default:
1518 if (BTy->isInteger())
1519 return 0;
1520 llvm_unreachable("Unexpected fixed point or integer type");
1521 }
1522}
1523
1524/// handleFixedPointConversion - Fixed point operations between fixed
1525/// point types and integers or other fixed point types do not fall under
1526/// usual arithmetic conversion since these conversions could result in loss
1527/// of precsision (N1169 4.1.4). These operations should be calculated with
1528/// the full precision of their result type (N1169 4.1.6.2.1).
1530 QualType RHSTy) {
1531 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1532 "Expected at least one of the operands to be a fixed point type");
1533 assert((LHSTy->isFixedPointOrIntegerType() ||
1534 RHSTy->isFixedPointOrIntegerType()) &&
1535 "Special fixed point arithmetic operation conversions are only "
1536 "applied to ints or other fixed point types");
1537
1538 // If one operand has signed fixed-point type and the other operand has
1539 // unsigned fixed-point type, then the unsigned fixed-point operand is
1540 // converted to its corresponding signed fixed-point type and the resulting
1541 // type is the type of the converted operand.
1542 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1544 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1546
1547 // The result type is the type with the highest rank, whereby a fixed-point
1548 // conversion rank is always greater than an integer conversion rank; if the
1549 // type of either of the operands is a saturating fixedpoint type, the result
1550 // type shall be the saturating fixed-point type corresponding to the type
1551 // with the highest rank; the resulting value is converted (taking into
1552 // account rounding and overflow) to the precision of the resulting type.
1553 // Same ranks between signed and unsigned types are resolved earlier, so both
1554 // types are either signed or both unsigned at this point.
1555 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1556 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1557
1558 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1559
1561 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1562
1563 return ResultTy;
1564}
1565
1566/// Check that the usual arithmetic conversions can be performed on this pair of
1567/// expressions that might be of enumeration type.
1569 SourceLocation Loc,
1570 ArithConvKind ACK) {
1571 // C++2a [expr.arith.conv]p1:
1572 // If one operand is of enumeration type and the other operand is of a
1573 // different enumeration type or a floating-point type, this behavior is
1574 // deprecated ([depr.arith.conv.enum]).
1575 //
1576 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1577 // Eventually we will presumably reject these cases (in C++23 onwards?).
1579 R = RHS->getEnumCoercedType(Context);
1580 bool LEnum = L->isUnscopedEnumerationType(),
1581 REnum = R->isUnscopedEnumerationType();
1582 bool IsCompAssign = ACK == ArithConvKind::CompAssign;
1583 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1584 (REnum && L->isFloatingType())) {
1585 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1587 ? diag::warn_arith_conv_enum_float_cxx20
1588 : diag::warn_arith_conv_enum_float)
1589 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1590 << L << R;
1591 } else if (!IsCompAssign && LEnum && REnum &&
1592 !Context.hasSameUnqualifiedType(L, R)) {
1593 unsigned DiagID;
1594 // In C++ 26, usual arithmetic conversions between 2 different enum types
1595 // are ill-formed.
1597 DiagID = diag::warn_conv_mixed_enum_types_cxx26;
1598 else if (!L->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage() ||
1599 !R->castAsCanonical<EnumType>()->getDecl()->hasNameForLinkage()) {
1600 // If either enumeration type is unnamed, it's less likely that the
1601 // user cares about this, but this situation is still deprecated in
1602 // C++2a. Use a different warning group.
1603 DiagID = getLangOpts().CPlusPlus20
1604 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1605 : diag::warn_arith_conv_mixed_anon_enum_types;
1606 } else if (ACK == ArithConvKind::Conditional) {
1607 // Conditional expressions are separated out because they have
1608 // historically had a different warning flag.
1609 DiagID = getLangOpts().CPlusPlus20
1610 ? diag::warn_conditional_mixed_enum_types_cxx20
1611 : diag::warn_conditional_mixed_enum_types;
1612 } else if (ACK == ArithConvKind::Comparison) {
1613 // Comparison expressions are separated out because they have
1614 // historically had a different warning flag.
1615 DiagID = getLangOpts().CPlusPlus20
1616 ? diag::warn_comparison_mixed_enum_types_cxx20
1617 : diag::warn_comparison_mixed_enum_types;
1618 } else {
1619 DiagID = getLangOpts().CPlusPlus20
1620 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1621 : diag::warn_arith_conv_mixed_enum_types;
1622 }
1623 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1624 << (int)ACK << L << R;
1625 }
1626}
1627
1629 Expr *RHS, SourceLocation Loc,
1630 ArithConvKind ACK) {
1631 QualType LHSType = LHS->getType().getUnqualifiedType();
1632 QualType RHSType = RHS->getType().getUnqualifiedType();
1633
1634 if (!SemaRef.getLangOpts().CPlusPlus || !LHSType->isUnicodeCharacterType() ||
1635 !RHSType->isUnicodeCharacterType())
1636 return;
1637
1638 if (ACK == ArithConvKind::Comparison) {
1639 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1640 return;
1641
1642 auto IsSingleCodeUnitCP = [](const QualType &T, const llvm::APSInt &Value) {
1643 if (T->isChar8Type())
1644 return llvm::IsSingleCodeUnitUTF8Codepoint(Value.getExtValue());
1645 if (T->isChar16Type())
1646 return llvm::IsSingleCodeUnitUTF16Codepoint(Value.getExtValue());
1647 assert(T->isChar32Type());
1648 return llvm::IsSingleCodeUnitUTF32Codepoint(Value.getExtValue());
1649 };
1650
1651 Expr::EvalResult LHSRes, RHSRes;
1652 bool LHSSuccess = LHS->EvaluateAsInt(LHSRes, SemaRef.getASTContext(),
1654 SemaRef.isConstantEvaluatedContext());
1655 bool RHSuccess = RHS->EvaluateAsInt(RHSRes, SemaRef.getASTContext(),
1657 SemaRef.isConstantEvaluatedContext());
1658
1659 // Don't warn if the one known value is a representable
1660 // in the type of both expressions.
1661 if (LHSSuccess != RHSuccess) {
1662 Expr::EvalResult &Res = LHSSuccess ? LHSRes : RHSRes;
1663 if (IsSingleCodeUnitCP(LHSType, Res.Val.getInt()) &&
1664 IsSingleCodeUnitCP(RHSType, Res.Val.getInt()))
1665 return;
1666 }
1667
1668 if (!LHSSuccess || !RHSuccess) {
1669 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types)
1670 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType
1671 << RHSType;
1672 return;
1673 }
1674
1675 llvm::APSInt LHSValue(32);
1676 LHSValue = LHSRes.Val.getInt();
1677 llvm::APSInt RHSValue(32);
1678 RHSValue = RHSRes.Val.getInt();
1679
1680 bool LHSSafe = IsSingleCodeUnitCP(LHSType, LHSValue);
1681 bool RHSSafe = IsSingleCodeUnitCP(RHSType, RHSValue);
1682 if (LHSSafe && RHSSafe)
1683 return;
1684
1685 SemaRef.Diag(Loc, diag::warn_comparison_unicode_mixed_types_constant)
1686 << LHS->getSourceRange() << RHS->getSourceRange() << LHSType << RHSType
1687 << FormatUTFCodeUnitAsCodepoint(LHSValue.getExtValue(), LHSType)
1688 << FormatUTFCodeUnitAsCodepoint(RHSValue.getExtValue(), RHSType);
1689 return;
1690 }
1691
1692 if (SemaRef.getASTContext().hasSameType(LHSType, RHSType))
1693 return;
1694
1695 SemaRef.Diag(Loc, diag::warn_arith_conv_mixed_unicode_types)
1696 << LHS->getSourceRange() << RHS->getSourceRange() << ACK << LHSType
1697 << RHSType;
1698}
1699
1700/// UsualArithmeticConversions - Performs various conversions that are common to
1701/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1702/// routine returns the first non-arithmetic type found. The client is
1703/// responsible for emitting appropriate error diagnostics.
1705 SourceLocation Loc,
1706 ArithConvKind ACK) {
1707
1708 checkEnumArithmeticConversions(LHS.get(), RHS.get(), Loc, ACK);
1709
1710 CheckUnicodeArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1711
1712 if (ACK != ArithConvKind::CompAssign) {
1713 LHS = UsualUnaryConversions(LHS.get());
1714 if (LHS.isInvalid())
1715 return QualType();
1716 }
1717
1718 RHS = UsualUnaryConversions(RHS.get());
1719 if (RHS.isInvalid())
1720 return QualType();
1721
1722 // For conversion purposes, we ignore any qualifiers.
1723 // For example, "const float" and "float" are equivalent.
1724 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1725 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1726
1727 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1728 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1729 LHSType = AtomicLHS->getValueType();
1730
1731 // If both types are identical, no conversion is needed.
1732 if (Context.hasSameType(LHSType, RHSType))
1733 return Context.getCommonSugaredType(LHSType, RHSType);
1734
1735 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1736 // The caller can deal with this (e.g. pointer + int).
1737 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1738 return QualType();
1739
1740 // Apply unary and bitfield promotions to the LHS's type.
1741 QualType LHSUnpromotedType = LHSType;
1742 if (Context.isPromotableIntegerType(LHSType))
1743 LHSType = Context.getPromotedIntegerType(LHSType);
1744 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1745 if (!LHSBitfieldPromoteTy.isNull())
1746 LHSType = LHSBitfieldPromoteTy;
1747 if (LHSType != LHSUnpromotedType && ACK != ArithConvKind::CompAssign)
1748 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1749
1750 // If both types are identical, no conversion is needed.
1751 if (Context.hasSameType(LHSType, RHSType))
1752 return Context.getCommonSugaredType(LHSType, RHSType);
1753
1754 // At this point, we have two different arithmetic types.
1755
1756 // Diagnose attempts to convert between __ibm128, __float128 and long double
1757 // where such conversions currently can't be handled.
1758 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1759 return QualType();
1760
1761 // Handle complex types first (C99 6.3.1.8p1).
1762 if (LHSType->isComplexType() || RHSType->isComplexType())
1763 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1765
1766 // Now handle "real" floating types (i.e. float, double, long double).
1767 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1768 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1770
1771 // Handle GCC complex int extension.
1772 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1773 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1775
1776 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1777 return handleFixedPointConversion(*this, LHSType, RHSType);
1778
1779 if (LHSType->isOverflowBehaviorType() || RHSType->isOverflowBehaviorType())
1781 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1782
1783 // Finally, we have two differing integer types.
1785 *this, LHS, RHS, LHSType, RHSType, ACK == ArithConvKind::CompAssign);
1786}
1787
1788//===----------------------------------------------------------------------===//
1789// Semantic Analysis for various Expression Types
1790//===----------------------------------------------------------------------===//
1791
1792
1794 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1795 bool PredicateIsExpr, void *ControllingExprOrType,
1796 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1797 unsigned NumAssocs = ArgTypes.size();
1798 assert(NumAssocs == ArgExprs.size());
1799
1800 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1801 for (unsigned i = 0; i < NumAssocs; ++i) {
1802 if (ArgTypes[i])
1803 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1804 else
1805 Types[i] = nullptr;
1806 }
1807
1808 // If we have a controlling type, we need to convert it from a parsed type
1809 // into a semantic type and then pass that along.
1810 if (!PredicateIsExpr) {
1811 TypeSourceInfo *ControllingType;
1812 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1813 &ControllingType);
1814 assert(ControllingType && "couldn't get the type out of the parser");
1815 ControllingExprOrType = ControllingType;
1816 }
1817
1819 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1820 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1821 delete [] Types;
1822 return ER;
1823}
1824
1825// Helper function to determine type compatibility for C _Generic expressions.
1826// Multiple compatible types within the same _Generic expression is ambiguous
1827// and not valid.
1829 QualType U) {
1830 // Try to handle special types like OverflowBehaviorTypes
1831 const auto *TOBT = T->getAs<OverflowBehaviorType>();
1832 const auto *UOBT = U.getCanonicalType()->getAs<OverflowBehaviorType>();
1833
1834 if (TOBT || UOBT) {
1835 if (TOBT && UOBT) {
1836 if (TOBT->getBehaviorKind() == UOBT->getBehaviorKind())
1837 return Ctx.typesAreCompatible(TOBT->getUnderlyingType(),
1838 UOBT->getUnderlyingType());
1839 return false;
1840 }
1841 return false;
1842 }
1843
1844 // We're dealing with types that don't require special handling.
1845 return Ctx.typesAreCompatible(T, U);
1846}
1847
1849 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1850 bool PredicateIsExpr, void *ControllingExprOrType,
1852 unsigned NumAssocs = Types.size();
1853 assert(NumAssocs == Exprs.size());
1854 assert(ControllingExprOrType &&
1855 "Must have either a controlling expression or a controlling type");
1856
1857 Expr *ControllingExpr = nullptr;
1858 TypeSourceInfo *ControllingType = nullptr;
1859 if (PredicateIsExpr) {
1860 // Decay and strip qualifiers for the controlling expression type, and
1861 // handle placeholder type replacement. See committee discussion from WG14
1862 // DR423.
1866 reinterpret_cast<Expr *>(ControllingExprOrType));
1867 if (R.isInvalid())
1868 return ExprError();
1869 ControllingExpr = R.get();
1870 } else {
1871 // The extension form uses the type directly rather than converting it.
1872 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1873 if (!ControllingType)
1874 return ExprError();
1875 }
1876
1877 bool TypeErrorFound = false,
1878 IsResultDependent = ControllingExpr
1879 ? ControllingExpr->isTypeDependent()
1880 : ControllingType->getType()->isDependentType(),
1881 ContainsUnexpandedParameterPack =
1882 ControllingExpr
1883 ? ControllingExpr->containsUnexpandedParameterPack()
1884 : ControllingType->getType()->containsUnexpandedParameterPack();
1885
1886 // The controlling expression is an unevaluated operand, so side effects are
1887 // likely unintended.
1888 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1889 ControllingExpr->HasSideEffects(Context, false))
1890 Diag(ControllingExpr->getExprLoc(),
1891 diag::warn_side_effects_unevaluated_context);
1892
1893 for (unsigned i = 0; i < NumAssocs; ++i) {
1894 if (Exprs[i]->containsUnexpandedParameterPack())
1895 ContainsUnexpandedParameterPack = true;
1896
1897 if (Types[i]) {
1898 if (Types[i]->getType()->containsUnexpandedParameterPack())
1899 ContainsUnexpandedParameterPack = true;
1900
1901 if (Types[i]->getType()->isDependentType()) {
1902 IsResultDependent = true;
1903 } else {
1904 // We relax the restriction on use of incomplete types and non-object
1905 // types with the type-based extension of _Generic. Allowing incomplete
1906 // objects means those can be used as "tags" for a type-safe way to map
1907 // to a value. Similarly, matching on function types rather than
1908 // function pointer types can be useful. However, the restriction on VM
1909 // types makes sense to retain as there are open questions about how
1910 // the selection can be made at compile time.
1911 //
1912 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1913 // complete object type other than a variably modified type."
1914 // C2y removed the requirement that an expression form must
1915 // use a complete type, though it's still as-if the type has undergone
1916 // lvalue conversion. We support this as an extension in C23 and
1917 // earlier because GCC does so.
1918 unsigned D = 0;
1919 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1920 D = LangOpts.C2y ? diag::warn_c2y_compat_assoc_type_incomplete
1921 : diag::ext_assoc_type_incomplete;
1922 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1923 D = diag::err_assoc_type_nonobject;
1924 else if (Types[i]->getType()->isVariablyModifiedType())
1925 D = diag::err_assoc_type_variably_modified;
1926 else if (ControllingExpr) {
1927 // Because the controlling expression undergoes lvalue conversion,
1928 // array conversion, and function conversion, an association which is
1929 // of array type, function type, or is qualified can never be
1930 // reached. We will warn about this so users are less surprised by
1931 // the unreachable association. However, we don't have to handle
1932 // function types; that's not an object type, so it's handled above.
1933 //
1934 // The logic is somewhat different for C++ because C++ has different
1935 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1936 // If T is a non-class type, the type of the prvalue is the cv-
1937 // unqualified version of T. Otherwise, the type of the prvalue is T.
1938 // The result of these rules is that all qualified types in an
1939 // association in C are unreachable, and in C++, only qualified non-
1940 // class types are unreachable.
1941 //
1942 // NB: this does not apply when the first operand is a type rather
1943 // than an expression, because the type form does not undergo
1944 // conversion.
1945 unsigned Reason = 0;
1946 QualType QT = Types[i]->getType();
1947 if (QT->isArrayType())
1948 Reason = 1;
1949 else if (QT.hasQualifiers() &&
1950 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1951 Reason = 2;
1952
1953 if (Reason)
1954 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1955 diag::warn_unreachable_association)
1956 << QT << (Reason - 1);
1957 }
1958
1959 if (D != 0) {
1960 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1961 << Types[i]->getTypeLoc().getSourceRange() << Types[i]->getType();
1962 if (getDiagnostics().getDiagnosticLevel(
1963 D, Types[i]->getTypeLoc().getBeginLoc()) >=
1965 TypeErrorFound = true;
1966 }
1967
1968 // C11 6.5.1.1p2 "No two generic associations in the same generic
1969 // selection shall specify compatible types."
1970 for (unsigned j = i+1; j < NumAssocs; ++j)
1971 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1973 Types[j]->getType())) {
1974 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1975 diag::err_assoc_compatible_types)
1976 << Types[j]->getTypeLoc().getSourceRange()
1977 << Types[j]->getType()
1978 << Types[i]->getType();
1979 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1980 diag::note_compat_assoc)
1981 << Types[i]->getTypeLoc().getSourceRange()
1982 << Types[i]->getType();
1983 TypeErrorFound = true;
1984 }
1985 }
1986 }
1987 }
1988 if (TypeErrorFound)
1989 return ExprError();
1990
1991 // If we determined that the generic selection is result-dependent, don't
1992 // try to compute the result expression.
1993 if (IsResultDependent) {
1994 if (ControllingExpr)
1995 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1996 Types, Exprs, DefaultLoc, RParenLoc,
1997 ContainsUnexpandedParameterPack);
1998 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1999 Exprs, DefaultLoc, RParenLoc,
2000 ContainsUnexpandedParameterPack);
2001 }
2002
2003 SmallVector<unsigned, 1> CompatIndices;
2004 unsigned DefaultIndex = std::numeric_limits<unsigned>::max();
2005 // Look at the canonical type of the controlling expression in case it was a
2006 // deduced type like __auto_type. However, when issuing diagnostics, use the
2007 // type the user wrote in source rather than the canonical one.
2008 for (unsigned i = 0; i < NumAssocs; ++i) {
2009 if (!Types[i])
2010 DefaultIndex = i;
2011 else {
2012 bool Compatible;
2013 QualType ControllingQT =
2014 ControllingExpr ? ControllingExpr->getType().getCanonicalType()
2015 : ControllingType->getType().getCanonicalType();
2016 QualType AssocQT = Types[i]->getType();
2017
2018 Compatible =
2019 areTypesCompatibleForGeneric(Context, ControllingQT, AssocQT);
2020
2021 if (Compatible)
2022 CompatIndices.push_back(i);
2023 }
2024 }
2025
2026 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
2027 TypeSourceInfo *ControllingType) {
2028 // We strip parens here because the controlling expression is typically
2029 // parenthesized in macro definitions.
2030 if (ControllingExpr)
2031 ControllingExpr = ControllingExpr->IgnoreParens();
2032
2033 SourceRange SR = ControllingExpr
2034 ? ControllingExpr->getSourceRange()
2035 : ControllingType->getTypeLoc().getSourceRange();
2036 QualType QT = ControllingExpr ? ControllingExpr->getType()
2037 : ControllingType->getType();
2038
2039 return std::make_pair(SR, QT);
2040 };
2041
2042 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
2043 // type compatible with at most one of the types named in its generic
2044 // association list."
2045 if (CompatIndices.size() > 1) {
2046 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2047 SourceRange SR = P.first;
2048 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
2049 << SR << P.second << (unsigned)CompatIndices.size();
2050 for (unsigned I : CompatIndices) {
2051 Diag(Types[I]->getTypeLoc().getBeginLoc(),
2052 diag::note_compat_assoc)
2053 << Types[I]->getTypeLoc().getSourceRange()
2054 << Types[I]->getType();
2055 }
2056 return ExprError();
2057 }
2058
2059 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
2060 // its controlling expression shall have type compatible with exactly one of
2061 // the types named in its generic association list."
2062 if (DefaultIndex == std::numeric_limits<unsigned>::max() &&
2063 CompatIndices.size() == 0) {
2064 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
2065 SourceRange SR = P.first;
2066 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
2067 return ExprError();
2068 }
2069
2070 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
2071 // type name that is compatible with the type of the controlling expression,
2072 // then the result expression of the generic selection is the expression
2073 // in that generic association. Otherwise, the result expression of the
2074 // generic selection is the expression in the default generic association."
2075 unsigned ResultIndex =
2076 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
2077
2078 if (ControllingExpr) {
2080 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
2081 ContainsUnexpandedParameterPack, ResultIndex);
2082 }
2084 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
2085 ContainsUnexpandedParameterPack, ResultIndex);
2086}
2087
2089 switch (Kind) {
2090 default:
2091 llvm_unreachable("unexpected TokenKind");
2092 case tok::kw___func__:
2093 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
2094 case tok::kw___FUNCTION__:
2096 case tok::kw___FUNCDNAME__:
2097 return PredefinedIdentKind::FuncDName; // [MS]
2098 case tok::kw___FUNCSIG__:
2099 return PredefinedIdentKind::FuncSig; // [MS]
2100 case tok::kw_L__FUNCTION__:
2101 return PredefinedIdentKind::LFunction; // [MS]
2102 case tok::kw_L__FUNCSIG__:
2103 return PredefinedIdentKind::LFuncSig; // [MS]
2104 case tok::kw___PRETTY_FUNCTION__:
2106 }
2107}
2108
2109/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
2110/// to determine the value of a PredefinedExpr. This can be either a
2111/// block, lambda, captured statement, function, otherwise a nullptr.
2114 DC = DC->getParent();
2115 return cast_or_null<Decl>(DC);
2116}
2117
2118/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
2119/// location of the token and the offset of the ud-suffix within it.
2121 unsigned Offset) {
2122 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
2123 S.getLangOpts());
2124}
2125
2126/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
2127/// the corresponding cooked (non-raw) literal operator, and build a call to it.
2129 IdentifierInfo *UDSuffix,
2130 SourceLocation UDSuffixLoc,
2131 ArrayRef<Expr*> Args,
2132 SourceLocation LitEndLoc) {
2133 assert(Args.size() <= 2 && "too many arguments for literal operator");
2134
2135 QualType ArgTy[2];
2136 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2137 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
2138 if (ArgTy[ArgIdx]->isArrayType())
2139 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
2140 }
2141
2142 DeclarationName OpName =
2144 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2145 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2146
2147 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
2148 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
2149 /*AllowRaw*/ false, /*AllowTemplate*/ false,
2150 /*AllowStringTemplatePack*/ false,
2151 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
2152 return ExprError();
2153
2154 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
2155}
2156
2158 // StringToks needs backing storage as it doesn't hold array elements itself
2159 std::vector<Token> ExpandedToks;
2160 if (getLangOpts().MicrosoftExt)
2161 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2162
2163 StringLiteralParser Literal(StringToks, PP,
2165 if (Literal.hadError)
2166 return ExprError();
2167
2168 SmallVector<SourceLocation, 4> StringTokLocs;
2169 for (const Token &Tok : StringToks)
2170 StringTokLocs.push_back(Tok.getLocation());
2171
2172 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2174 false, {}, StringTokLocs);
2175
2176 if (!Literal.getUDSuffix().empty()) {
2177 SourceLocation UDSuffixLoc =
2178 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2179 Literal.getUDSuffixOffset());
2180 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2181 }
2182
2183 return Lit;
2184}
2185
2186std::vector<Token>
2188 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2189 // local macros that expand to string literals that may be concatenated.
2190 // These macros are expanded here (in Sema), because StringLiteralParser
2191 // (in Lex) doesn't know the enclosing function (because it hasn't been
2192 // parsed yet).
2193 assert(getLangOpts().MicrosoftExt);
2194
2195 // Note: Although function local macros are defined only inside functions,
2196 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2197 // expansion of macros into empty string literals without additional checks.
2198 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2199 if (!CurrentDecl)
2200 CurrentDecl = Context.getTranslationUnitDecl();
2201
2202 std::vector<Token> ExpandedToks;
2203 ExpandedToks.reserve(Toks.size());
2204 for (const Token &Tok : Toks) {
2206 assert(tok::isStringLiteral(Tok.getKind()));
2207 ExpandedToks.emplace_back(Tok);
2208 continue;
2209 }
2210 if (isa<TranslationUnitDecl>(CurrentDecl))
2211 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2212 // Stringify predefined expression
2213 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2214 << Tok.getKind();
2215 SmallString<64> Str;
2216 llvm::raw_svector_ostream OS(Str);
2217 Token &Exp = ExpandedToks.emplace_back();
2218 Exp.startToken();
2219 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2220 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2221 OS << 'L';
2222 Exp.setKind(tok::wide_string_literal);
2223 } else {
2224 Exp.setKind(tok::string_literal);
2225 }
2226 OS << '"'
2228 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2229 << '"';
2230 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2231 }
2232 return ExpandedToks;
2233}
2234
2237 assert(!StringToks.empty() && "Must have at least one string!");
2238
2239 // StringToks needs backing storage as it doesn't hold array elements itself
2240 std::vector<Token> ExpandedToks;
2241 if (getLangOpts().MicrosoftExt)
2242 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2243
2244 StringLiteralParser Literal(StringToks, PP);
2245 if (Literal.hadError)
2246 return ExprError();
2247
2248 SmallVector<SourceLocation, 4> StringTokLocs;
2249 for (const Token &Tok : StringToks)
2250 StringTokLocs.push_back(Tok.getLocation());
2251
2252 QualType CharTy = Context.CharTy;
2254 if (Literal.isWide()) {
2255 CharTy = Context.getWideCharType();
2257 } else if (Literal.isUTF8()) {
2258 if (getLangOpts().Char8)
2259 CharTy = Context.Char8Ty;
2260 else if (getLangOpts().C23)
2261 CharTy = Context.UnsignedCharTy;
2263 } else if (Literal.isUTF16()) {
2264 CharTy = Context.Char16Ty;
2266 } else if (Literal.isUTF32()) {
2267 CharTy = Context.Char32Ty;
2269 } else if (Literal.isPascal()) {
2270 CharTy = Context.UnsignedCharTy;
2271 }
2272
2273 // Warn on u8 string literals before C++20 and C23, whose type
2274 // was an array of char before but becomes an array of char8_t.
2275 // In C++20, it cannot be used where a pointer to char is expected.
2276 // In C23, it might have an unexpected value if char was signed.
2277 if (Kind == StringLiteralKind::UTF8 &&
2279 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2280 : !getLangOpts().C23)) {
2281 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2282 ? diag::warn_cxx20_compat_utf8_string
2283 : diag::warn_c23_compat_utf8_string);
2284
2285 // Create removals for all 'u8' prefixes in the string literal(s). This
2286 // ensures C++20/C23 compatibility (but may change the program behavior when
2287 // built by non-Clang compilers for which the execution character set is
2288 // not always UTF-8).
2289 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2290 SourceLocation RemovalDiagLoc;
2291 for (const Token &Tok : StringToks) {
2292 if (Tok.getKind() == tok::utf8_string_literal) {
2293 if (RemovalDiagLoc.isInvalid())
2294 RemovalDiagLoc = Tok.getLocation();
2296 Tok.getLocation(),
2297 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2299 }
2300 }
2301 Diag(RemovalDiagLoc, RemovalDiag);
2302 }
2303
2304 QualType StrTy =
2305 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2306
2307 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2309 Context, Literal.GetString(), Kind, Literal.Pascal, StrTy, StringTokLocs);
2310 if (Literal.getUDSuffix().empty())
2311 return Lit;
2312
2313 // We're building a user-defined literal.
2314 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2315 SourceLocation UDSuffixLoc =
2316 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2317 Literal.getUDSuffixOffset());
2318
2319 // Make sure we're allowed user-defined literals here.
2320 if (!UDLScope)
2321 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2322
2323 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2324 // operator "" X (str, len)
2325 QualType SizeType = Context.getSizeType();
2326
2327 DeclarationName OpName =
2328 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2329 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2330 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2331
2332 QualType ArgTy[] = {
2333 Context.getArrayDecayedType(StrTy), SizeType
2334 };
2335
2336 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2337 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2338 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2339 /*AllowStringTemplatePack*/ true,
2340 /*DiagnoseMissing*/ true, Lit)) {
2341
2342 case LOLR_Cooked: {
2343 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2344 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2345 StringTokLocs[0]);
2346 Expr *Args[] = { Lit, LenArg };
2347
2348 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2349 }
2350
2351 case LOLR_Template: {
2352 TemplateArgumentListInfo ExplicitArgs;
2353 TemplateArgument Arg(Lit, /*IsCanonical=*/false);
2354 TemplateArgumentLocInfo ArgInfo(Lit);
2355 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2356 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2357 &ExplicitArgs);
2358 }
2359
2361 TemplateArgumentListInfo ExplicitArgs;
2362
2363 unsigned CharBits = Context.getIntWidth(CharTy);
2364 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2365 llvm::APSInt Value(CharBits, CharIsUnsigned);
2366
2367 TemplateArgument TypeArg(CharTy);
2368 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
2369 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2370
2371 SourceLocation Loc = StringTokLocs.back();
2372 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2373 Value = Lit->getCodeUnit(I);
2374 TemplateArgument Arg(Context, Value, CharTy);
2376 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2377 }
2378 return BuildLiteralOperatorCall(R, OpNameInfo, {}, Loc, &ExplicitArgs);
2379 }
2380 case LOLR_Raw:
2382 llvm_unreachable("unexpected literal operator lookup result");
2383 case LOLR_Error:
2384 return ExprError();
2385 }
2386 llvm_unreachable("unexpected literal operator lookup result");
2387}
2388
2391 SourceLocation Loc,
2392 const CXXScopeSpec *SS) {
2393 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2394 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2395}
2396
2399 const DeclarationNameInfo &NameInfo,
2400 const CXXScopeSpec *SS, NamedDecl *FoundD,
2401 SourceLocation TemplateKWLoc,
2402 const TemplateArgumentListInfo *TemplateArgs) {
2405 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2406 TemplateArgs);
2407}
2408
2409// CUDA/HIP: Check whether a captured reference variable is referencing a
2410// host variable in a device or host device lambda.
2412 VarDecl *VD) {
2413 if (!S.getLangOpts().CUDA || !VD->hasInit())
2414 return false;
2415 assert(VD->getType()->isReferenceType());
2416
2417 // Check whether the reference variable is referencing a host variable.
2418 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2419 if (!DRE)
2420 return false;
2421 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2422 if (!Referee || !Referee->hasGlobalStorage() ||
2423 Referee->hasAttr<CUDADeviceAttr>())
2424 return false;
2425
2426 // Check whether the current function is a device or host device lambda.
2427 // Check whether the reference variable is a capture by getDeclContext()
2428 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2429 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2430 if (MD && MD->getParent()->isLambda() &&
2431 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2432 VD->getDeclContext() != MD)
2433 return true;
2434
2435 return false;
2436}
2437
2439 // A declaration named in an unevaluated operand never constitutes an odr-use.
2441 return NOUR_Unevaluated;
2442
2443 // C++2a [basic.def.odr]p4:
2444 // A variable x whose name appears as a potentially-evaluated expression e
2445 // is odr-used by e unless [...] x is a reference that is usable in
2446 // constant expressions.
2447 // CUDA/HIP:
2448 // If a reference variable referencing a host variable is captured in a
2449 // device or host device lambda, the value of the referee must be copied
2450 // to the capture and the reference variable must be treated as odr-use
2451 // since the value of the referee is not known at compile time and must
2452 // be loaded from the captured.
2453 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2454 if (VD->getType()->isReferenceType() &&
2455 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2457 VD->isUsableInConstantExpressions(Context))
2458 return NOUR_Constant;
2459 }
2460
2461 // All remaining non-variable cases constitute an odr-use. For variables, we
2462 // need to wait and see how the expression is used.
2463 return NOUR_None;
2464}
2465
2468 const DeclarationNameInfo &NameInfo,
2469 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2470 SourceLocation TemplateKWLoc,
2471 const TemplateArgumentListInfo *TemplateArgs) {
2472 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2473 NeedToCaptureVariable(D, NameInfo.getLoc());
2474
2476 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2477 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2479
2480 // C++ [except.spec]p17:
2481 // An exception-specification is considered to be needed when:
2482 // - in an expression, the function is the unique lookup result or
2483 // the selected member of a set of overloaded functions.
2484 //
2485 // We delay doing this until after we've built the function reference and
2486 // marked it as used so that:
2487 // a) if the function is defaulted, we get errors from defining it before /
2488 // instead of errors from computing its exception specification, and
2489 // b) if the function is a defaulted comparison, we can use the body we
2490 // build when defining it as input to the exception specification
2491 // computation rather than computing a new body.
2492 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2493 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2494 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2495 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2496 }
2497 }
2498
2499 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2501 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2503
2504 const auto *FD = dyn_cast<FieldDecl>(D);
2505 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2506 FD = IFD->getAnonField();
2507 if (FD) {
2508 UnusedPrivateFields.remove(FD);
2509 // Just in case we're building an illegal pointer-to-member.
2510 if (FD->isBitField())
2512 }
2513
2514 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2515 // designates a bit-field.
2516 if (const auto *BD = dyn_cast<BindingDecl>(D))
2517 if (const auto *BE = BD->getBinding())
2518 E->setObjectKind(BE->getObjectKind());
2519
2520 return E;
2521}
2522
2523void
2526 DeclarationNameInfo &NameInfo,
2527 const TemplateArgumentListInfo *&TemplateArgs) {
2529 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2530 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2531
2532 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2533 Id.TemplateId->NumArgs);
2534 translateTemplateArguments(TemplateArgsPtr, Buffer);
2535
2536 TemplateName TName = Id.TemplateId->Template.get();
2538 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2539 TemplateArgs = &Buffer;
2540 } else {
2541 NameInfo = GetNameFromUnqualifiedId(Id);
2542 TemplateArgs = nullptr;
2543 }
2544}
2545
2547 // During a default argument instantiation the CurContext points
2548 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2549 // function parameter list, hence add an explicit check.
2550 bool isDefaultArgument =
2551 !CodeSynthesisContexts.empty() &&
2552 CodeSynthesisContexts.back().Kind ==
2554 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2555 bool isInstance = CurMethod && CurMethod->isInstance() &&
2556 R.getNamingClass() == CurMethod->getParent() &&
2557 !isDefaultArgument;
2558
2559 // There are two ways we can find a class-scope declaration during template
2560 // instantiation that we did not find in the template definition: if it is a
2561 // member of a dependent base class, or if it is declared after the point of
2562 // use in the same class. Distinguish these by comparing the class in which
2563 // the member was found to the naming class of the lookup.
2564 unsigned DiagID = diag::err_found_in_dependent_base;
2565 unsigned NoteID = diag::note_member_declared_at;
2566 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
2567 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2568 : diag::err_found_later_in_class;
2569 } else if (getLangOpts().MSVCCompat) {
2570 DiagID = diag::ext_found_in_dependent_base;
2571 NoteID = diag::note_dependent_member_use;
2572 }
2573
2574 if (isInstance) {
2575 // Give a code modification hint to insert 'this->'.
2576 Diag(R.getNameLoc(), DiagID)
2577 << R.getLookupName()
2578 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2579 CheckCXXThisCapture(R.getNameLoc());
2580 } else {
2581 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2582 // they're not shadowed).
2583 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2584 }
2585
2586 for (const NamedDecl *D : R)
2587 Diag(D->getLocation(), NoteID);
2588
2589 // Return true if we are inside a default argument instantiation
2590 // and the found name refers to an instance member function, otherwise
2591 // the caller will try to create an implicit member call and this is wrong
2592 // for default arguments.
2593 //
2594 // FIXME: Is this special case necessary? We could allow the caller to
2595 // diagnose this.
2596 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2597 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2598 return true;
2599 }
2600
2601 // Tell the callee to try to recover.
2602 return false;
2603}
2604
2607 TemplateArgumentListInfo *ExplicitTemplateArgs,
2608 ArrayRef<Expr *> Args, DeclContext *LookupCtx) {
2609 DeclarationName Name = R.getLookupName();
2610 SourceRange NameRange = R.getLookupNameInfo().getSourceRange();
2611
2612 unsigned diagnostic = diag::err_undeclared_var_use;
2613 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2617 diagnostic = diag::err_undeclared_use;
2618 diagnostic_suggest = diag::err_undeclared_use_suggest;
2619 }
2620
2621 // If the original lookup was an unqualified lookup, fake an
2622 // unqualified lookup. This is useful when (for example) the
2623 // original lookup would not have found something because it was a
2624 // dependent name.
2625 DeclContext *DC =
2626 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2627 while (DC) {
2628 if (isa<CXXRecordDecl>(DC)) {
2629 if (ExplicitTemplateArgs) {
2631 R, S, SS, Context.getCanonicalTagType(cast<CXXRecordDecl>(DC)),
2632 /*EnteringContext*/ false, TemplateNameIsRequired,
2633 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2634 return true;
2635 } else {
2636 LookupQualifiedName(R, DC);
2637 }
2638
2639 if (!R.empty()) {
2640 // Don't give errors about ambiguities in this lookup.
2641 R.suppressDiagnostics();
2642
2643 // If there's a best viable function among the results, only mention
2644 // that one in the notes.
2645 OverloadCandidateSet Candidates(R.getNameLoc(),
2647 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2649 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2650 OR_Success) {
2651 R.clear();
2652 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2653 R.resolveKind();
2654 }
2655
2657 }
2658
2659 R.clear();
2660 }
2661
2662 DC = DC->getLookupParent();
2663 }
2664
2665 // We didn't find anything, so try to correct for a typo.
2666 TypoCorrection Corrected;
2667 if (S && (Corrected =
2668 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
2669 CCC, CorrectTypoKind::ErrorRecovery, LookupCtx))) {
2670 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2671 bool DroppedSpecifier =
2672 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2673 R.setLookupName(Corrected.getCorrection());
2674
2675 bool AcceptableWithRecovery = false;
2676 bool AcceptableWithoutRecovery = false;
2677 NamedDecl *ND = Corrected.getFoundDecl();
2678 if (ND) {
2679 if (Corrected.isOverloaded()) {
2680 OverloadCandidateSet OCS(R.getNameLoc(),
2683 for (NamedDecl *CD : Corrected) {
2684 if (FunctionTemplateDecl *FTD =
2685 dyn_cast<FunctionTemplateDecl>(CD))
2687 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2688 Args, OCS);
2689 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2690 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2692 Args, OCS);
2693 }
2694 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2695 case OR_Success:
2696 ND = Best->FoundDecl;
2697 Corrected.setCorrectionDecl(ND);
2698 break;
2699 default:
2700 // FIXME: Arbitrarily pick the first declaration for the note.
2701 Corrected.setCorrectionDecl(ND);
2702 break;
2703 }
2704 }
2705 R.addDecl(ND);
2706 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2709 if (!Record)
2712 R.setNamingClass(Record);
2713 }
2714
2715 auto *UnderlyingND = ND->getUnderlyingDecl();
2716 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2717 isa<FunctionTemplateDecl>(UnderlyingND);
2718 // FIXME: If we ended up with a typo for a type name or
2719 // Objective-C class name, we're in trouble because the parser
2720 // is in the wrong place to recover. Suggest the typo
2721 // correction, but don't make it a fix-it since we're not going
2722 // to recover well anyway.
2723 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2724 getAsTypeTemplateDecl(UnderlyingND) ||
2725 isa<ObjCInterfaceDecl>(UnderlyingND);
2726 } else {
2727 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2728 // because we aren't able to recover.
2729 AcceptableWithoutRecovery = true;
2730 }
2731
2732 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2733 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2734 ? diag::note_implicit_param_decl
2735 : diag::note_previous_decl;
2736 if (SS.isEmpty())
2737 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name << NameRange,
2738 PDiag(NoteID), AcceptableWithRecovery);
2739 else
2740 diagnoseTypo(Corrected,
2741 PDiag(diag::err_no_member_suggest)
2742 << Name << computeDeclContext(SS, false)
2743 << DroppedSpecifier << NameRange,
2744 PDiag(NoteID), AcceptableWithRecovery);
2745
2746 if (Corrected.WillReplaceSpecifier()) {
2748 // In order to be valid, a non-empty CXXScopeSpec needs a source range.
2749 SS.MakeTrivial(Context, NNS,
2750 NNS ? NameRange.getBegin() : SourceRange());
2751 }
2752
2753 // Tell the callee whether to try to recover.
2754 return !AcceptableWithRecovery;
2755 }
2756 }
2757 R.clear();
2758
2759 // Emit a special diagnostic for failed member lookups.
2760 // FIXME: computing the declaration context might fail here (?)
2761 if (!SS.isEmpty()) {
2762 Diag(R.getNameLoc(), diag::err_no_member)
2763 << Name << computeDeclContext(SS, false) << NameRange;
2764 return true;
2765 }
2766
2767 // Give up, we can't recover.
2768 Diag(R.getNameLoc(), diagnostic) << Name << NameRange;
2769 return true;
2770}
2771
2772/// In Microsoft mode, if we are inside a template class whose parent class has
2773/// dependent base classes, and we can't resolve an unqualified identifier, then
2774/// assume the identifier is a member of a dependent base class. We can only
2775/// recover successfully in static methods, instance methods, and other contexts
2776/// where 'this' is available. This doesn't precisely match MSVC's
2777/// instantiation model, but it's close enough.
2778static Expr *
2780 DeclarationNameInfo &NameInfo,
2781 SourceLocation TemplateKWLoc,
2782 const TemplateArgumentListInfo *TemplateArgs) {
2783 // Only try to recover from lookup into dependent bases in static methods or
2784 // contexts where 'this' is available.
2785 QualType ThisType = S.getCurrentThisType();
2786 const CXXRecordDecl *RD = nullptr;
2787 if (!ThisType.isNull())
2788 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2789 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2790 RD = MD->getParent();
2791 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2792 return nullptr;
2793
2794 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2795 // is available, suggest inserting 'this->' as a fixit.
2796 SourceLocation Loc = NameInfo.getLoc();
2797 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2798 DB << NameInfo.getName() << RD;
2799
2800 if (!ThisType.isNull()) {
2801 DB << FixItHint::CreateInsertion(Loc, "this->");
2803 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2804 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2805 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2806 }
2807
2808 // Synthesize a fake NNS that points to the derived class. This will
2809 // perform name lookup during template instantiation.
2810 CXXScopeSpec SS;
2811 NestedNameSpecifier NNS(Context.getCanonicalTagType(RD)->getTypePtr());
2812 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2814 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2815 TemplateArgs);
2816}
2817
2819 SourceLocation TemplateKWLoc,
2820 UnqualifiedId &Id, bool HasTrailingLParen,
2821 bool IsAddressOfOperand,
2823 bool IsInlineAsmIdentifier) {
2824 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2825 "cannot be direct & operand and have a trailing lparen");
2826 if (SS.isInvalid())
2827 return ExprError();
2828
2829 TemplateArgumentListInfo TemplateArgsBuffer;
2830
2831 // Decompose the UnqualifiedId into the following data.
2832 DeclarationNameInfo NameInfo;
2833 const TemplateArgumentListInfo *TemplateArgs;
2834 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2835
2836 DeclarationName Name = NameInfo.getName();
2838 SourceLocation NameLoc = NameInfo.getLoc();
2839
2840 if (II && II->isEditorPlaceholder()) {
2841 // FIXME: When typed placeholders are supported we can create a typed
2842 // placeholder expression node.
2843 return ExprError();
2844 }
2845
2846 // This specially handles arguments of attributes appertains to a type of C
2847 // struct field such that the name lookup within a struct finds the member
2848 // name, which is not the case for other contexts in C.
2849 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2850 // See if this is reference to a field of struct.
2851 LookupResult R(*this, NameInfo, LookupMemberName);
2852 // LookupName handles a name lookup from within anonymous struct.
2853 if (LookupName(R, S)) {
2854 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2855 QualType type = VD->getType().getNonReferenceType();
2856 // This will eventually be translated into MemberExpr upon
2857 // the use of instantiated struct fields.
2858 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2859 }
2860 }
2861 }
2862
2863 // Perform the required lookup.
2864 LookupResult R(*this, NameInfo,
2868 if (TemplateKWLoc.isValid() || TemplateArgs) {
2869 // Lookup the template name again to correctly establish the context in
2870 // which it was found. This is really unfortunate as we already did the
2871 // lookup to determine that it was a template name in the first place. If
2872 // this becomes a performance hit, we can work harder to preserve those
2873 // results until we get here but it's likely not worth it.
2874 AssumedTemplateKind AssumedTemplate;
2875 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2876 /*EnteringContext=*/false, TemplateKWLoc,
2877 &AssumedTemplate))
2878 return ExprError();
2879
2880 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2881 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2882 IsAddressOfOperand, TemplateArgs);
2883 } else {
2884 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2885 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2886 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2887
2888 // If the result might be in a dependent base class, this is a dependent
2889 // id-expression.
2890 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
2891 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2892 IsAddressOfOperand, TemplateArgs);
2893
2894 // If this reference is in an Objective-C method, then we need to do
2895 // some special Objective-C lookup, too.
2896 if (IvarLookupFollowUp) {
2897 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2898 if (E.isInvalid())
2899 return ExprError();
2900
2901 if (Expr *Ex = E.getAs<Expr>())
2902 return Ex;
2903 }
2904 }
2905
2906 if (R.isAmbiguous())
2907 return ExprError();
2908
2909 // This could be an implicitly declared function reference if the language
2910 // mode allows it as a feature.
2911 if (R.empty() && HasTrailingLParen && II &&
2912 getLangOpts().implicitFunctionsAllowed()) {
2913 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2914 if (D) R.addDecl(D);
2915 }
2916
2917 // Determine whether this name might be a candidate for
2918 // argument-dependent lookup.
2919 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2920
2921 if (R.empty() && !ADL) {
2922 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2923 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2924 TemplateKWLoc, TemplateArgs))
2925 return E;
2926 }
2927
2928 // Don't diagnose an empty lookup for inline assembly.
2929 if (IsInlineAsmIdentifier)
2930 return ExprError();
2931
2932 // If this name wasn't predeclared and if this is not a function
2933 // call, diagnose the problem.
2934 DefaultFilterCCC DefaultValidator(II, SS.getScopeRep());
2935 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2936 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2937 "Typo correction callback misconfigured");
2938 if (CCC) {
2939 // Make sure the callback knows what the typo being diagnosed is.
2940 CCC->setTypoName(II);
2941 if (SS.isValid())
2942 CCC->setTypoNNS(SS.getScopeRep());
2943 }
2944 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2945 // a template name, but we happen to have always already looked up the name
2946 // before we get here if it must be a template name.
2947 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2948 {}, nullptr))
2949 return ExprError();
2950
2951 assert(!R.empty() &&
2952 "DiagnoseEmptyLookup returned false but added no results");
2953
2954 // If we found an Objective-C instance variable, let
2955 // LookupInObjCMethod build the appropriate expression to
2956 // reference the ivar.
2957 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2958 R.clear();
2959 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2960 // In a hopelessly buggy code, Objective-C instance variable
2961 // lookup fails and no expression will be built to reference it.
2962 if (!E.isInvalid() && !E.get())
2963 return ExprError();
2964 return E;
2965 }
2966 }
2967
2968 // This is guaranteed from this point on.
2969 assert(!R.empty() || ADL);
2970
2971 // Check whether this might be a C++ implicit instance member access.
2972 // C++ [class.mfct.non-static]p3:
2973 // When an id-expression that is not part of a class member access
2974 // syntax and not used to form a pointer to member is used in the
2975 // body of a non-static member function of class X, if name lookup
2976 // resolves the name in the id-expression to a non-static non-type
2977 // member of some class C, the id-expression is transformed into a
2978 // class member access expression using (*this) as the
2979 // postfix-expression to the left of the . operator.
2980 //
2981 // But we don't actually need to do this for '&' operands if R
2982 // resolved to a function or overloaded function set, because the
2983 // expression is ill-formed if it actually works out to be a
2984 // non-static member function:
2985 //
2986 // C++ [expr.ref]p4:
2987 // Otherwise, if E1.E2 refers to a non-static member function. . .
2988 // [t]he expression can be used only as the left-hand operand of a
2989 // member function call.
2990 //
2991 // There are other safeguards against such uses, but it's important
2992 // to get this right here so that we don't end up making a
2993 // spuriously dependent expression if we're inside a dependent
2994 // instance method.
2995 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2996 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2997 S);
2998
2999 if (TemplateArgs || TemplateKWLoc.isValid()) {
3000
3001 // In C++1y, if this is a variable template id, then check it
3002 // in BuildTemplateIdExpr().
3003 // The single lookup result must be a variable template declaration.
3007 assert(R.getAsSingle<TemplateDecl>() &&
3008 "There should only be one declaration found.");
3009 }
3010
3011 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
3012 }
3013
3014 return BuildDeclarationNameExpr(SS, R, ADL);
3015}
3016
3018 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
3019 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
3020 LookupResult R(*this, NameInfo, LookupOrdinaryName);
3021 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
3022
3023 if (R.isAmbiguous())
3024 return ExprError();
3025
3026 if (R.wasNotFoundInCurrentInstantiation() || SS.isInvalid())
3027 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
3028 NameInfo, /*TemplateArgs=*/nullptr);
3029
3030 if (R.empty()) {
3031 // Don't diagnose problems with invalid record decl, the secondary no_member
3032 // diagnostic during template instantiation is likely bogus, e.g. if a class
3033 // is invalid because it's derived from an invalid base class, then missing
3034 // members were likely supposed to be inherited.
3036 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
3037 if (CD->isInvalidDecl() || CD->isBeingDefined())
3038 return ExprError();
3039 Diag(NameInfo.getLoc(), diag::err_no_member)
3040 << NameInfo.getName() << DC << SS.getRange();
3041 return ExprError();
3042 }
3043
3044 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
3045 QualType ET;
3046 TypeLocBuilder TLB;
3047 if (auto *TagD = dyn_cast<TagDecl>(TD)) {
3048 ET = SemaRef.Context.getTagType(ElaboratedTypeKeyword::None,
3049 SS.getScopeRep(), TagD,
3050 /*OwnsTag=*/false);
3051 auto TL = TLB.push<TagTypeLoc>(ET);
3053 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3054 TL.setNameLoc(NameInfo.getLoc());
3055 } else if (auto *TypedefD = dyn_cast<TypedefNameDecl>(TD)) {
3056 ET = SemaRef.Context.getTypedefType(ElaboratedTypeKeyword::None,
3057 SS.getScopeRep(), TypedefD);
3058 TLB.push<TypedefTypeLoc>(ET).set(
3059 /*ElaboratedKeywordLoc=*/SourceLocation(),
3060 SS.getWithLocInContext(Context), NameInfo.getLoc());
3061 } else {
3062 // FIXME: What else can appear here?
3063 ET = SemaRef.Context.getTypeDeclType(TD);
3064 TLB.pushTypeSpec(ET).setNameLoc(NameInfo.getLoc());
3065 assert(SS.isEmpty());
3066 }
3067
3068 // Diagnose a missing typename if this resolved unambiguously to a type in
3069 // a dependent context. If we can recover with a type, downgrade this to
3070 // a warning in Microsoft compatibility mode.
3071 unsigned DiagID = diag::err_typename_missing;
3072 if (RecoveryTSI && getLangOpts().MSVCCompat)
3073 DiagID = diag::ext_typename_missing;
3074 SourceLocation Loc = SS.getBeginLoc();
3075 auto D = Diag(Loc, DiagID);
3076 D << ET << SourceRange(Loc, NameInfo.getEndLoc());
3077
3078 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
3079 // context.
3080 if (!RecoveryTSI)
3081 return ExprError();
3082
3083 // Only issue the fixit if we're prepared to recover.
3084 D << FixItHint::CreateInsertion(Loc, "typename ");
3085
3086 // Recover by pretending this was an elaborated type.
3087 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
3088
3089 return ExprEmpty();
3090 }
3091
3092 // If necessary, build an implicit class member access.
3093 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
3095 /*TemplateKWLoc=*/SourceLocation(),
3096 R, /*TemplateArgs=*/nullptr,
3097 /*S=*/nullptr);
3098
3099 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
3100}
3101
3103 NestedNameSpecifier Qualifier,
3104 NamedDecl *FoundDecl,
3105 NamedDecl *Member) {
3106 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3107 if (!RD)
3108 return From;
3109
3110 QualType DestRecordType;
3111 QualType DestType;
3112 QualType FromRecordType;
3113 QualType FromType = From->getType();
3114 bool PointerConversions = false;
3115 if (isa<FieldDecl>(Member)) {
3116 DestRecordType = Context.getCanonicalTagType(RD);
3117 auto FromPtrType = FromType->getAs<PointerType>();
3118 DestRecordType = Context.getAddrSpaceQualType(
3119 DestRecordType, FromPtrType
3120 ? FromType->getPointeeType().getAddressSpace()
3121 : FromType.getAddressSpace());
3122
3123 if (FromPtrType) {
3124 DestType = Context.getPointerType(DestRecordType);
3125 FromRecordType = FromPtrType->getPointeeType();
3126 PointerConversions = true;
3127 } else {
3128 DestType = DestRecordType;
3129 FromRecordType = FromType;
3130 }
3131 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3132 if (!Method->isImplicitObjectMemberFunction())
3133 return From;
3134
3135 DestType = Method->getThisType().getNonReferenceType();
3136 DestRecordType = Method->getFunctionObjectParameterType();
3137
3138 if (FromType->getAs<PointerType>()) {
3139 FromRecordType = FromType->getPointeeType();
3140 PointerConversions = true;
3141 } else {
3142 FromRecordType = FromType;
3143 DestType = DestRecordType;
3144 }
3145
3146 LangAS FromAS = FromRecordType.getAddressSpace();
3147 LangAS DestAS = DestRecordType.getAddressSpace();
3148 if (FromAS != DestAS) {
3149 QualType FromRecordTypeWithoutAS =
3150 Context.removeAddrSpaceQualType(FromRecordType);
3151 QualType FromTypeWithDestAS =
3152 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3153 if (PointerConversions)
3154 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3155 From = ImpCastExprToType(From, FromTypeWithDestAS,
3156 CK_AddressSpaceConversion, From->getValueKind())
3157 .get();
3158 }
3159 } else {
3160 // No conversion necessary.
3161 return From;
3162 }
3163
3164 if (DestType->isDependentType() || FromType->isDependentType())
3165 return From;
3166
3167 // If the unqualified types are the same, no conversion is necessary.
3168 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3169 return From;
3170
3171 SourceRange FromRange = From->getSourceRange();
3172 SourceLocation FromLoc = FromRange.getBegin();
3173
3174 ExprValueKind VK = From->getValueKind();
3175
3176 // C++ [class.member.lookup]p8:
3177 // [...] Ambiguities can often be resolved by qualifying a name with its
3178 // class name.
3179 //
3180 // If the member was a qualified name and the qualified referred to a
3181 // specific base subobject type, we'll cast to that intermediate type
3182 // first and then to the object in which the member is declared. That allows
3183 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3184 //
3185 // class Base { public: int x; };
3186 // class Derived1 : public Base { };
3187 // class Derived2 : public Base { };
3188 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3189 //
3190 // void VeryDerived::f() {
3191 // x = 17; // error: ambiguous base subobjects
3192 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3193 // }
3194 if (Qualifier.getKind() == NestedNameSpecifier::Kind::Type) {
3195 QualType QType = QualType(Qualifier.getAsType(), 0);
3196 assert(QType->isRecordType() && "lookup done with non-record type");
3197
3198 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3199
3200 // In C++98, the qualifier type doesn't actually have to be a base
3201 // type of the object type, in which case we just ignore it.
3202 // Otherwise build the appropriate casts.
3203 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3204 CXXCastPath BasePath;
3205 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3206 FromLoc, FromRange, &BasePath))
3207 return ExprError();
3208
3209 if (PointerConversions)
3210 QType = Context.getPointerType(QType);
3211 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3212 VK, &BasePath).get();
3213
3214 FromType = QType;
3215 FromRecordType = QRecordType;
3216
3217 // If the qualifier type was the same as the destination type,
3218 // we're done.
3219 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3220 return From;
3221 }
3222 }
3223
3224 CXXCastPath BasePath;
3225 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3226 FromLoc, FromRange, &BasePath,
3227 /*IgnoreAccess=*/true))
3228 return ExprError();
3229
3230 // Propagate qualifiers to base subobjects as per:
3231 // C++ [basic.type.qualifier]p1.2:
3232 // A volatile object is [...] a subobject of a volatile object.
3233 Qualifiers FromTypeQuals = FromType.getQualifiers();
3234 FromTypeQuals.setAddressSpace(DestType.getAddressSpace());
3235 DestType = Context.getQualifiedType(DestType, FromTypeQuals);
3236
3237 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase, VK,
3238 &BasePath);
3239}
3240
3242 const LookupResult &R,
3243 bool HasTrailingLParen) {
3244 // Only when used directly as the postfix-expression of a call.
3245 if (!HasTrailingLParen)
3246 return false;
3247
3248 // Never if a scope specifier was provided.
3249 if (SS.isNotEmpty())
3250 return false;
3251
3252 // Only in C++ or ObjC++.
3253 if (!getLangOpts().CPlusPlus)
3254 return false;
3255
3256 // Turn off ADL when we find certain kinds of declarations during
3257 // normal lookup:
3258 for (const NamedDecl *D : R) {
3259 // C++0x [basic.lookup.argdep]p3:
3260 // -- a declaration of a class member
3261 // Since using decls preserve this property, we check this on the
3262 // original decl.
3263 if (D->isCXXClassMember())
3264 return false;
3265
3266 // C++0x [basic.lookup.argdep]p3:
3267 // -- a block-scope function declaration that is not a
3268 // using-declaration
3269 // NOTE: we also trigger this for function templates (in fact, we
3270 // don't check the decl type at all, since all other decl types
3271 // turn off ADL anyway).
3272 if (isa<UsingShadowDecl>(D))
3273 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3274 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3275 return false;
3276
3277 // C++0x [basic.lookup.argdep]p3:
3278 // -- a declaration that is neither a function or a function
3279 // template
3280 // And also for builtin functions.
3281 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3282 // But also builtin functions.
3283 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3284 return false;
3285 } else if (!isa<FunctionTemplateDecl>(D))
3286 return false;
3287 }
3288
3289 return true;
3290}
3291
3292
3293/// Diagnoses obvious problems with the use of the given declaration
3294/// as an expression. This is only actually called for lookups that
3295/// were not overloaded, and it doesn't promise that the declaration
3296/// will in fact be used.
3298 bool AcceptInvalid) {
3299 if (D->isInvalidDecl() && !AcceptInvalid)
3300 return true;
3301
3302 if (isa<TypedefNameDecl>(D)) {
3303 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3304 return true;
3305 }
3306
3307 if (isa<ObjCInterfaceDecl>(D)) {
3308 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3309 return true;
3310 }
3311
3312 if (isa<NamespaceDecl>(D)) {
3313 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3314 return true;
3315 }
3316
3317 return false;
3318}
3319
3320// Certain multiversion types should be treated as overloaded even when there is
3321// only one result.
3323 assert(R.isSingleResult() && "Expected only a single result");
3324 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3325 return FD &&
3326 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3327}
3328
3330 LookupResult &R, bool NeedsADL,
3331 bool AcceptInvalidDecl) {
3332 // If this is a single, fully-resolved result and we don't need ADL,
3333 // just build an ordinary singleton decl ref.
3334 if (!NeedsADL && R.isSingleResult() &&
3335 !R.getAsSingle<FunctionTemplateDecl>() &&
3337 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
3338 R.getRepresentativeDecl(), nullptr,
3339 AcceptInvalidDecl);
3340
3341 // We only need to check the declaration if there's exactly one
3342 // result, because in the overloaded case the results can only be
3343 // functions and function templates.
3344 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3345 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3346 AcceptInvalidDecl))
3347 return ExprError();
3348
3349 // Otherwise, just build an unresolved lookup expression. Suppress
3350 // any lookup-related diagnostics; we'll hash these out later, when
3351 // we've picked a target.
3352 R.suppressDiagnostics();
3353
3355 Context, R.getNamingClass(), SS.getWithLocInContext(Context),
3356 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3357 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3358
3359 return ULE;
3360}
3361
3363 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3364 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3365 bool AcceptInvalidDecl) {
3366 assert(D && "Cannot refer to a NULL declaration");
3367 assert(!isa<FunctionTemplateDecl>(D) &&
3368 "Cannot refer unambiguously to a function template");
3369
3370 SourceLocation Loc = NameInfo.getLoc();
3371 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3372 // Recovery from invalid cases (e.g. D is an invalid Decl).
3373 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3374 // diagnostics, as invalid decls use int as a fallback type.
3375 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3376 }
3377
3378 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3379 // Specifically diagnose references to class templates that are missing
3380 // a template argument list.
3381 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3382 return ExprError();
3383 }
3384
3385 // Make sure that we're referring to a value.
3387 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3388 Diag(D->getLocation(), diag::note_declared_at);
3389 return ExprError();
3390 }
3391
3392 // Check whether this declaration can be used. Note that we suppress
3393 // this check when we're going to perform argument-dependent lookup
3394 // on this function name, because this might not be the function
3395 // that overload resolution actually selects.
3396 if (DiagnoseUseOfDecl(D, Loc))
3397 return ExprError();
3398
3399 auto *VD = cast<ValueDecl>(D);
3400
3401 // Only create DeclRefExpr's for valid Decl's.
3402 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3403 return ExprError();
3404
3405 // Handle members of anonymous structs and unions. If we got here,
3406 // and the reference is to a class member indirect field, then this
3407 // must be the subject of a pointer-to-member expression.
3408 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3409 IndirectField && !IndirectField->isCXXClassMember())
3411 IndirectField);
3412
3413 QualType type = VD->getType();
3414 if (type.isNull())
3415 return ExprError();
3416 ExprValueKind valueKind = VK_PRValue;
3417
3418 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3419 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3420 // is expanded by some outer '...' in the context of the use.
3421 type = type.getNonPackExpansionType();
3422
3423 switch (D->getKind()) {
3424 // Ignore all the non-ValueDecl kinds.
3425#define ABSTRACT_DECL(kind)
3426#define VALUE(type, base)
3427#define DECL(type, base) case Decl::type:
3428#include "clang/AST/DeclNodes.inc"
3429 llvm_unreachable("invalid value decl kind");
3430
3431 // These shouldn't make it here.
3432 case Decl::ObjCAtDefsField:
3433 llvm_unreachable("forming non-member reference to ivar?");
3434
3435 // Enum constants are always r-values and never references.
3436 // Unresolved using declarations are dependent.
3437 case Decl::EnumConstant:
3438 case Decl::UnresolvedUsingValue:
3439 case Decl::OMPDeclareReduction:
3440 case Decl::OMPDeclareMapper:
3441 valueKind = VK_PRValue;
3442 break;
3443
3444 // Fields and indirect fields that got here must be for
3445 // pointer-to-member expressions; we just call them l-values for
3446 // internal consistency, because this subexpression doesn't really
3447 // exist in the high-level semantics.
3448 case Decl::Field:
3449 case Decl::IndirectField:
3450 case Decl::ObjCIvar:
3451 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3452 "building reference to field in C?");
3453
3454 // These can't have reference type in well-formed programs, but
3455 // for internal consistency we do this anyway.
3456 type = type.getNonReferenceType();
3457 valueKind = VK_LValue;
3458 break;
3459
3460 // Non-type template parameters are either l-values or r-values
3461 // depending on the type.
3462 case Decl::NonTypeTemplateParm: {
3463 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3464 type = reftype->getPointeeType();
3465 valueKind = VK_LValue; // even if the parameter is an r-value reference
3466 break;
3467 }
3468
3469 // [expr.prim.id.unqual]p2:
3470 // If the entity is a template parameter object for a template
3471 // parameter of type T, the type of the expression is const T.
3472 // [...] The expression is an lvalue if the entity is a [...] template
3473 // parameter object.
3474 if (type->isRecordType()) {
3475 type = type.getUnqualifiedType().withConst();
3476 valueKind = VK_LValue;
3477 break;
3478 }
3479
3480 // For non-references, we need to strip qualifiers just in case
3481 // the template parameter was declared as 'const int' or whatever.
3482 valueKind = VK_PRValue;
3483 type = type.getUnqualifiedType();
3484 break;
3485 }
3486
3487 case Decl::Var:
3488 case Decl::VarTemplateSpecialization:
3489 case Decl::VarTemplatePartialSpecialization:
3490 case Decl::Decomposition:
3491 case Decl::Binding:
3492 case Decl::OMPCapturedExpr:
3493 // In C, "extern void blah;" is valid and is an r-value.
3494 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3495 type->isVoidType()) {
3496 valueKind = VK_PRValue;
3497 break;
3498 }
3499 [[fallthrough]];
3500
3501 case Decl::ImplicitParam:
3502 case Decl::ParmVar: {
3503 // These are always l-values.
3504 valueKind = VK_LValue;
3505 type = type.getNonReferenceType();
3506
3507 // FIXME: Does the addition of const really only apply in
3508 // potentially-evaluated contexts? Since the variable isn't actually
3509 // captured in an unevaluated context, it seems that the answer is no.
3510 if (!isUnevaluatedContext()) {
3511 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3512 if (!CapturedType.isNull())
3513 type = CapturedType;
3514 }
3515 break;
3516 }
3517
3518 case Decl::Function: {
3519 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3520 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
3521 type = Context.BuiltinFnTy;
3522 valueKind = VK_PRValue;
3523 break;
3524 }
3525 }
3526
3527 const FunctionType *fty = type->castAs<FunctionType>();
3528
3529 // If we're referring to a function with an __unknown_anytype
3530 // result type, make the entire expression __unknown_anytype.
3531 if (fty->getReturnType() == Context.UnknownAnyTy) {
3532 type = Context.UnknownAnyTy;
3533 valueKind = VK_PRValue;
3534 break;
3535 }
3536
3537 // Functions are l-values in C++.
3538 if (getLangOpts().CPlusPlus) {
3539 valueKind = VK_LValue;
3540 break;
3541 }
3542
3543 // C99 DR 316 says that, if a function type comes from a
3544 // function definition (without a prototype), that type is only
3545 // used for checking compatibility. Therefore, when referencing
3546 // the function, we pretend that we don't have the full function
3547 // type.
3548 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3549 type = Context.getFunctionNoProtoType(fty->getReturnType(),
3550 fty->getExtInfo());
3551
3552 // Functions are r-values in C.
3553 valueKind = VK_PRValue;
3554 break;
3555 }
3556
3557 case Decl::CXXDeductionGuide:
3558 llvm_unreachable("building reference to deduction guide");
3559
3560 case Decl::MSProperty:
3561 case Decl::MSGuid:
3562 case Decl::TemplateParamObject:
3563 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3564 // capture in OpenMP, or duplicated between host and device?
3565 valueKind = VK_LValue;
3566 break;
3567
3568 case Decl::UnnamedGlobalConstant:
3569 valueKind = VK_LValue;
3570 break;
3571
3572 case Decl::CXXMethod:
3573 // If we're referring to a method with an __unknown_anytype
3574 // result type, make the entire expression __unknown_anytype.
3575 // This should only be possible with a type written directly.
3576 if (const FunctionProtoType *proto =
3577 dyn_cast<FunctionProtoType>(VD->getType()))
3578 if (proto->getReturnType() == Context.UnknownAnyTy) {
3579 type = Context.UnknownAnyTy;
3580 valueKind = VK_PRValue;
3581 break;
3582 }
3583
3584 // C++ methods are l-values if static, r-values if non-static.
3585 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3586 valueKind = VK_LValue;
3587 break;
3588 }
3589 [[fallthrough]];
3590
3591 case Decl::CXXConversion:
3592 case Decl::CXXDestructor:
3593 case Decl::CXXConstructor:
3594 valueKind = VK_PRValue;
3595 break;
3596 }
3597
3598 auto *E =
3599 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3600 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3601 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3602 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3603 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3604 // diagnostics).
3605 if (VD->isInvalidDecl() && E)
3606 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3607 return E;
3608}
3609
3610static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3612 Target.resize(CharByteWidth * (Source.size() + 1));
3613 char *ResultPtr = &Target[0];
3614 const llvm::UTF8 *ErrorPtr;
3615 bool success =
3616 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3617 (void)success;
3618 assert(success);
3619 Target.resize(ResultPtr - &Target[0]);
3620}
3621
3624 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3625 if (!currentDecl) {
3626 Diag(Loc, diag::ext_predef_outside_function);
3627 currentDecl = Context.getTranslationUnitDecl();
3628 }
3629
3630 QualType ResTy;
3631 StringLiteral *SL = nullptr;
3632 if (cast<DeclContext>(currentDecl)->isDependentContext())
3633 ResTy = Context.DependentTy;
3634 else {
3635 // Pre-defined identifiers are of type char[x], where x is the length of
3636 // the string.
3637 bool ForceElaboratedPrinting =
3638 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3639 auto Str =
3640 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3641 unsigned Length = Str.length();
3642
3643 llvm::APInt LengthI(32, Length + 1);
3646 ResTy =
3647 Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3648 SmallString<32> RawChars;
3649 ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3650 Str, RawChars);
3651 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3653 /*IndexTypeQuals*/ 0);
3655 /*Pascal*/ false, ResTy, Loc);
3656 } else {
3657 ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3658 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3660 /*IndexTypeQuals*/ 0);
3662 /*Pascal*/ false, ResTy, Loc);
3663 }
3664 }
3665
3666 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3667 SL);
3668}
3669
3673
3675 SmallString<16> CharBuffer;
3676 bool Invalid = false;
3677 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3678 if (Invalid)
3679 return ExprError();
3680
3681 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3682 PP, Tok.getKind());
3683 if (Literal.hadError())
3684 return ExprError();
3685
3686 QualType Ty;
3687 if (Literal.isWide())
3688 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3689 else if (Literal.isUTF8() && getLangOpts().C23)
3690 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3691 else if (Literal.isUTF8() && getLangOpts().Char8)
3692 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3693 else if (Literal.isUTF16())
3694 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3695 else if (Literal.isUTF32())
3696 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3697 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3698 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3699 else
3700 Ty = Context.CharTy; // 'x' -> char in C++;
3701 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3702
3704 if (Literal.isWide())
3706 else if (Literal.isUTF16())
3708 else if (Literal.isUTF32())
3710 else if (Literal.isUTF8())
3712
3713 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3714 Tok.getLocation());
3715
3716 if (Literal.getUDSuffix().empty())
3717 return Lit;
3718
3719 // We're building a user-defined literal.
3720 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3721 SourceLocation UDSuffixLoc =
3722 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3723
3724 // Make sure we're allowed user-defined literals here.
3725 if (!UDLScope)
3726 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3727
3728 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3729 // operator "" X (ch)
3730 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3731 Lit, Tok.getLocation());
3732}
3733
3735 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3737 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3738 Context.IntTy, Loc);
3739}
3740
3742 ExprResult Inner;
3743 if (getLangOpts().CPlusPlus) {
3744 Inner = ActOnCXXBoolLiteral(Loc, Value ? tok::kw_true : tok::kw_false);
3745 } else {
3746 // C doesn't actually have a way to represent literal values of type
3747 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
3748 Inner = ActOnIntegerConstant(Loc, Value ? 1 : 0);
3749 Inner =
3750 ImpCastExprToType(Inner.get(), Context.BoolTy, CK_IntegralToBoolean);
3751 }
3752 return Inner;
3753}
3754
3756 QualType Ty, SourceLocation Loc) {
3757 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3758
3759 using llvm::APFloat;
3760 APFloat Val(Format);
3761
3762 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3763 if (RM == llvm::RoundingMode::Dynamic)
3764 RM = llvm::RoundingMode::NearestTiesToEven;
3765 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3766
3767 // Overflow is always an error, but underflow is only an error if
3768 // we underflowed to zero (APFloat reports denormals as underflow).
3769 if ((result & APFloat::opOverflow) ||
3770 ((result & APFloat::opUnderflow) && Val.isZero())) {
3771 unsigned diagnostic;
3772 SmallString<20> buffer;
3773 if (result & APFloat::opOverflow) {
3774 diagnostic = diag::warn_float_overflow;
3775 APFloat::getLargest(Format).toString(buffer);
3776 } else {
3777 diagnostic = diag::warn_float_underflow;
3778 APFloat::getSmallest(Format).toString(buffer);
3779 }
3780
3781 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3782 }
3783
3784 bool isExact = (result == APFloat::opOK);
3785 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3786}
3787
3788bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3789 assert(E && "Invalid expression");
3790
3791 if (E->isValueDependent())
3792 return false;
3793
3794 QualType QT = E->getType();
3795 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3796 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3797 return true;
3798 }
3799
3800 llvm::APSInt ValueAPS;
3802
3803 if (R.isInvalid())
3804 return true;
3805
3806 // GCC allows the value of unroll count to be 0.
3807 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3808 // "The values of 0 and 1 block any unrolling of the loop."
3809 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3810 // '#pragma unroll' cases.
3811 bool ValueIsPositive =
3812 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3813 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3814 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3815 << toString(ValueAPS, 10) << ValueIsPositive;
3816 return true;
3817 }
3818
3819 return false;
3820}
3821
3823 // Fast path for a single digit (which is quite common). A single digit
3824 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3825 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3826 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3827 return ActOnIntegerConstant(Tok.getLocation(), Val);
3828 }
3829
3830 SmallString<128> SpellingBuffer;
3831 // NumericLiteralParser wants to overread by one character. Add padding to
3832 // the buffer in case the token is copied to the buffer. If getSpelling()
3833 // returns a StringRef to the memory buffer, it should have a null char at
3834 // the EOF, so it is also safe.
3835 SpellingBuffer.resize(Tok.getLength() + 1);
3836
3837 // Get the spelling of the token, which eliminates trigraphs, etc.
3838 bool Invalid = false;
3839 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3840 if (Invalid)
3841 return ExprError();
3842
3843 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3844 PP.getSourceManager(), PP.getLangOpts(),
3845 PP.getTargetInfo(), PP.getDiagnostics());
3846 if (Literal.hadError)
3847 return ExprError();
3848
3849 if (Literal.hasUDSuffix()) {
3850 // We're building a user-defined literal.
3851 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3852 SourceLocation UDSuffixLoc =
3853 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3854
3855 // Make sure we're allowed user-defined literals here.
3856 if (!UDLScope)
3857 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3858
3859 QualType CookedTy;
3860 if (Literal.isFloatingLiteral()) {
3861 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3862 // long double, the literal is treated as a call of the form
3863 // operator "" X (f L)
3864 CookedTy = Context.LongDoubleTy;
3865 } else {
3866 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3867 // unsigned long long, the literal is treated as a call of the form
3868 // operator "" X (n ULL)
3869 CookedTy = Context.UnsignedLongLongTy;
3870 }
3871
3872 DeclarationName OpName =
3873 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3874 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3875 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3876
3877 SourceLocation TokLoc = Tok.getLocation();
3878
3879 // Perform literal operator lookup to determine if we're building a raw
3880 // literal or a cooked one.
3881 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3882 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3883 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3884 /*AllowStringTemplatePack*/ false,
3885 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3887 // Lookup failure for imaginary constants isn't fatal, there's still the
3888 // GNU extension producing _Complex types.
3889 break;
3890 case LOLR_Error:
3891 return ExprError();
3892 case LOLR_Cooked: {
3893 Expr *Lit;
3894 if (Literal.isFloatingLiteral()) {
3895 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3896 } else {
3897 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3898 if (Literal.GetIntegerValue(ResultVal))
3899 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3900 << /* Unsigned */ 1;
3901 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3902 Tok.getLocation());
3903 }
3904 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3905 }
3906
3907 case LOLR_Raw: {
3908 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3909 // literal is treated as a call of the form
3910 // operator "" X ("n")
3911 unsigned Length = Literal.getUDSuffixOffset();
3912 QualType StrTy = Context.getConstantArrayType(
3913 Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3914 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3915 Expr *Lit =
3916 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3918 /*Pascal*/ false, StrTy, TokLoc);
3919 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3920 }
3921
3922 case LOLR_Template: {
3923 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3924 // template), L is treated as a call fo the form
3925 // operator "" X <'c1', 'c2', ... 'ck'>()
3926 // where n is the source character sequence c1 c2 ... ck.
3927 TemplateArgumentListInfo ExplicitArgs;
3928 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3929 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3930 llvm::APSInt Value(CharBits, CharIsUnsigned);
3931 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3932 Value = TokSpelling[I];
3933 TemplateArgument Arg(Context, Value, Context.CharTy);
3935 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3936 }
3937 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
3938 }
3940 llvm_unreachable("unexpected literal operator lookup result");
3941 }
3942 }
3943
3944 Expr *Res;
3945
3946 if (Literal.isFixedPointLiteral()) {
3947 QualType Ty;
3948
3949 if (Literal.isAccum) {
3950 if (Literal.isHalf) {
3951 Ty = Context.ShortAccumTy;
3952 } else if (Literal.isLong) {
3953 Ty = Context.LongAccumTy;
3954 } else {
3955 Ty = Context.AccumTy;
3956 }
3957 } else if (Literal.isFract) {
3958 if (Literal.isHalf) {
3959 Ty = Context.ShortFractTy;
3960 } else if (Literal.isLong) {
3961 Ty = Context.LongFractTy;
3962 } else {
3963 Ty = Context.FractTy;
3964 }
3965 }
3966
3967 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3968
3969 bool isSigned = !Literal.isUnsigned;
3970 unsigned scale = Context.getFixedPointScale(Ty);
3971 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3972
3973 llvm::APInt Val(bit_width, 0, isSigned);
3974 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3975 bool ValIsZero = Val.isZero() && !Overflowed;
3976
3977 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3978 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3979 // Clause 6.4.4 - The value of a constant shall be in the range of
3980 // representable values for its type, with exception for constants of a
3981 // fract type with a value of exactly 1; such a constant shall denote
3982 // the maximal value for the type.
3983 --Val;
3984 else if (Val.ugt(MaxVal) || Overflowed)
3985 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3986
3988 Tok.getLocation(), scale);
3989 } else if (Literal.isFloatingLiteral()) {
3990 QualType Ty;
3991 if (Literal.isHalf){
3992 if (getLangOpts().HLSL ||
3993 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3994 Ty = Context.HalfTy;
3995 else {
3996 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3997 return ExprError();
3998 }
3999 } else if (Literal.isFloat)
4000 Ty = Context.FloatTy;
4001 else if (Literal.isLong)
4002 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
4003 else if (Literal.isFloat16)
4004 Ty = Context.Float16Ty;
4005 else if (Literal.isFloat128)
4006 Ty = Context.Float128Ty;
4007 else if (getLangOpts().HLSL)
4008 Ty = Context.FloatTy;
4009 else
4010 Ty = Context.DoubleTy;
4011
4012 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
4013
4014 if (Ty == Context.DoubleTy) {
4015 if (getLangOpts().SinglePrecisionConstants) {
4016 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4017 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4018 }
4019 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4020 "cl_khr_fp64", getLangOpts())) {
4021 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4022 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4024 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4025 }
4026 }
4027 } else if (!Literal.isIntegerLiteral()) {
4028 return ExprError();
4029 } else {
4030 QualType Ty;
4031
4032 // 'z/uz' literals are a C++23 feature.
4033 if (Literal.isSizeT)
4034 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
4036 ? diag::warn_cxx20_compat_size_t_suffix
4037 : diag::ext_cxx23_size_t_suffix
4038 : diag::err_cxx23_size_t_suffix);
4039
4040 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4041 // but we do not currently support the suffix in C++ mode because it's not
4042 // entirely clear whether WG21 will prefer this suffix to return a library
4043 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4044 // literals are a C++ extension.
4045 if (Literal.isBitInt)
4046 PP.Diag(Tok.getLocation(),
4047 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4048 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4049 : diag::ext_c23_bitint_suffix);
4050
4051 // Get the value in the widest-possible width. What is "widest" depends on
4052 // whether the literal is a bit-precise integer or not. For a bit-precise
4053 // integer type, try to scan the source to determine how many bits are
4054 // needed to represent the value. This may seem a bit expensive, but trying
4055 // to get the integer value from an overly-wide APInt is *extremely*
4056 // expensive, so the naive approach of assuming
4057 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4058 unsigned BitsNeeded = Context.getTargetInfo().getIntMaxTWidth();
4059 if (Literal.isBitInt)
4060 BitsNeeded = llvm::APInt::getSufficientBitsNeeded(
4061 Literal.getLiteralDigits(), Literal.getRadix());
4062 if (Literal.MicrosoftInteger) {
4063 if (Literal.MicrosoftInteger == 128 &&
4064 !Context.getTargetInfo().hasInt128Type())
4065 PP.Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4066 << Literal.isUnsigned;
4067 BitsNeeded = Literal.MicrosoftInteger;
4068 }
4069
4070 llvm::APInt ResultVal(BitsNeeded, 0);
4071
4072 if (Literal.GetIntegerValue(ResultVal)) {
4073 // If this value didn't fit into uintmax_t, error and force to ull.
4074 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4075 << /* Unsigned */ 1;
4076 Ty = Context.UnsignedLongLongTy;
4077 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4078 "long long is not intmax_t?");
4079 } else {
4080 // If this value fits into a ULL, try to figure out what else it fits into
4081 // according to the rules of C99 6.4.4.1p5.
4082
4083 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4084 // be an unsigned int.
4085 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4086
4087 // HLSL doesn't really have `long` or `long long`. We support the `ll`
4088 // suffix for portability of code with C++, but both `l` and `ll` are
4089 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
4090 // same.
4091 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
4092 Literal.isLong = true;
4093 Literal.isLongLong = false;
4094 }
4095
4096 // Check from smallest to largest, picking the smallest type we can.
4097 unsigned Width = 0;
4098
4099 // Microsoft specific integer suffixes are explicitly sized.
4100 if (Literal.MicrosoftInteger) {
4101 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4102 Width = 8;
4103 Ty = Context.CharTy;
4104 } else {
4105 Width = Literal.MicrosoftInteger;
4106 Ty = Context.getIntTypeForBitwidth(Width,
4107 /*Signed=*/!Literal.isUnsigned);
4108 }
4109 }
4110
4111 // Bit-precise integer literals are automagically-sized based on the
4112 // width required by the literal.
4113 if (Literal.isBitInt) {
4114 // The signed version has one more bit for the sign value. There are no
4115 // zero-width bit-precise integers, even if the literal value is 0.
4116 Width = std::max(ResultVal.getActiveBits(), 1u) +
4117 (Literal.isUnsigned ? 0u : 1u);
4118
4119 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4120 // and reset the type to the largest supported width.
4121 unsigned int MaxBitIntWidth =
4122 Context.getTargetInfo().getMaxBitIntWidth();
4123 if (Width > MaxBitIntWidth) {
4124 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4125 << Literal.isUnsigned;
4126 Width = MaxBitIntWidth;
4127 }
4128
4129 // Reset the result value to the smaller APInt and select the correct
4130 // type to be used. Note, we zext even for signed values because the
4131 // literal itself is always an unsigned value (a preceeding - is a
4132 // unary operator, not part of the literal).
4133 ResultVal = ResultVal.zextOrTrunc(Width);
4134 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4135 }
4136
4137 // Check C++23 size_t literals.
4138 if (Literal.isSizeT) {
4139 assert(!Literal.MicrosoftInteger &&
4140 "size_t literals can't be Microsoft literals");
4141 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4142 Context.getTargetInfo().getSizeType());
4143
4144 // Does it fit in size_t?
4145 if (ResultVal.isIntN(SizeTSize)) {
4146 // Does it fit in ssize_t?
4147 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4148 Ty = Context.getSignedSizeType();
4149 else if (AllowUnsigned)
4150 Ty = Context.getSizeType();
4151 Width = SizeTSize;
4152 }
4153 }
4154
4155 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4156 !Literal.isSizeT) {
4157 // Are int/unsigned possibilities?
4158 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4159
4160 // Does it fit in a unsigned int?
4161 if (ResultVal.isIntN(IntSize)) {
4162 // Does it fit in a signed int?
4163 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4164 Ty = Context.IntTy;
4165 else if (AllowUnsigned)
4166 Ty = Context.UnsignedIntTy;
4167 Width = IntSize;
4168 }
4169 }
4170
4171 // Are long/unsigned long possibilities?
4172 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4173 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4174
4175 // Does it fit in a unsigned long?
4176 if (ResultVal.isIntN(LongSize)) {
4177 // Does it fit in a signed long?
4178 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4179 Ty = Context.LongTy;
4180 else if (AllowUnsigned)
4181 Ty = Context.UnsignedLongTy;
4182 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4183 // is compatible.
4184 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4185 const unsigned LongLongSize =
4186 Context.getTargetInfo().getLongLongWidth();
4187 Diag(Tok.getLocation(),
4189 ? Literal.isLong
4190 ? diag::warn_old_implicitly_unsigned_long_cxx
4191 : /*C++98 UB*/ diag::
4192 ext_old_implicitly_unsigned_long_cxx
4193 : diag::warn_old_implicitly_unsigned_long)
4194 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4195 : /*will be ill-formed*/ 1);
4196 Ty = Context.UnsignedLongTy;
4197 }
4198 Width = LongSize;
4199 }
4200 }
4201
4202 // Check long long if needed.
4203 if (Ty.isNull() && !Literal.isSizeT) {
4204 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4205
4206 // Does it fit in a unsigned long long?
4207 if (ResultVal.isIntN(LongLongSize)) {
4208 // Does it fit in a signed long long?
4209 // To be compatible with MSVC, hex integer literals ending with the
4210 // LL or i64 suffix are always signed in Microsoft mode.
4211 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4212 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4213 Ty = Context.LongLongTy;
4214 else if (AllowUnsigned)
4215 Ty = Context.UnsignedLongLongTy;
4216 Width = LongLongSize;
4217
4218 // 'long long' is a C99 or C++11 feature, whether the literal
4219 // explicitly specified 'long long' or we needed the extra width.
4220 if (getLangOpts().CPlusPlus)
4221 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4222 ? diag::warn_cxx98_compat_longlong
4223 : diag::ext_cxx11_longlong);
4224 else if (!getLangOpts().C99)
4225 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4226 }
4227 }
4228
4229 // If we still couldn't decide a type, we either have 'size_t' literal
4230 // that is out of range, or a decimal literal that does not fit in a
4231 // signed long long and has no U suffix.
4232 if (Ty.isNull()) {
4233 if (Literal.isSizeT)
4234 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4235 << Literal.isUnsigned;
4236 else
4237 Diag(Tok.getLocation(),
4238 diag::ext_integer_literal_too_large_for_signed);
4239 Ty = Context.UnsignedLongLongTy;
4240 Width = Context.getTargetInfo().getLongLongWidth();
4241 }
4242
4243 if (ResultVal.getBitWidth() != Width)
4244 ResultVal = ResultVal.trunc(Width);
4245 }
4246 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4247 }
4248
4249 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4250 if (Literal.isImaginary) {
4251 Res = new (Context) ImaginaryLiteral(Res,
4252 Context.getComplexType(Res->getType()));
4253
4254 // In C++, this is a GNU extension. In C, it's a C2y extension.
4255 unsigned DiagId;
4256 if (getLangOpts().CPlusPlus)
4257 DiagId = diag::ext_gnu_imaginary_constant;
4258 else if (getLangOpts().C2y)
4259 DiagId = diag::warn_c23_compat_imaginary_constant;
4260 else
4261 DiagId = diag::ext_c2y_imaginary_constant;
4262 Diag(Tok.getLocation(), DiagId);
4263 }
4264 return Res;
4265}
4266
4268 assert(E && "ActOnParenExpr() missing expr");
4269 QualType ExprTy = E->getType();
4270 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4271 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4272 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4273 return new (Context) ParenExpr(L, R, E);
4274}
4275
4277 SourceLocation Loc,
4278 SourceRange ArgRange) {
4279 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4280 // scalar or vector data type argument..."
4281 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4282 // type (C99 6.2.5p18) or void.
4283 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4284 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4285 << T << ArgRange;
4286 return true;
4287 }
4288
4289 assert((T->isVoidType() || !T->isIncompleteType()) &&
4290 "Scalar types should always be complete");
4291 return false;
4292}
4293
4295 SourceLocation Loc,
4296 SourceRange ArgRange) {
4297 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4298 if (!T->isVectorType() && !T->isSizelessVectorType())
4299 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4300 << ""
4301 << "__builtin_vectorelements" << T << ArgRange;
4302
4303 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) {
4304 if (T->isSVESizelessBuiltinType()) {
4305 llvm::StringMap<bool> CallerFeatureMap;
4306 S.Context.getFunctionFeatureMap(CallerFeatureMap, FD);
4307 return S.ARM().checkSVETypeSupport(T, Loc, FD, CallerFeatureMap);
4308 }
4309 }
4310
4311 return false;
4312}
4313
4315 SourceLocation Loc,
4316 SourceRange ArgRange) {
4317 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4318 return true;
4319
4320 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4321 !T->isFunctionReferenceType() && !T->isMemberFunctionPointerType()) {
4322 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4323 return true;
4324 }
4325
4326 return false;
4327}
4328
4330 SourceLocation Loc,
4331 SourceRange ArgRange,
4332 UnaryExprOrTypeTrait TraitKind) {
4333 // Invalid types must be hard errors for SFINAE in C++.
4334 if (S.LangOpts.CPlusPlus)
4335 return true;
4336
4337 // C99 6.5.3.4p1:
4338 if (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4339 TraitKind == UETT_PreferredAlignOf) {
4340
4341 // sizeof(function)/alignof(function) is allowed as an extension.
4342 if (T->isFunctionType()) {
4343 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4344 << getTraitSpelling(TraitKind) << ArgRange;
4345 return false;
4346 }
4347
4348 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4349 // this is an error (OpenCL v1.1 s6.3.k)
4350 if (T->isVoidType()) {
4351 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4352 : diag::ext_sizeof_alignof_void_type;
4353 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4354 return false;
4355 }
4356 }
4357 return true;
4358}
4359
4361 SourceLocation Loc,
4362 SourceRange ArgRange,
4363 UnaryExprOrTypeTrait TraitKind) {
4364 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4365 // runtime doesn't allow it.
4366 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
4367 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4368 << T << (TraitKind == UETT_SizeOf)
4369 << ArgRange;
4370 return true;
4371 }
4372
4373 return false;
4374}
4375
4376/// Check whether E is a pointer from a decayed array type (the decayed
4377/// pointer type is equal to T) and emit a warning if it is.
4379 const Expr *E) {
4380 // Don't warn if the operation changed the type.
4381 if (T != E->getType())
4382 return;
4383
4384 // Now look for array decays.
4385 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4386 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4387 return;
4388
4389 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4390 << ICE->getType()
4391 << ICE->getSubExpr()->getType();
4392}
4393
4395 UnaryExprOrTypeTrait ExprKind) {
4396 QualType ExprTy = E->getType();
4397 assert(!ExprTy->isReferenceType());
4398
4399 bool IsUnevaluatedOperand =
4400 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4401 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4402 ExprKind == UETT_VecStep || ExprKind == UETT_CountOf);
4403 if (IsUnevaluatedOperand) {
4405 if (Result.isInvalid())
4406 return true;
4407 E = Result.get();
4408 }
4409
4410 // The operand for sizeof and alignof is in an unevaluated expression context,
4411 // so side effects could result in unintended consequences.
4412 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4413 // used to build SFINAE gadgets.
4414 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4415 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4417 !E->getType()->isVariableArrayType() &&
4418 E->HasSideEffects(Context, false))
4419 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4420
4421 if (ExprKind == UETT_VecStep)
4422 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4423 E->getSourceRange());
4424
4425 if (ExprKind == UETT_VectorElements)
4426 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4427 E->getSourceRange());
4428
4429 // Explicitly list some types as extensions.
4430 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4431 E->getSourceRange(), ExprKind))
4432 return false;
4433
4434 // WebAssembly tables are always illegal operands to unary expressions and
4435 // type traits.
4436 if (Context.getTargetInfo().getTriple().isWasm() &&
4438 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4439 << getTraitSpelling(ExprKind);
4440 return true;
4441 }
4442
4443 // 'alignof' applied to an expression only requires the base element type of
4444 // the expression to be complete. 'sizeof' requires the expression's type to
4445 // be complete (and will attempt to complete it if it's an array of unknown
4446 // bound).
4447 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4449 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4450 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4451 getTraitSpelling(ExprKind), E->getSourceRange()))
4452 return true;
4453 } else {
4455 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4456 getTraitSpelling(ExprKind), E->getSourceRange()))
4457 return true;
4458 }
4459
4460 // Completing the expression's type may have changed it.
4461 ExprTy = E->getType();
4462 assert(!ExprTy->isReferenceType());
4463
4464 if (ExprTy->isFunctionType()) {
4465 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4466 << getTraitSpelling(ExprKind) << E->getSourceRange();
4467 return true;
4468 }
4469
4470 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4471 E->getSourceRange(), ExprKind))
4472 return true;
4473
4474 if (ExprKind == UETT_CountOf) {
4475 // The type has to be an array type. We already checked for incomplete
4476 // types above.
4477 QualType ExprType = E->IgnoreParens()->getType();
4478 if (!ExprType->isArrayType()) {
4479 Diag(E->getExprLoc(), diag::err_countof_arg_not_array_type) << ExprType;
4480 return true;
4481 }
4482 // FIXME: warn on _Countof on an array parameter. Not warning on it
4483 // currently because there are papers in WG14 about array types which do
4484 // not decay that could impact this behavior, so we want to see if anything
4485 // changes here before coming up with a warning group for _Countof-related
4486 // diagnostics.
4487 }
4488
4489 if (ExprKind == UETT_SizeOf) {
4490 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4491 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4492 QualType OType = PVD->getOriginalType();
4493 QualType Type = PVD->getType();
4494 if (Type->isPointerType() && OType->isArrayType()) {
4495 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4496 << Type << OType;
4497 Diag(PVD->getLocation(), diag::note_declared_at);
4498 }
4499 }
4500 }
4501
4502 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4503 // decays into a pointer and returns an unintended result. This is most
4504 // likely a typo for "sizeof(array) op x".
4505 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4506 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4507 BO->getLHS());
4508 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4509 BO->getRHS());
4510 }
4511 }
4512
4513 return false;
4514}
4515
4516static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4517 // Cannot know anything else if the expression is dependent.
4518 if (E->isTypeDependent())
4519 return false;
4520
4521 if (E->getObjectKind() == OK_BitField) {
4522 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4523 << 1 << E->getSourceRange();
4524 return true;
4525 }
4526
4527 ValueDecl *D = nullptr;
4528 Expr *Inner = E->IgnoreParens();
4529 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4530 D = DRE->getDecl();
4531 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4532 D = ME->getMemberDecl();
4533 }
4534
4535 // If it's a field, require the containing struct to have a
4536 // complete definition so that we can compute the layout.
4537 //
4538 // This can happen in C++11 onwards, either by naming the member
4539 // in a way that is not transformed into a member access expression
4540 // (in an unevaluated operand, for instance), or by naming the member
4541 // in a trailing-return-type.
4542 //
4543 // For the record, since __alignof__ on expressions is a GCC
4544 // extension, GCC seems to permit this but always gives the
4545 // nonsensical answer 0.
4546 //
4547 // We don't really need the layout here --- we could instead just
4548 // directly check for all the appropriate alignment-lowing
4549 // attributes --- but that would require duplicating a lot of
4550 // logic that just isn't worth duplicating for such a marginal
4551 // use-case.
4552 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4553 // Fast path this check, since we at least know the record has a
4554 // definition if we can find a member of it.
4555 if (!FD->getParent()->isCompleteDefinition()) {
4556 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4557 << E->getSourceRange();
4558 return true;
4559 }
4560
4561 // Otherwise, if it's a field, and the field doesn't have
4562 // reference type, then it must have a complete type (or be a
4563 // flexible array member, which we explicitly want to
4564 // white-list anyway), which makes the following checks trivial.
4565 if (!FD->getType()->isReferenceType())
4566 return false;
4567 }
4568
4569 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4570}
4571
4573 E = E->IgnoreParens();
4574
4575 // Cannot know anything else if the expression is dependent.
4576 if (E->isTypeDependent())
4577 return false;
4578
4579 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4580}
4581
4583 CapturingScopeInfo *CSI) {
4584 assert(T->isVariablyModifiedType());
4585 assert(CSI != nullptr);
4586
4587 // We're going to walk down into the type and look for VLA expressions.
4588 do {
4589 const Type *Ty = T.getTypePtr();
4590 switch (Ty->getTypeClass()) {
4591#define TYPE(Class, Base)
4592#define ABSTRACT_TYPE(Class, Base)
4593#define NON_CANONICAL_TYPE(Class, Base)
4594#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4595#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4596#include "clang/AST/TypeNodes.inc"
4597 T = QualType();
4598 break;
4599 // These types are never variably-modified.
4600 case Type::Builtin:
4601 case Type::Complex:
4602 case Type::Vector:
4603 case Type::ExtVector:
4604 case Type::ConstantMatrix:
4605 case Type::Record:
4606 case Type::Enum:
4607 case Type::TemplateSpecialization:
4608 case Type::ObjCObject:
4609 case Type::ObjCInterface:
4610 case Type::ObjCObjectPointer:
4611 case Type::ObjCTypeParam:
4612 case Type::Pipe:
4613 case Type::BitInt:
4614 case Type::HLSLInlineSpirv:
4615 llvm_unreachable("type class is never variably-modified!");
4616 case Type::Adjusted:
4617 T = cast<AdjustedType>(Ty)->getOriginalType();
4618 break;
4619 case Type::Decayed:
4620 T = cast<DecayedType>(Ty)->getPointeeType();
4621 break;
4622 case Type::ArrayParameter:
4623 T = cast<ArrayParameterType>(Ty)->getElementType();
4624 break;
4625 case Type::Pointer:
4626 T = cast<PointerType>(Ty)->getPointeeType();
4627 break;
4628 case Type::BlockPointer:
4629 T = cast<BlockPointerType>(Ty)->getPointeeType();
4630 break;
4631 case Type::LValueReference:
4632 case Type::RValueReference:
4633 T = cast<ReferenceType>(Ty)->getPointeeType();
4634 break;
4635 case Type::MemberPointer:
4636 T = cast<MemberPointerType>(Ty)->getPointeeType();
4637 break;
4638 case Type::ConstantArray:
4639 case Type::IncompleteArray:
4640 // Losing element qualification here is fine.
4641 T = cast<ArrayType>(Ty)->getElementType();
4642 break;
4643 case Type::VariableArray: {
4644 // Losing element qualification here is fine.
4646
4647 // Unknown size indication requires no size computation.
4648 // Otherwise, evaluate and record it.
4649 auto Size = VAT->getSizeExpr();
4650 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4652 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4653
4654 T = VAT->getElementType();
4655 break;
4656 }
4657 case Type::FunctionProto:
4658 case Type::FunctionNoProto:
4659 T = cast<FunctionType>(Ty)->getReturnType();
4660 break;
4661 case Type::Paren:
4662 case Type::TypeOf:
4663 case Type::UnaryTransform:
4664 case Type::Attributed:
4665 case Type::BTFTagAttributed:
4666 case Type::OverflowBehavior:
4667 case Type::HLSLAttributedResource:
4668 case Type::SubstTemplateTypeParm:
4669 case Type::MacroQualified:
4670 case Type::CountAttributed:
4671 // Keep walking after single level desugaring.
4672 T = T.getSingleStepDesugaredType(Context);
4673 break;
4674 case Type::Typedef:
4675 T = cast<TypedefType>(Ty)->desugar();
4676 break;
4677 case Type::Decltype:
4678 T = cast<DecltypeType>(Ty)->desugar();
4679 break;
4680 case Type::PackIndexing:
4681 T = cast<PackIndexingType>(Ty)->desugar();
4682 break;
4683 case Type::Using:
4684 T = cast<UsingType>(Ty)->desugar();
4685 break;
4686 case Type::Auto:
4687 case Type::DeducedTemplateSpecialization:
4688 T = cast<DeducedType>(Ty)->getDeducedType();
4689 break;
4690 case Type::TypeOfExpr:
4691 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4692 break;
4693 case Type::Atomic:
4694 T = cast<AtomicType>(Ty)->getValueType();
4695 break;
4696 case Type::PredefinedSugar:
4697 T = cast<PredefinedSugarType>(Ty)->desugar();
4698 break;
4699 }
4700 } while (!T.isNull() && T->isVariablyModifiedType());
4701}
4702
4704 SourceLocation OpLoc,
4705 SourceRange ExprRange,
4706 UnaryExprOrTypeTrait ExprKind,
4707 StringRef KWName) {
4708 if (ExprType->isDependentType())
4709 return false;
4710
4711 // C++ [expr.sizeof]p2:
4712 // When applied to a reference or a reference type, the result
4713 // is the size of the referenced type.
4714 // C++11 [expr.alignof]p3:
4715 // When alignof is applied to a reference type, the result
4716 // shall be the alignment of the referenced type.
4717 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4718 ExprType = Ref->getPointeeType();
4719
4720 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4721 // When alignof or _Alignof is applied to an array type, the result
4722 // is the alignment of the element type.
4723 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4724 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4725 // If the trait is 'alignof' in C before C2y, the ability to apply the
4726 // trait to an incomplete array is an extension.
4727 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4728 ExprType->isIncompleteArrayType())
4729 Diag(OpLoc, getLangOpts().C2y
4730 ? diag::warn_c2y_compat_alignof_incomplete_array
4731 : diag::ext_c2y_alignof_incomplete_array);
4732 ExprType = Context.getBaseElementType(ExprType);
4733 }
4734
4735 if (ExprKind == UETT_VecStep)
4736 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4737
4738 if (ExprKind == UETT_VectorElements)
4739 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4740 ExprRange);
4741
4742 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4743 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4744 ExprRange);
4745
4746 // Explicitly list some types as extensions.
4747 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4748 ExprKind))
4749 return false;
4750
4752 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4753 KWName, ExprRange))
4754 return true;
4755
4756 if (ExprType->isFunctionType()) {
4757 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4758 return true;
4759 }
4760
4761 if (ExprKind == UETT_CountOf) {
4762 // The type has to be an array type. We already checked for incomplete
4763 // types above.
4764 if (!ExprType->isArrayType()) {
4765 Diag(OpLoc, diag::err_countof_arg_not_array_type) << ExprType;
4766 return true;
4767 }
4768 }
4769
4770 // WebAssembly tables are always illegal operands to unary expressions and
4771 // type traits.
4772 if (Context.getTargetInfo().getTriple().isWasm() &&
4773 ExprType->isWebAssemblyTableType()) {
4774 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4775 << getTraitSpelling(ExprKind);
4776 return true;
4777 }
4778
4779 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4780 ExprKind))
4781 return true;
4782
4783 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4784 if (auto *TT = ExprType->getAs<TypedefType>()) {
4785 for (auto I = FunctionScopes.rbegin(),
4786 E = std::prev(FunctionScopes.rend());
4787 I != E; ++I) {
4788 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4789 if (CSI == nullptr)
4790 break;
4791 DeclContext *DC = nullptr;
4792 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4793 DC = LSI->CallOperator;
4794 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4795 DC = CRSI->TheCapturedDecl;
4796 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4797 DC = BSI->TheDecl;
4798 if (DC) {
4799 if (DC->containsDecl(TT->getDecl()))
4800 break;
4801 captureVariablyModifiedType(Context, ExprType, CSI);
4802 }
4803 }
4804 }
4805 }
4806
4807 return false;
4808}
4809
4811 SourceLocation OpLoc,
4812 UnaryExprOrTypeTrait ExprKind,
4813 SourceRange R) {
4814 if (!TInfo)
4815 return ExprError();
4816
4817 QualType T = TInfo->getType();
4818
4819 if (!T->isDependentType() &&
4820 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4821 getTraitSpelling(ExprKind)))
4822 return ExprError();
4823
4824 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4825 // properly deal with VLAs in nested calls of sizeof and typeof.
4826 if (currentEvaluationContext().isUnevaluated() &&
4827 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4828 (ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4829 TInfo->getType()->isVariablyModifiedType())
4830 TInfo = TransformToPotentiallyEvaluated(TInfo);
4831
4832 // It's possible that the transformation above failed.
4833 if (!TInfo)
4834 return ExprError();
4835
4836 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4837 return new (Context) UnaryExprOrTypeTraitExpr(
4838 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4839}
4840
4843 UnaryExprOrTypeTrait ExprKind) {
4845 if (PE.isInvalid())
4846 return ExprError();
4847
4848 E = PE.get();
4849
4850 // Verify that the operand is valid.
4851 bool isInvalid = false;
4852 if (E->isTypeDependent()) {
4853 // Delay type-checking for type-dependent expressions.
4854 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4855 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4856 } else if (ExprKind == UETT_VecStep) {
4858 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4859 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4860 isInvalid = true;
4861 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4862 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4863 isInvalid = true;
4864 } else if (ExprKind == UETT_VectorElements || ExprKind == UETT_SizeOf ||
4865 ExprKind == UETT_CountOf) { // FIXME: __datasizeof?
4867 }
4868
4869 if (isInvalid)
4870 return ExprError();
4871
4872 if ((ExprKind == UETT_SizeOf || ExprKind == UETT_CountOf) &&
4873 E->getType()->isVariableArrayType()) {
4875 if (PE.isInvalid()) return ExprError();
4876 E = PE.get();
4877 }
4878
4879 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4880 return new (Context) UnaryExprOrTypeTraitExpr(
4881 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4882}
4883
4886 UnaryExprOrTypeTrait ExprKind, bool IsType,
4887 void *TyOrEx, SourceRange ArgRange) {
4888 // If error parsing type, ignore.
4889 if (!TyOrEx) return ExprError();
4890
4891 if (IsType) {
4892 TypeSourceInfo *TInfo;
4893 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4894 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4895 }
4896
4897 Expr *ArgEx = (Expr *)TyOrEx;
4898 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4899 return Result;
4900}
4901
4903 SourceLocation OpLoc, SourceRange R) {
4904 if (!TInfo)
4905 return true;
4906 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4907 UETT_AlignOf, KWName);
4908}
4909
4911 SourceLocation OpLoc, SourceRange R) {
4912 TypeSourceInfo *TInfo;
4914 &TInfo);
4915 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4916}
4917
4919 bool IsReal) {
4920 if (V.get()->isTypeDependent())
4921 return S.Context.DependentTy;
4922
4923 // _Real and _Imag are only l-values for normal l-values.
4924 if (V.get()->getObjectKind() != OK_Ordinary) {
4925 V = S.DefaultLvalueConversion(V.get());
4926 if (V.isInvalid())
4927 return QualType();
4928 }
4929
4930 // These operators return the element type of a complex type.
4931 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4932 return CT->getElementType();
4933
4934 // Otherwise they pass through real integer and floating point types here.
4935 if (V.get()->getType()->isArithmeticType())
4936 return V.get()->getType();
4937
4938 // Test for placeholders.
4939 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4940 if (PR.isInvalid()) return QualType();
4941 if (PR.get() != V.get()) {
4942 V = PR;
4943 return CheckRealImagOperand(S, V, Loc, IsReal);
4944 }
4945
4946 // Reject anything else.
4947 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4948 << (IsReal ? "__real" : "__imag");
4949 return QualType();
4950}
4951
4952
4953
4956 tok::TokenKind Kind, Expr *Input) {
4958 switch (Kind) {
4959 default: llvm_unreachable("Unknown unary op!");
4960 case tok::plusplus: Opc = UO_PostInc; break;
4961 case tok::minusminus: Opc = UO_PostDec; break;
4962 }
4963
4964 // Since this might is a postfix expression, get rid of ParenListExprs.
4966 if (Result.isInvalid()) return ExprError();
4967 Input = Result.get();
4968
4969 return BuildUnaryOp(S, OpLoc, Opc, Input);
4970}
4971
4972/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4973///
4974/// \return true on error
4976 SourceLocation opLoc,
4977 Expr *op) {
4978 assert(op->getType()->isObjCObjectPointerType());
4980 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4981 return false;
4982
4983 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4985 << op->getSourceRange();
4986 return true;
4987}
4988
4990 auto *BaseNoParens = Base->IgnoreParens();
4991 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4992 return MSProp->getPropertyDecl()->getType()->isArrayType();
4993 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4994}
4995
4996// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4997// Typically this is DependentTy, but can sometimes be more precise.
4998//
4999// There are cases when we could determine a non-dependent type:
5000// - LHS and RHS may have non-dependent types despite being type-dependent
5001// (e.g. unbounded array static members of the current instantiation)
5002// - one may be a dependent-sized array with known element type
5003// - one may be a dependent-typed valid index (enum in current instantiation)
5004//
5005// We *always* return a dependent type, in such cases it is DependentTy.
5006// This avoids creating type-dependent expressions with non-dependent types.
5007// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5009 const ASTContext &Ctx) {
5010 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5011 QualType LTy = LHS->getType(), RTy = RHS->getType();
5013 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5014 if (const PointerType *PT = LTy->getAs<PointerType>())
5015 Result = PT->getPointeeType();
5016 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5017 Result = AT->getElementType();
5018 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5019 if (const PointerType *PT = RTy->getAs<PointerType>())
5020 Result = PT->getPointeeType();
5021 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5022 Result = AT->getElementType();
5023 }
5024 // Ensure we return a dependent type.
5025 return Result->isDependentType() ? Result : Ctx.DependentTy;
5026}
5027
5029 SourceLocation lbLoc,
5030 MultiExprArg ArgExprs,
5031 SourceLocation rbLoc) {
5032
5033 if (base && !base->getType().isNull() &&
5034 base->hasPlaceholderType(BuiltinType::ArraySection)) {
5035 auto *AS = cast<ArraySectionExpr>(base);
5036 if (AS->isOMPArraySection())
5038 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
5039 /*Length*/ nullptr,
5040 /*Stride=*/nullptr, rbLoc);
5041
5042 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
5043 SourceLocation(), /*Length*/ nullptr,
5044 rbLoc);
5045 }
5046
5047 // Since this might be a postfix expression, get rid of ParenListExprs.
5048 if (isa<ParenListExpr>(base)) {
5050 if (result.isInvalid())
5051 return ExprError();
5052 base = result.get();
5053 }
5054
5055 // Check if base and idx form a MatrixSubscriptExpr.
5056 //
5057 // Helper to check for comma expressions, which are not allowed as indices for
5058 // matrix subscript expressions.
5059 //
5060 // In C++23, we get multiple arguments instead of a comma expression.
5061 auto CheckAndReportCommaError = [&](Expr *E) {
5062 if (ArgExprs.size() > 1 ||
5063 (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp())) {
5064 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
5065 << SourceRange(base->getBeginLoc(), rbLoc);
5066 return true;
5067 }
5068 return false;
5069 };
5070 // The matrix subscript operator ([][])is considered a single operator.
5071 // Separating the index expressions by parenthesis is not allowed.
5072 if (base && !base->getType().isNull() &&
5073 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
5074 !isa<MatrixSubscriptExpr>(base)) {
5075 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
5076 << SourceRange(base->getBeginLoc(), rbLoc);
5077 return ExprError();
5078 }
5079 // If the base is a MatrixSubscriptExpr, try to create a new
5080 // MatrixSubscriptExpr.
5081 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
5082 if (matSubscriptE) {
5083 if (CheckAndReportCommaError(ArgExprs.front()))
5084 return ExprError();
5085
5086 assert(matSubscriptE->isIncomplete() &&
5087 "base has to be an incomplete matrix subscript");
5088 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
5089 matSubscriptE->getRowIdx(),
5090 ArgExprs.front(), rbLoc);
5091 }
5092 if (base->getType()->isWebAssemblyTableType()) {
5093 Diag(base->getExprLoc(), diag::err_wasm_table_art)
5094 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5095 return ExprError();
5096 }
5097
5098 CheckInvalidBuiltinCountedByRef(base,
5100
5101 // Handle any non-overload placeholder types in the base and index
5102 // expressions. We can't handle overloads here because the other
5103 // operand might be an overloadable type, in which case the overload
5104 // resolution for the operator overload should get the first crack
5105 // at the overload.
5106 bool IsMSPropertySubscript = false;
5107 if (base->getType()->isNonOverloadPlaceholderType()) {
5108 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
5109 if (!IsMSPropertySubscript) {
5110 ExprResult result = CheckPlaceholderExpr(base);
5111 if (result.isInvalid())
5112 return ExprError();
5113 base = result.get();
5114 }
5115 }
5116
5117 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5118 if (base->getType()->isMatrixType()) {
5119 if (CheckAndReportCommaError(ArgExprs.front()))
5120 return ExprError();
5121
5122 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5123 rbLoc);
5124 }
5125
5126 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5127 Expr *idx = ArgExprs[0];
5128 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5130 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5131 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5132 << SourceRange(base->getBeginLoc(), rbLoc);
5133 }
5134 }
5135
5136 if (ArgExprs.size() == 1 &&
5137 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5138 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5139 if (result.isInvalid())
5140 return ExprError();
5141 ArgExprs[0] = result.get();
5142 } else {
5143 if (CheckArgsForPlaceholders(ArgExprs))
5144 return ExprError();
5145 }
5146
5147 // Build an unanalyzed expression if either operand is type-dependent.
5148 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5149 (base->isTypeDependent() ||
5151 !isa<PackExpansionExpr>(ArgExprs[0])) {
5152 return new (Context) ArraySubscriptExpr(
5153 base, ArgExprs.front(),
5154 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5155 VK_LValue, OK_Ordinary, rbLoc);
5156 }
5157
5158 // MSDN, property (C++)
5159 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5160 // This attribute can also be used in the declaration of an empty array in a
5161 // class or structure definition. For example:
5162 // __declspec(property(get=GetX, put=PutX)) int x[];
5163 // The above statement indicates that x[] can be used with one or more array
5164 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5165 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5166 if (IsMSPropertySubscript) {
5167 if (ArgExprs.size() > 1) {
5168 Diag(base->getExprLoc(),
5169 diag::err_ms_property_subscript_expects_single_arg);
5170 return ExprError();
5171 }
5172
5173 // Build MS property subscript expression if base is MS property reference
5174 // or MS property subscript.
5175 return new (Context)
5176 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5177 VK_LValue, OK_Ordinary, rbLoc);
5178 }
5179
5180 // Use C++ overloaded-operator rules if either operand has record
5181 // type. The spec says to do this if either type is *overloadable*,
5182 // but enum types can't declare subscript operators or conversion
5183 // operators, so there's nothing interesting for overload resolution
5184 // to do if there aren't any record types involved.
5185 //
5186 // ObjC pointers have their own subscripting logic that is not tied
5187 // to overload resolution and so should not take this path.
5188 //
5189 // Issue a better diagnostic if we tried to pass multiple arguments to
5190 // a builtin subscript operator rather than diagnosing this as a generic
5191 // overload resolution failure.
5192 if (ArgExprs.size() != 1 && !base->getType()->isDependentType() &&
5193 !base->getType()->isRecordType() &&
5194 !base->getType()->isObjCObjectPointerType()) {
5195 Diag(base->getExprLoc(), diag::err_ovl_builtin_subscript_expects_single_arg)
5196 << base->getType() << base->getSourceRange();
5197 return ExprError();
5198 }
5199
5201 ((base->getType()->isRecordType() ||
5202 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5203 ArgExprs[0]->getType()->isRecordType())))) {
5204 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5205 }
5206
5207 ExprResult Res =
5208 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5209
5210 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5211 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5212
5213 return Res;
5214}
5215
5218 InitializationKind Kind =
5220 InitializationSequence InitSeq(*this, Entity, Kind, E);
5221 return InitSeq.Perform(*this, Entity, Kind, E);
5222}
5223
5225 Expr *RowIdx,
5226 SourceLocation RBLoc) {
5228 if (BaseR.isInvalid())
5229 return BaseR;
5230 Base = BaseR.get();
5231
5232 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5233 if (RowR.isInvalid())
5234 return RowR;
5235 RowIdx = RowR.get();
5236
5237 // Build an unanalyzed expression if any of the operands is type-dependent.
5238 if (Base->isTypeDependent() || RowIdx->isTypeDependent())
5239 return new (Context)
5240 MatrixSingleSubscriptExpr(Base, RowIdx, Context.DependentTy, RBLoc);
5241
5242 // Check that IndexExpr is an integer expression. If it is a constant
5243 // expression, check that it is less than Dim (= the number of elements in the
5244 // corresponding dimension).
5245 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5246 bool IsColumnIdx) -> Expr * {
5247 if (!IndexExpr->getType()->isIntegerType() &&
5248 !IndexExpr->isTypeDependent()) {
5249 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5250 << IsColumnIdx;
5251 return nullptr;
5252 }
5253
5254 if (std::optional<llvm::APSInt> Idx =
5255 IndexExpr->getIntegerConstantExpr(Context)) {
5256 if ((*Idx < 0 || *Idx >= Dim)) {
5257 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5258 << IsColumnIdx << Dim;
5259 return nullptr;
5260 }
5261 }
5262
5263 ExprResult ConvExpr = IndexExpr;
5264 assert(!ConvExpr.isInvalid() &&
5265 "should be able to convert any integer type to size type");
5266 return ConvExpr.get();
5267 };
5268
5269 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5270 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5271 if (!RowIdx)
5272 return ExprError();
5273
5274 QualType RowVecQT =
5275 Context.getExtVectorType(MTy->getElementType(), MTy->getNumColumns());
5276
5277 return new (Context) MatrixSingleSubscriptExpr(Base, RowIdx, RowVecQT, RBLoc);
5278}
5279
5281 Expr *ColumnIdx,
5282 SourceLocation RBLoc) {
5284 if (BaseR.isInvalid())
5285 return BaseR;
5286 Base = BaseR.get();
5287
5288 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5289 if (RowR.isInvalid())
5290 return RowR;
5291 RowIdx = RowR.get();
5292
5293 if (!ColumnIdx)
5294 return new (Context) MatrixSubscriptExpr(
5295 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5296
5297 // Build an unanalyzed expression if any of the operands is type-dependent.
5298 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5299 ColumnIdx->isTypeDependent())
5300 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5301 Context.DependentTy, RBLoc);
5302
5303 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5304 if (ColumnR.isInvalid())
5305 return ColumnR;
5306 ColumnIdx = ColumnR.get();
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 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5338 if (!RowIdx || !ColumnIdx)
5339 return ExprError();
5340
5341 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5342 MTy->getElementType(), RBLoc);
5343}
5344
5345void Sema::CheckAddressOfNoDeref(const Expr *E) {
5346 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5347 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5348
5349 // For expressions like `&(*s).b`, the base is recorded and what should be
5350 // checked.
5351 const MemberExpr *Member = nullptr;
5352 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5353 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5354
5355 LastRecord.PossibleDerefs.erase(StrippedExpr);
5356}
5357
5358void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5360 return;
5361
5362 QualType ResultTy = E->getType();
5363 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5364
5365 // Bail if the element is an array since it is not memory access.
5366 if (isa<ArrayType>(ResultTy))
5367 return;
5368
5369 if (ResultTy->hasAttr(attr::NoDeref)) {
5370 LastRecord.PossibleDerefs.insert(E);
5371 return;
5372 }
5373
5374 // Check if the base type is a pointer to a member access of a struct
5375 // marked with noderef.
5376 const Expr *Base = E->getBase();
5377 QualType BaseTy = Base->getType();
5378 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5379 // Not a pointer access
5380 return;
5381
5382 const MemberExpr *Member = nullptr;
5383 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5384 Member->isArrow())
5385 Base = Member->getBase();
5386
5387 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5388 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5389 LastRecord.PossibleDerefs.insert(E);
5390 }
5391}
5392
5395 Expr *Idx, SourceLocation RLoc) {
5396 Expr *LHSExp = Base;
5397 Expr *RHSExp = Idx;
5398
5401
5402 // Per C++ core issue 1213, the result is an xvalue if either operand is
5403 // a non-lvalue array, and an lvalue otherwise.
5404 if (getLangOpts().CPlusPlus11) {
5405 for (auto *Op : {LHSExp, RHSExp}) {
5406 Op = Op->IgnoreImplicit();
5407 if (Op->getType()->isArrayType() && !Op->isLValue())
5408 VK = VK_XValue;
5409 }
5410 }
5411
5412 // Perform default conversions.
5413 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5415 if (Result.isInvalid())
5416 return ExprError();
5417 LHSExp = Result.get();
5418 }
5420 if (Result.isInvalid())
5421 return ExprError();
5422 RHSExp = Result.get();
5423
5424 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5425
5426 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5427 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5428 // in the subscript position. As a result, we need to derive the array base
5429 // and index from the expression types.
5430 Expr *BaseExpr, *IndexExpr;
5431 QualType ResultType;
5432 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5433 BaseExpr = LHSExp;
5434 IndexExpr = RHSExp;
5435 ResultType =
5437 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5438 BaseExpr = LHSExp;
5439 IndexExpr = RHSExp;
5440 ResultType = PTy->getPointeeType();
5441 } else if (const ObjCObjectPointerType *PTy =
5442 LHSTy->getAs<ObjCObjectPointerType>()) {
5443 BaseExpr = LHSExp;
5444 IndexExpr = RHSExp;
5445
5446 // Use custom logic if this should be the pseudo-object subscript
5447 // expression.
5448 if (!LangOpts.isSubscriptPointerArithmetic())
5449 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5450 nullptr, nullptr);
5451
5452 ResultType = PTy->getPointeeType();
5453 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5454 // Handle the uncommon case of "123[Ptr]".
5455 BaseExpr = RHSExp;
5456 IndexExpr = LHSExp;
5457 ResultType = PTy->getPointeeType();
5458 } else if (const ObjCObjectPointerType *PTy =
5459 RHSTy->getAs<ObjCObjectPointerType>()) {
5460 // Handle the uncommon case of "123[Ptr]".
5461 BaseExpr = RHSExp;
5462 IndexExpr = LHSExp;
5463 ResultType = PTy->getPointeeType();
5464 if (!LangOpts.isSubscriptPointerArithmetic()) {
5465 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5466 << ResultType << BaseExpr->getSourceRange();
5467 return ExprError();
5468 }
5469 } else if (LHSTy->isSubscriptableVectorType()) {
5470 if (LHSTy->isBuiltinType() &&
5471 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5472 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5473 if (BTy->isSVEBool())
5474 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5475 << LHSExp->getSourceRange()
5476 << RHSExp->getSourceRange());
5477 ResultType = BTy->getSveEltType(Context);
5478 } else {
5479 const VectorType *VTy = LHSTy->getAs<VectorType>();
5480 ResultType = VTy->getElementType();
5481 }
5482 BaseExpr = LHSExp; // vectors: V[123]
5483 IndexExpr = RHSExp;
5484 // We apply C++ DR1213 to vector subscripting too.
5485 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5486 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5487 if (Materialized.isInvalid())
5488 return ExprError();
5489 LHSExp = Materialized.get();
5490 }
5491 VK = LHSExp->getValueKind();
5492 if (VK != VK_PRValue)
5493 OK = OK_VectorComponent;
5494
5495 QualType BaseType = BaseExpr->getType();
5496 Qualifiers BaseQuals = BaseType.getQualifiers();
5497 Qualifiers MemberQuals = ResultType.getQualifiers();
5498 Qualifiers Combined = BaseQuals + MemberQuals;
5499 if (Combined != MemberQuals)
5500 ResultType = Context.getQualifiedType(ResultType, Combined);
5501 } else if (LHSTy->isArrayType()) {
5502 // If we see an array that wasn't promoted by
5503 // DefaultFunctionArrayLvalueConversion, it must be an array that
5504 // wasn't promoted because of the C90 rule that doesn't
5505 // allow promoting non-lvalue arrays. Warn, then
5506 // force the promotion here.
5507 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5508 << LHSExp->getSourceRange();
5509 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5510 CK_ArrayToPointerDecay).get();
5511 LHSTy = LHSExp->getType();
5512
5513 BaseExpr = LHSExp;
5514 IndexExpr = RHSExp;
5515 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5516 } else if (RHSTy->isArrayType()) {
5517 // Same as previous, except for 123[f().a] case
5518 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5519 << RHSExp->getSourceRange();
5520 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5521 CK_ArrayToPointerDecay).get();
5522 RHSTy = RHSExp->getType();
5523
5524 BaseExpr = RHSExp;
5525 IndexExpr = LHSExp;
5526 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5527 } else {
5528 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5529 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5530 }
5531 // C99 6.5.2.1p1
5532 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5533 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5534 << IndexExpr->getSourceRange());
5535
5536 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5537 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5538 !IndexExpr->isTypeDependent()) {
5539 std::optional<llvm::APSInt> IntegerContantExpr =
5541 if (!IntegerContantExpr.has_value() ||
5542 IntegerContantExpr.value().isNegative())
5543 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5544 }
5545
5546 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5547 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5548 // type. Note that Functions are not objects, and that (in C99 parlance)
5549 // incomplete types are not object types.
5550 if (ResultType->isFunctionType()) {
5551 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5552 << ResultType << BaseExpr->getSourceRange();
5553 return ExprError();
5554 }
5555
5556 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5557 // GNU extension: subscripting on pointer to void
5558 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5559 << BaseExpr->getSourceRange();
5560
5561 // C forbids expressions of unqualified void type from being l-values.
5562 // See IsCForbiddenLValueType.
5563 if (!ResultType.hasQualifiers())
5564 VK = VK_PRValue;
5565 } else if (!ResultType->isDependentType() &&
5566 !ResultType.isWebAssemblyReferenceType() &&
5568 LLoc, ResultType,
5569 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5570 return ExprError();
5571
5572 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5573 !ResultType.isCForbiddenLValueType());
5574
5576 FunctionScopes.size() > 1) {
5577 if (auto *TT =
5578 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5579 for (auto I = FunctionScopes.rbegin(),
5580 E = std::prev(FunctionScopes.rend());
5581 I != E; ++I) {
5582 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5583 if (CSI == nullptr)
5584 break;
5585 DeclContext *DC = nullptr;
5586 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5587 DC = LSI->CallOperator;
5588 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5589 DC = CRSI->TheCapturedDecl;
5590 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5591 DC = BSI->TheDecl;
5592 if (DC) {
5593 if (DC->containsDecl(TT->getDecl()))
5594 break;
5596 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5597 }
5598 }
5599 }
5600 }
5601
5602 return new (Context)
5603 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5604}
5605
5607 ParmVarDecl *Param, Expr *RewrittenInit,
5608 bool SkipImmediateInvocations) {
5609 if (Param->hasUnparsedDefaultArg()) {
5610 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5611 // If we've already cleared out the location for the default argument,
5612 // that means we're parsing it right now.
5613 if (!UnparsedDefaultArgLocs.count(Param)) {
5614 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5615 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5616 Param->setInvalidDecl();
5617 return true;
5618 }
5619
5620 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5621 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5623 diag::note_default_argument_declared_here);
5624 return true;
5625 }
5626
5627 if (Param->hasUninstantiatedDefaultArg()) {
5628 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5629 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5630 return true;
5631 }
5632
5633 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5634 assert(Init && "default argument but no initializer?");
5635
5636 // If the default expression creates temporaries, we need to
5637 // push them to the current stack of expression temporaries so they'll
5638 // be properly destroyed.
5639 // FIXME: We should really be rebuilding the default argument with new
5640 // bound temporaries; see the comment in PR5810.
5641 // We don't need to do that with block decls, though, because
5642 // blocks in default argument expression can never capture anything.
5643 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5644 // Set the "needs cleanups" bit regardless of whether there are
5645 // any explicit objects.
5646 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5647 // Append all the objects to the cleanup list. Right now, this
5648 // should always be a no-op, because blocks in default argument
5649 // expressions should never be able to capture anything.
5650 assert(!InitWithCleanup->getNumObjects() &&
5651 "default argument expression has capturing blocks?");
5652 }
5653 // C++ [expr.const]p15.1:
5654 // An expression or conversion is in an immediate function context if it is
5655 // potentially evaluated and [...] its innermost enclosing non-block scope
5656 // is a function parameter scope of an immediate function.
5658 *this,
5662 Param);
5663 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5664 SkipImmediateInvocations;
5665 runWithSufficientStackSpace(CallLoc, [&] {
5666 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5667 });
5668 return false;
5669}
5670
5675 }
5676
5677 bool HasImmediateCalls = false;
5678
5679 bool VisitCallExpr(CallExpr *E) override {
5680 if (const FunctionDecl *FD = E->getDirectCallee())
5681 HasImmediateCalls |= FD->isImmediateFunction();
5683 }
5684
5686 if (const FunctionDecl *FD = E->getConstructor())
5687 HasImmediateCalls |= FD->isImmediateFunction();
5689 }
5690
5691 // SourceLocExpr are not immediate invocations
5692 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5693 // need to be rebuilt so that they refer to the correct SourceLocation and
5694 // DeclContext.
5696 HasImmediateCalls = true;
5698 }
5699
5700 // A nested lambda might have parameters with immediate invocations
5701 // in their default arguments.
5702 // The compound statement is not visited (as it does not constitute a
5703 // subexpression).
5704 // FIXME: We should consider visiting and transforming captures
5705 // with init expressions.
5706 bool VisitLambdaExpr(LambdaExpr *E) override {
5707 return VisitCXXMethodDecl(E->getCallOperator());
5708 }
5709
5711 return TraverseStmt(E->getExpr());
5712 }
5713
5715 return TraverseStmt(E->getExpr());
5716 }
5717};
5718
5720 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5723
5724 bool AlwaysRebuild() { return true; }
5725
5726 // Lambda can only have immediate invocations in the default
5727 // args of their parameters, which is transformed upon calling the closure.
5728 // The body is not a subexpression, so we have nothing to do.
5729 // FIXME: Immediate calls in capture initializers should be transformed.
5732
5733 // Make sure we don't rebuild the this pointer as it would
5734 // cause it to incorrectly point it to the outermost class
5735 // in the case of nested struct initialization.
5737
5738 // Rewrite to source location to refer to the context in which they are used.
5740 DeclContext *DC = E->getParentContext();
5741 if (DC == SemaRef.CurContext)
5742 return E;
5743
5744 // FIXME: During instantiation, because the rebuild of defaults arguments
5745 // is not always done in the context of the template instantiator,
5746 // we run the risk of producing a dependent source location
5747 // that would never be rebuilt.
5748 // This usually happens during overload resolution, or in contexts
5749 // where the value of the source location does not matter.
5750 // However, we should find a better way to deal with source location
5751 // of function templates.
5752 if (!SemaRef.CurrentInstantiationScope ||
5753 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5754 DC = SemaRef.CurContext;
5755
5756 return getDerived().RebuildSourceLocExpr(
5757 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5758 }
5759};
5760
5762 FunctionDecl *FD, ParmVarDecl *Param,
5763 Expr *Init) {
5764 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5765
5766 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5767 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5768 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5769 InitializationContext =
5771 if (!InitializationContext.has_value())
5772 InitializationContext.emplace(CallLoc, Param, CurContext);
5773
5774 if (!Init && !Param->hasUnparsedDefaultArg()) {
5775 // Mark that we are replacing a default argument first.
5776 // If we are instantiating a template we won't have to
5777 // retransform immediate calls.
5778 // C++ [expr.const]p15.1:
5779 // An expression or conversion is in an immediate function context if it
5780 // is potentially evaluated and [...] its innermost enclosing non-block
5781 // scope is a function parameter scope of an immediate function.
5783 *this,
5787 Param);
5788
5789 if (Param->hasUninstantiatedDefaultArg()) {
5790 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5791 return ExprError();
5792 }
5793 // CWG2631
5794 // An immediate invocation that is not evaluated where it appears is
5795 // evaluated and checked for whether it is a constant expression at the
5796 // point where the enclosing initializer is used in a function call.
5798 if (!NestedDefaultChecking)
5799 V.TraverseDecl(Param);
5800
5801 // Rewrite the call argument that was created from the corresponding
5802 // parameter's default argument.
5803 if (V.HasImmediateCalls ||
5804 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5805 if (V.HasImmediateCalls)
5806 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5807 CallLoc, Param, CurContext};
5808 // Pass down lifetime extending flag, and collect temporaries in
5809 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5813 ExprResult Res;
5814 runWithSufficientStackSpace(CallLoc, [&] {
5815 Res = Immediate.TransformInitializer(Param->getInit(),
5816 /*NotCopy=*/false);
5817 });
5818 if (Res.isInvalid())
5819 return ExprError();
5820 Res = ConvertParamDefaultArgument(Param, Res.get(),
5821 Res.get()->getBeginLoc());
5822 if (Res.isInvalid())
5823 return ExprError();
5824 Init = Res.get();
5825 }
5826 }
5827
5829 CallLoc, FD, Param, Init,
5830 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5831 return ExprError();
5832
5833 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5834 Init, InitializationContext->Context);
5835}
5836
5838 FieldDecl *Field) {
5839 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5840 return Pattern;
5841 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5842 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5844 ClassPattern->lookup(Field->getDeclName());
5845 auto Rng = llvm::make_filter_range(
5846 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5847 if (Rng.empty())
5848 return nullptr;
5849 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5850 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5851 // && "Duplicated instantiation pattern for field decl");
5852 return cast<FieldDecl>(*Rng.begin());
5853}
5854
5856 assert(Field->hasInClassInitializer());
5857
5858 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5859
5860 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5861
5862 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5863 InitializationContext =
5865 if (!InitializationContext.has_value())
5866 InitializationContext.emplace(Loc, Field, CurContext);
5867
5868 Expr *Init = nullptr;
5869
5870 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5871 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5874
5875 if (!Field->getInClassInitializer()) {
5876 // Maybe we haven't instantiated the in-class initializer. Go check the
5877 // pattern FieldDecl to see if it has one.
5878 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5879 FieldDecl *Pattern =
5881 assert(Pattern && "We must have set the Pattern!");
5882 if (!Pattern->hasInClassInitializer() ||
5883 InstantiateInClassInitializer(Loc, Field, Pattern,
5885 Field->setInvalidDecl();
5886 return ExprError();
5887 }
5888 }
5889 }
5890
5891 // CWG2631
5892 // An immediate invocation that is not evaluated where it appears is
5893 // evaluated and checked for whether it is a constant expression at the
5894 // point where the enclosing initializer is used in a [...] a constructor
5895 // definition, or an aggregate initialization.
5897 if (!NestedDefaultChecking)
5898 V.TraverseDecl(Field);
5899
5900 // CWG1815
5901 // Support lifetime extension of temporary created by aggregate
5902 // initialization using a default member initializer. We should rebuild
5903 // the initializer in a lifetime extension context if the initializer
5904 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5905 // extension code recurses into the default initializer and does lifetime
5906 // extension when warranted.
5907 bool ContainsAnyTemporaries =
5908 isa_and_present<ExprWithCleanups>(Field->getInClassInitializer());
5909 if (Field->getInClassInitializer() &&
5910 !Field->getInClassInitializer()->containsErrors() &&
5911 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5912 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5913 CurContext};
5914 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5915 NestedDefaultChecking;
5916 // Pass down lifetime extending flag, and collect temporaries in
5917 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5921 ExprResult Res;
5923 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5924 /*CXXDirectInit=*/false);
5925 });
5926 if (!Res.isInvalid())
5927 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5928 if (Res.isInvalid()) {
5929 Field->setInvalidDecl();
5930 return ExprError();
5931 }
5932 Init = Res.get();
5933 }
5934
5935 if (Field->getInClassInitializer()) {
5936 Expr *E = Init ? Init : Field->getInClassInitializer();
5937 if (!NestedDefaultChecking)
5939 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5940 });
5943 // C++11 [class.base.init]p7:
5944 // The initialization of each base and member constitutes a
5945 // full-expression.
5946 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5947 if (Res.isInvalid()) {
5948 Field->setInvalidDecl();
5949 return ExprError();
5950 }
5951 Init = Res.get();
5952
5953 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5954 Field, InitializationContext->Context,
5955 Init);
5956 }
5957
5958 // DR1351:
5959 // If the brace-or-equal-initializer of a non-static data member
5960 // invokes a defaulted default constructor of its class or of an
5961 // enclosing class in a potentially evaluated subexpression, the
5962 // program is ill-formed.
5963 //
5964 // This resolution is unworkable: the exception specification of the
5965 // default constructor can be needed in an unevaluated context, in
5966 // particular, in the operand of a noexcept-expression, and we can be
5967 // unable to compute an exception specification for an enclosed class.
5968 //
5969 // Any attempt to resolve the exception specification of a defaulted default
5970 // constructor before the initializer is lexically complete will ultimately
5971 // come here at which point we can diagnose it.
5972 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5973 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5974 << OutermostClass << Field;
5975 Diag(Field->getEndLoc(),
5976 diag::note_default_member_initializer_not_yet_parsed);
5977 // Recover by marking the field invalid, unless we're in a SFINAE context.
5978 if (!isSFINAEContext())
5979 Field->setInvalidDecl();
5980 return ExprError();
5981}
5982
5984 const FunctionProtoType *Proto,
5985 Expr *Fn) {
5986 if (Proto && Proto->isVariadic()) {
5987 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5989 else if (Fn && Fn->getType()->isBlockPointerType())
5991 else if (FDecl) {
5992 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5993 if (Method->isInstance())
5995 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5998 }
6000}
6001
6002namespace {
6003class FunctionCallCCC final : public FunctionCallFilterCCC {
6004public:
6005 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
6006 unsigned NumArgs, MemberExpr *ME)
6007 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
6008 FunctionName(FuncName) {}
6009
6010 bool ValidateCandidate(const TypoCorrection &candidate) override {
6011 if (!candidate.getCorrectionSpecifier() ||
6012 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
6013 return false;
6014 }
6015
6017 }
6018
6019 std::unique_ptr<CorrectionCandidateCallback> clone() override {
6020 return std::make_unique<FunctionCallCCC>(*this);
6021 }
6022
6023private:
6024 const IdentifierInfo *const FunctionName;
6025};
6026}
6027
6029 FunctionDecl *FDecl,
6030 ArrayRef<Expr *> Args) {
6031 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
6032 DeclarationName FuncName = FDecl->getDeclName();
6033 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
6034
6035 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
6036 if (TypoCorrection Corrected = S.CorrectTypo(
6038 S.getScopeForContext(S.CurContext), nullptr, CCC,
6040 if (NamedDecl *ND = Corrected.getFoundDecl()) {
6041 if (Corrected.isOverloaded()) {
6044 for (NamedDecl *CD : Corrected) {
6045 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
6047 OCS);
6048 }
6049 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
6050 case OR_Success:
6051 ND = Best->FoundDecl;
6052 Corrected.setCorrectionDecl(ND);
6053 break;
6054 default:
6055 break;
6056 }
6057 }
6058 ND = ND->getUnderlyingDecl();
6060 return Corrected;
6061 }
6062 }
6063 return TypoCorrection();
6064}
6065
6066// [C++26][[expr.unary.op]/p4
6067// A pointer to member is only formed when an explicit &
6068// is used and its operand is a qualified-id not enclosed in parentheses.
6070 if (!isa<ParenExpr>(Fn))
6071 return false;
6072
6073 Fn = Fn->IgnoreParens();
6074
6075 auto *UO = dyn_cast<UnaryOperator>(Fn);
6076 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
6077 return false;
6078 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
6079 return DRE->hasQualifier();
6080 }
6081 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
6082 return bool(OVL->getQualifier());
6083 return false;
6084}
6085
6086bool
6088 FunctionDecl *FDecl,
6089 const FunctionProtoType *Proto,
6090 ArrayRef<Expr *> Args,
6091 SourceLocation RParenLoc,
6092 bool IsExecConfig) {
6093 // Bail out early if calling a builtin with custom typechecking.
6094 // For HLSL builtin aliases, argument conversion is still needed because
6095 // overload resolution may have selected a conversion sequence (e.g.,
6096 // vector-to-scalar truncation) that must be applied before the custom
6097 // type checker runs.
6098 if (FDecl)
6099 if (unsigned ID = FDecl->getBuiltinID())
6100 if (Context.BuiltinInfo.hasCustomTypechecking(ID) &&
6101 !(Context.getLangOpts().HLSL && FDecl->hasAttr<BuiltinAliasAttr>()))
6102 return false;
6103
6104 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6105 // assignment, to the types of the corresponding parameter, ...
6106
6107 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
6108 bool HasExplicitObjectParameter =
6109 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6110 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6111 unsigned NumParams = Proto->getNumParams();
6112 bool Invalid = false;
6113 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6114 unsigned FnKind = Fn->getType()->isBlockPointerType()
6115 ? 1 /* block */
6116 : (IsExecConfig ? 3 /* kernel function (exec config) */
6117 : 0 /* function */);
6118
6119 // If too few arguments are available (and we don't have default
6120 // arguments for the remaining parameters), don't make the call.
6121 if (Args.size() < NumParams) {
6122 if (Args.size() < MinArgs) {
6123 TypoCorrection TC;
6124 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6125 unsigned diag_id =
6126 MinArgs == NumParams && !Proto->isVariadic()
6127 ? diag::err_typecheck_call_too_few_args_suggest
6128 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6130 TC, PDiag(diag_id)
6131 << FnKind << MinArgs - ExplicitObjectParameterOffset
6132 << static_cast<unsigned>(Args.size()) -
6133 ExplicitObjectParameterOffset
6134 << HasExplicitObjectParameter << TC.getCorrectionRange());
6135 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6136 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6137 ->getDeclName())
6138 Diag(RParenLoc,
6139 MinArgs == NumParams && !Proto->isVariadic()
6140 ? diag::err_typecheck_call_too_few_args_one
6141 : diag::err_typecheck_call_too_few_args_at_least_one)
6142 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6143 << HasExplicitObjectParameter << Fn->getSourceRange();
6144 else
6145 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6146 ? diag::err_typecheck_call_too_few_args
6147 : diag::err_typecheck_call_too_few_args_at_least)
6148 << FnKind << MinArgs - ExplicitObjectParameterOffset
6149 << static_cast<unsigned>(Args.size()) -
6150 ExplicitObjectParameterOffset
6151 << HasExplicitObjectParameter << Fn->getSourceRange();
6152
6153 // Emit the location of the prototype.
6154 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6155 Diag(FDecl->getLocation(), diag::note_callee_decl)
6156 << FDecl << FDecl->getParametersSourceRange();
6157
6158 return true;
6159 }
6160 // We reserve space for the default arguments when we create
6161 // the call expression, before calling ConvertArgumentsForCall.
6162 assert((Call->getNumArgs() == NumParams) &&
6163 "We should have reserved space for the default arguments before!");
6164 }
6165
6166 // If too many are passed and not variadic, error on the extras and drop
6167 // them.
6168 if (Args.size() > NumParams) {
6169 if (!Proto->isVariadic()) {
6170 TypoCorrection TC;
6171 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6172 unsigned diag_id =
6173 MinArgs == NumParams && !Proto->isVariadic()
6174 ? diag::err_typecheck_call_too_many_args_suggest
6175 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6177 TC, PDiag(diag_id)
6178 << FnKind << NumParams - ExplicitObjectParameterOffset
6179 << static_cast<unsigned>(Args.size()) -
6180 ExplicitObjectParameterOffset
6181 << HasExplicitObjectParameter << TC.getCorrectionRange());
6182 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6183 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6184 ->getDeclName())
6185 Diag(Args[NumParams]->getBeginLoc(),
6186 MinArgs == NumParams
6187 ? diag::err_typecheck_call_too_many_args_one
6188 : diag::err_typecheck_call_too_many_args_at_most_one)
6189 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6190 << static_cast<unsigned>(Args.size()) -
6191 ExplicitObjectParameterOffset
6192 << HasExplicitObjectParameter << Fn->getSourceRange()
6193 << SourceRange(Args[NumParams]->getBeginLoc(),
6194 Args.back()->getEndLoc());
6195 else
6196 Diag(Args[NumParams]->getBeginLoc(),
6197 MinArgs == NumParams
6198 ? diag::err_typecheck_call_too_many_args
6199 : diag::err_typecheck_call_too_many_args_at_most)
6200 << FnKind << NumParams - ExplicitObjectParameterOffset
6201 << static_cast<unsigned>(Args.size()) -
6202 ExplicitObjectParameterOffset
6203 << HasExplicitObjectParameter << Fn->getSourceRange()
6204 << SourceRange(Args[NumParams]->getBeginLoc(),
6205 Args.back()->getEndLoc());
6206
6207 // Emit the location of the prototype.
6208 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6209 Diag(FDecl->getLocation(), diag::note_callee_decl)
6210 << FDecl << FDecl->getParametersSourceRange();
6211
6212 // This deletes the extra arguments.
6213 Call->shrinkNumArgs(NumParams);
6214 return true;
6215 }
6216 }
6217 SmallVector<Expr *, 8> AllArgs;
6218 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6219
6220 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
6221 AllArgs, CallType);
6222 if (Invalid)
6223 return true;
6224 unsigned TotalNumArgs = AllArgs.size();
6225 for (unsigned i = 0; i < TotalNumArgs; ++i)
6226 Call->setArg(i, AllArgs[i]);
6227
6228 Call->computeDependence();
6229 return false;
6230}
6231
6233 const FunctionProtoType *Proto,
6234 unsigned FirstParam, ArrayRef<Expr *> Args,
6235 SmallVectorImpl<Expr *> &AllArgs,
6236 VariadicCallType CallType, bool AllowExplicit,
6237 bool IsListInitialization) {
6238 unsigned NumParams = Proto->getNumParams();
6239 bool Invalid = false;
6240 size_t ArgIx = 0;
6241 // Continue to check argument types (even if we have too few/many args).
6242 for (unsigned i = FirstParam; i < NumParams; i++) {
6243 QualType ProtoArgType = Proto->getParamType(i);
6244
6245 Expr *Arg;
6246 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6247 if (ArgIx < Args.size()) {
6248 Arg = Args[ArgIx++];
6249
6250 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6251 diag::err_call_incomplete_argument, Arg))
6252 return true;
6253
6254 // Strip the unbridged-cast placeholder expression off, if applicable.
6255 bool CFAudited = false;
6256 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6257 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6258 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6259 Arg = ObjC().stripARCUnbridgedCast(Arg);
6260 else if (getLangOpts().ObjCAutoRefCount &&
6261 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6262 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6263 CFAudited = true;
6264
6265 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6266 ProtoArgType->isBlockPointerType())
6267 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6268 BE->getBlockDecl()->setDoesNotEscape();
6269 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
6271 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6272 if (ArgExpr.isInvalid())
6273 return true;
6274 Arg = ArgExpr.getAs<Expr>();
6275 }
6276
6277 InitializedEntity Entity =
6279 ProtoArgType)
6281 Context, ProtoArgType, Proto->isParamConsumed(i));
6282
6283 // Remember that parameter belongs to a CF audited API.
6284 if (CFAudited)
6285 Entity.setParameterCFAudited();
6286
6287 // Warn if argument has OBT but parameter doesn't, discarding OBTs at
6288 // function boundaries is a common oversight.
6289 if (const auto *OBT = Arg->getType()->getAs<OverflowBehaviorType>();
6290 OBT && !ProtoArgType->isOverflowBehaviorType()) {
6291 bool isPedantic =
6292 OBT->isUnsignedIntegerOrEnumerationType() && OBT->isWrapKind();
6293 Diag(Arg->getExprLoc(),
6294 isPedantic ? diag::warn_obt_discarded_at_function_boundary_pedantic
6295 : diag::warn_obt_discarded_at_function_boundary)
6296 << Arg->getType() << ProtoArgType;
6297 }
6298
6300 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6301 if (ArgE.isInvalid())
6302 return true;
6303
6304 Arg = ArgE.getAs<Expr>();
6305 } else {
6306 assert(Param && "can't use default arguments without a known callee");
6307
6308 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6309 if (ArgExpr.isInvalid())
6310 return true;
6311
6312 Arg = ArgExpr.getAs<Expr>();
6313 }
6314
6315 // Check for array bounds violations for each argument to the call. This
6316 // check only triggers warnings when the argument isn't a more complex Expr
6317 // with its own checking, such as a BinaryOperator.
6318 CheckArrayAccess(Arg);
6319
6320 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6321 CheckStaticArrayArgument(CallLoc, Param, Arg);
6322
6323 AllArgs.push_back(Arg);
6324 }
6325
6326 // If this is a variadic call, handle args passed through "...".
6327 if (CallType != VariadicCallType::DoesNotApply) {
6328 // Assume that extern "C" functions with variadic arguments that
6329 // return __unknown_anytype aren't *really* variadic.
6330 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6331 FDecl->isExternC()) {
6332 for (Expr *A : Args.slice(ArgIx)) {
6333 QualType paramType; // ignored
6334 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6335 Invalid |= arg.isInvalid();
6336 AllArgs.push_back(arg.get());
6337 }
6338
6339 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6340 } else {
6341 for (Expr *A : Args.slice(ArgIx)) {
6342 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6343 Invalid |= Arg.isInvalid();
6344 AllArgs.push_back(Arg.get());
6345 }
6346 }
6347
6348 // Check for array bounds violations.
6349 for (Expr *A : Args.slice(ArgIx))
6350 CheckArrayAccess(A);
6351 }
6352 return Invalid;
6353}
6354
6356 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6357 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6358 TL = DTL.getOriginalLoc();
6359 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6360 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6361 << ATL.getLocalSourceRange();
6362}
6363
6364void
6366 ParmVarDecl *Param,
6367 const Expr *ArgExpr) {
6368 // Static array parameters are not supported in C++.
6369 if (!Param || getLangOpts().CPlusPlus)
6370 return;
6371
6372 QualType OrigTy = Param->getOriginalType();
6373
6374 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6375 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6376 return;
6377
6378 if (ArgExpr->isNullPointerConstant(Context,
6380 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6381 DiagnoseCalleeStaticArrayParam(*this, Param);
6382 return;
6383 }
6384
6385 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6386 if (!CAT)
6387 return;
6388
6389 const ConstantArrayType *ArgCAT =
6390 Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
6391 if (!ArgCAT)
6392 return;
6393
6394 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6395 ArgCAT->getElementType())) {
6396 if (ArgCAT->getSize().ult(CAT->getSize())) {
6397 Diag(CallLoc, diag::warn_static_array_too_small)
6398 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6399 << (unsigned)CAT->getZExtSize() << 0;
6400 DiagnoseCalleeStaticArrayParam(*this, Param);
6401 }
6402 return;
6403 }
6404
6405 std::optional<CharUnits> ArgSize =
6407 std::optional<CharUnits> ParmSize =
6409 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6410 Diag(CallLoc, diag::warn_static_array_too_small)
6411 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6412 << (unsigned)ParmSize->getQuantity() << 1;
6413 DiagnoseCalleeStaticArrayParam(*this, Param);
6414 }
6415}
6416
6417/// Given a function expression of unknown-any type, try to rebuild it
6418/// to have a function type.
6420
6421/// Is the given type a placeholder that we need to lower out
6422/// immediately during argument processing?
6424 // Placeholders are never sugared.
6425 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6426 if (!placeholder) return false;
6427
6428 switch (placeholder->getKind()) {
6429 // Ignore all the non-placeholder types.
6430#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6431 case BuiltinType::Id:
6432#include "clang/Basic/OpenCLImageTypes.def"
6433#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6434 case BuiltinType::Id:
6435#include "clang/Basic/OpenCLExtensionTypes.def"
6436 // In practice we'll never use this, since all SVE types are sugared
6437 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6438#define SVE_TYPE(Name, Id, SingletonId) \
6439 case BuiltinType::Id:
6440#include "clang/Basic/AArch64ACLETypes.def"
6441#define PPC_VECTOR_TYPE(Name, Id, Size) \
6442 case BuiltinType::Id:
6443#include "clang/Basic/PPCTypes.def"
6444#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6445#include "clang/Basic/RISCVVTypes.def"
6446#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6447#include "clang/Basic/WebAssemblyReferenceTypes.def"
6448#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6449#include "clang/Basic/AMDGPUTypes.def"
6450#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6451#include "clang/Basic/HLSLIntangibleTypes.def"
6452#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6453#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6454#include "clang/AST/BuiltinTypes.def"
6455 return false;
6456
6457 case BuiltinType::UnresolvedTemplate:
6458 // We cannot lower out overload sets; they might validly be resolved
6459 // by the call machinery.
6460 case BuiltinType::Overload:
6461 return false;
6462
6463 // Unbridged casts in ARC can be handled in some call positions and
6464 // should be left in place.
6465 case BuiltinType::ARCUnbridgedCast:
6466 return false;
6467
6468 // Pseudo-objects should be converted as soon as possible.
6469 case BuiltinType::PseudoObject:
6470 return true;
6471
6472 // The debugger mode could theoretically but currently does not try
6473 // to resolve unknown-typed arguments based on known parameter types.
6474 case BuiltinType::UnknownAny:
6475 return true;
6476
6477 // These are always invalid as call arguments and should be reported.
6478 case BuiltinType::BoundMember:
6479 case BuiltinType::BuiltinFn:
6480 case BuiltinType::IncompleteMatrixIdx:
6481 case BuiltinType::ArraySection:
6482 case BuiltinType::OMPArrayShaping:
6483 case BuiltinType::OMPIterator:
6484 return true;
6485
6486 }
6487 llvm_unreachable("bad builtin type kind");
6488}
6489
6491 // Apply this processing to all the arguments at once instead of
6492 // dying at the first failure.
6493 bool hasInvalid = false;
6494 for (size_t i = 0, e = args.size(); i != e; i++) {
6495 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6496 ExprResult result = CheckPlaceholderExpr(args[i]);
6497 if (result.isInvalid()) hasInvalid = true;
6498 else args[i] = result.get();
6499 }
6500 }
6501 return hasInvalid;
6502}
6503
6504/// If a builtin function has a pointer argument with no explicit address
6505/// space, then it should be able to accept a pointer to any address
6506/// space as input. In order to do this, we need to replace the
6507/// standard builtin declaration with one that uses the same address space
6508/// as the call.
6509///
6510/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6511/// it does not contain any pointer arguments without
6512/// an address space qualifer. Otherwise the rewritten
6513/// FunctionDecl is returned.
6514/// TODO: Handle pointer return types.
6516 FunctionDecl *FDecl,
6517 MultiExprArg ArgExprs) {
6518
6519 QualType DeclType = FDecl->getType();
6520 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6521
6522 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6523 ArgExprs.size() < FT->getNumParams())
6524 return nullptr;
6525
6526 bool NeedsNewDecl = false;
6527 unsigned i = 0;
6528 SmallVector<QualType, 8> OverloadParams;
6529
6530 {
6531 // The lvalue conversions in this loop are only for type resolution and
6532 // don't actually occur.
6535 Sema::SFINAETrap Trap(*Sema, /*ForValidityCheck=*/true);
6536
6537 for (QualType ParamType : FT->param_types()) {
6538
6539 // Convert array arguments to pointer to simplify type lookup.
6540 ExprResult ArgRes =
6542 if (ArgRes.isInvalid())
6543 return nullptr;
6544 Expr *Arg = ArgRes.get();
6545 QualType ArgType = Arg->getType();
6546 if (!ParamType->isPointerType() ||
6547 ParamType->getPointeeType().hasAddressSpace() ||
6548 !ArgType->isPointerType() ||
6549 !ArgType->getPointeeType().hasAddressSpace() ||
6550 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
6551 OverloadParams.push_back(ParamType);
6552 continue;
6553 }
6554
6555 QualType PointeeType = ParamType->getPointeeType();
6556 NeedsNewDecl = true;
6557 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6558
6559 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6560 OverloadParams.push_back(Context.getPointerType(PointeeType));
6561 }
6562 }
6563
6564 if (!NeedsNewDecl)
6565 return nullptr;
6566
6568 EPI.Variadic = FT->isVariadic();
6569 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6570 OverloadParams, EPI);
6571 DeclContext *Parent = FDecl->getParent();
6572 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6573 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6574 FDecl->getIdentifier(), OverloadTy,
6575 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6576 false,
6577 /*hasPrototype=*/true);
6579 FT = cast<FunctionProtoType>(OverloadTy);
6580 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6581 QualType ParamType = FT->getParamType(i);
6582 ParmVarDecl *Parm =
6583 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6584 SourceLocation(), nullptr, ParamType,
6585 /*TInfo=*/nullptr, SC_None, nullptr);
6586 Parm->setScopeInfo(0, i);
6587 Params.push_back(Parm);
6588 }
6589 OverloadDecl->setParams(Params);
6590 // We cannot merge host/device attributes of redeclarations. They have to
6591 // be consistent when created.
6592 if (Sema->LangOpts.CUDA) {
6593 if (FDecl->hasAttr<CUDAHostAttr>())
6594 OverloadDecl->addAttr(CUDAHostAttr::CreateImplicit(Context));
6595 if (FDecl->hasAttr<CUDADeviceAttr>())
6596 OverloadDecl->addAttr(CUDADeviceAttr::CreateImplicit(Context));
6597 }
6598 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6599 return OverloadDecl;
6600}
6601
6602static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6603 FunctionDecl *Callee,
6604 MultiExprArg ArgExprs) {
6605 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6606 // similar attributes) really don't like it when functions are called with an
6607 // invalid number of args.
6608 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6609 /*PartialOverloading=*/false) &&
6610 !Callee->isVariadic())
6611 return;
6612 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6613 return;
6614
6615 if (const EnableIfAttr *Attr =
6616 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6617 S.Diag(Fn->getBeginLoc(),
6618 isa<CXXMethodDecl>(Callee)
6619 ? diag::err_ovl_no_viable_member_function_in_call
6620 : diag::err_ovl_no_viable_function_in_call)
6621 << Callee << Callee->getSourceRange();
6622 S.Diag(Callee->getLocation(),
6623 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6624 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6625 return;
6626 }
6627}
6628
6630 const UnresolvedMemberExpr *const UME, Sema &S) {
6631
6632 const auto GetFunctionLevelDCIfCXXClass =
6633 [](Sema &S) -> const CXXRecordDecl * {
6634 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6635 if (!DC || !DC->getParent())
6636 return nullptr;
6637
6638 // If the call to some member function was made from within a member
6639 // function body 'M' return return 'M's parent.
6640 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6641 return MD->getParent()->getCanonicalDecl();
6642 // else the call was made from within a default member initializer of a
6643 // class, so return the class.
6644 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6645 return RD->getCanonicalDecl();
6646 return nullptr;
6647 };
6648 // If our DeclContext is neither a member function nor a class (in the
6649 // case of a lambda in a default member initializer), we can't have an
6650 // enclosing 'this'.
6651
6652 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6653 if (!CurParentClass)
6654 return false;
6655
6656 // The naming class for implicit member functions call is the class in which
6657 // name lookup starts.
6658 const CXXRecordDecl *const NamingClass =
6660 assert(NamingClass && "Must have naming class even for implicit access");
6661
6662 // If the unresolved member functions were found in a 'naming class' that is
6663 // related (either the same or derived from) to the class that contains the
6664 // member function that itself contained the implicit member access.
6665
6666 return CurParentClass == NamingClass ||
6667 CurParentClass->isDerivedFrom(NamingClass);
6668}
6669
6670static void
6672 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6673
6674 if (!UME)
6675 return;
6676
6677 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6678 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6679 // already been captured, or if this is an implicit member function call (if
6680 // it isn't, an attempt to capture 'this' should already have been made).
6681 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6682 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6683 return;
6684
6685 // Check if the naming class in which the unresolved members were found is
6686 // related (same as or is a base of) to the enclosing class.
6687
6689 return;
6690
6691
6692 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6693 // If the enclosing function is not dependent, then this lambda is
6694 // capture ready, so if we can capture this, do so.
6695 if (!EnclosingFunctionCtx->isDependentContext()) {
6696 // If the current lambda and all enclosing lambdas can capture 'this' -
6697 // then go ahead and capture 'this' (since our unresolved overload set
6698 // contains at least one non-static member function).
6699 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6700 S.CheckCXXThisCapture(CallLoc);
6701 } else if (S.CurContext->isDependentContext()) {
6702 // ... since this is an implicit member reference, that might potentially
6703 // involve a 'this' capture, mark 'this' for potential capture in
6704 // enclosing lambdas.
6705 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6706 CurLSI->addPotentialThisCapture(CallLoc);
6707 }
6708}
6709
6710// Once a call is fully resolved, warn for unqualified calls to specific
6711// C++ standard functions, like move and forward.
6713 const CallExpr *Call) {
6714 // We are only checking unary move and forward so exit early here.
6715 if (Call->getNumArgs() != 1)
6716 return;
6717
6718 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6719 if (!E || isa<UnresolvedLookupExpr>(E))
6720 return;
6721 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6722 if (!DRE || !DRE->getLocation().isValid())
6723 return;
6724
6725 if (DRE->getQualifier())
6726 return;
6727
6728 const FunctionDecl *FD = Call->getDirectCallee();
6729 if (!FD)
6730 return;
6731
6732 // Only warn for some functions deemed more frequent or problematic.
6733 unsigned BuiltinID = FD->getBuiltinID();
6734 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6735 return;
6736
6737 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6739 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6740}
6741
6743 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6744 Expr *ExecConfig) {
6746 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6747 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6748 if (Call.isInvalid())
6749 return Call;
6750
6751 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6752 // language modes.
6753 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6754 ULE && ULE->hasExplicitTemplateArgs() && ULE->decls().empty()) {
6755 DiagCompat(Fn->getExprLoc(), diag_compat::adl_only_template_id)
6756 << ULE->getName();
6757 }
6758
6759 if (LangOpts.OpenMP)
6760 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6761 ExecConfig);
6762 if (LangOpts.CPlusPlus) {
6763 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6765
6766 // If we previously found that the id-expression of this call refers to a
6767 // consteval function but the call is dependent, we should not treat is an
6768 // an invalid immediate call.
6769 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6770 DRE && Call.get()->isValueDependent()) {
6772 }
6773 }
6774 return Call;
6775}
6776
6777// Any type that could be used to form a callable expression
6778static bool MayBeFunctionType(const ASTContext &Context, const Expr *E) {
6779 QualType T = E->getType();
6780 if (T->isDependentType())
6781 return true;
6782
6783 if (T == Context.BoundMemberTy || T == Context.UnknownAnyTy ||
6784 T == Context.BuiltinFnTy || T == Context.OverloadTy ||
6785 T->isFunctionType() || T->isFunctionReferenceType() ||
6786 T->isMemberFunctionPointerType() || T->isFunctionPointerType() ||
6787 T->isBlockPointerType() || T->isRecordType())
6788 return true;
6789
6792}
6793
6795 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6796 Expr *ExecConfig, bool IsExecConfig,
6797 bool AllowRecovery) {
6798 // Since this might be a postfix expression, get rid of ParenListExprs.
6800 if (Result.isInvalid()) return ExprError();
6801 Fn = Result.get();
6802
6803 // The __builtin_amdgcn_is_invocable builtin is special, and will be resolved
6804 // later, when we check boolean conditions, for now we merely forward it
6805 // without any additional checking.
6806 if (Fn->getType() == Context.BuiltinFnTy && ArgExprs.size() == 1 &&
6807 ArgExprs[0]->getType() == Context.BuiltinFnTy) {
6808 const auto *FD = cast<FunctionDecl>(Fn->getReferencedDeclOfCallee());
6809
6810 if (FD->getName() == "__builtin_amdgcn_is_invocable") {
6811 QualType FnPtrTy = Context.getPointerType(FD->getType());
6812 Expr *R = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6813 return CallExpr::Create(
6814 Context, R, ArgExprs, Context.AMDGPUFeaturePredicateTy,
6816 }
6817 }
6818
6819 if (CheckArgsForPlaceholders(ArgExprs))
6820 return ExprError();
6821
6822 // The result of __builtin_counted_by_ref cannot be used as a function
6823 // argument. It allows leaking and modification of bounds safety information.
6824 for (const Expr *Arg : ArgExprs)
6825 if (CheckInvalidBuiltinCountedByRef(Arg,
6827 return ExprError();
6828
6829 if (getLangOpts().CPlusPlus) {
6830 // If this is a pseudo-destructor expression, build the call immediately.
6832 if (!ArgExprs.empty()) {
6833 // Pseudo-destructor calls should not have any arguments.
6834 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6836 SourceRange(ArgExprs.front()->getBeginLoc(),
6837 ArgExprs.back()->getEndLoc()));
6838 }
6839
6840 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6841 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6842 }
6843 if (Fn->getType() == Context.PseudoObjectTy) {
6844 ExprResult result = CheckPlaceholderExpr(Fn);
6845 if (result.isInvalid()) return ExprError();
6846 Fn = result.get();
6847 }
6848
6849 // Determine whether this is a dependent call inside a C++ template,
6850 // in which case we won't do any semantic analysis now.
6851 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6852 if (ExecConfig) {
6854 cast<CallExpr>(ExecConfig), ArgExprs,
6855 Context.DependentTy, VK_PRValue,
6856 RParenLoc, CurFPFeatureOverrides());
6857 } else {
6858
6860 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6861 Fn->getBeginLoc());
6862
6863 // If the type of the function itself is not dependent
6864 // check that it is a reasonable as a function, as type deduction
6865 // later assume the CallExpr has a sensible TYPE.
6866 if (!MayBeFunctionType(Context, Fn))
6867 return ExprError(
6868 Diag(LParenLoc, diag::err_typecheck_call_not_function)
6869 << Fn->getType() << Fn->getSourceRange());
6870
6871 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6872 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6873 }
6874 }
6875
6876 // Determine whether this is a call to an object (C++ [over.call.object]).
6877 if (Fn->getType()->isRecordType())
6878 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6879 RParenLoc);
6880
6881 if (Fn->getType() == Context.UnknownAnyTy) {
6882 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6883 if (result.isInvalid()) return ExprError();
6884 Fn = result.get();
6885 }
6886
6887 if (Fn->getType() == Context.BoundMemberTy) {
6888 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6889 RParenLoc, ExecConfig, IsExecConfig,
6890 AllowRecovery);
6891 }
6892 }
6893
6894 // Check for overloaded calls. This can happen even in C due to extensions.
6895 if (Fn->getType() == Context.OverloadTy) {
6897
6898 // We aren't supposed to apply this logic if there's an '&' involved.
6901 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6902 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6903 OverloadExpr *ovl = find.Expression;
6904 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6906 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6907 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6908 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6909 RParenLoc, ExecConfig, IsExecConfig,
6910 AllowRecovery);
6911 }
6912 }
6913
6914 // If we're directly calling a function, get the appropriate declaration.
6915 if (Fn->getType() == Context.UnknownAnyTy) {
6916 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6917 if (result.isInvalid()) return ExprError();
6918 Fn = result.get();
6919 }
6920
6921 Expr *NakedFn = Fn->IgnoreParens();
6922
6923 bool CallingNDeclIndirectly = false;
6924 NamedDecl *NDecl = nullptr;
6925 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6926 if (UnOp->getOpcode() == UO_AddrOf) {
6927 CallingNDeclIndirectly = true;
6928 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6929 }
6930 }
6931
6932 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6933 NDecl = DRE->getDecl();
6934
6935 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6936 if (FDecl && FDecl->getBuiltinID()) {
6937 const llvm::Triple &Triple = Context.getTargetInfo().getTriple();
6938 if (Triple.isSPIRV() && Triple.getVendor() == llvm::Triple::AMD) {
6939 if (Context.BuiltinInfo.isTSBuiltin(FDecl->getBuiltinID()) &&
6940 !Context.BuiltinInfo.isAuxBuiltinID(FDecl->getBuiltinID())) {
6942 getFunctionLevelDeclContext(/*AllowLambda=*/true)));
6943 }
6944 }
6945
6946 // Rewrite the function decl for this builtin by replacing parameters
6947 // with no explicit address space with the address space of the arguments
6948 // in ArgExprs.
6949 if ((FDecl =
6950 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6951 NDecl = FDecl;
6953 Context, DRE->getQualifierLoc(), SourceLocation(), FDecl, false,
6954 SourceLocation(), Fn->getType() /* BuiltinFnTy */,
6955 Fn->getValueKind(), FDecl, nullptr, DRE->isNonOdrUse());
6956 }
6957 }
6958 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6959 NDecl = ME->getMemberDecl();
6960
6961 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6962 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6963 FD, /*Complain=*/true, Fn->getBeginLoc()))
6964 return ExprError();
6965
6966 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6967
6968 // If this expression is a call to a builtin function in HIP compilation,
6969 // allow a pointer-type argument to default address space to be passed as a
6970 // pointer-type parameter to a non-default address space. If Arg is declared
6971 // in the default address space and Param is declared in a non-default
6972 // address space, perform an implicit address space cast to the parameter
6973 // type.
6974 if (getLangOpts().HIP && FD && FD->getBuiltinID()) {
6975 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6976 ++Idx) {
6977 ParmVarDecl *Param = FD->getParamDecl(Idx);
6978 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6979 !ArgExprs[Idx]->getType()->isPointerType())
6980 continue;
6981
6982 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6983 auto ArgTy = ArgExprs[Idx]->getType();
6984 auto ArgPtTy = ArgTy->getPointeeType();
6985 auto ArgAS = ArgPtTy.getAddressSpace();
6986
6987 // Add address space cast if target address spaces are different
6988 bool NeedImplicitASC =
6989 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6990 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6991 // or from specific AS which has target AS matching that of Param.
6993 if (!NeedImplicitASC)
6994 continue;
6995
6996 // First, ensure that the Arg is an RValue.
6997 if (ArgExprs[Idx]->isGLValue()) {
6998 ExprResult Res = DefaultLvalueConversion(ArgExprs[Idx]);
6999 if (Res.isInvalid())
7000 return ExprError();
7001 ArgExprs[Idx] = Res.get();
7002 }
7003
7004 // Construct a new arg type with address space of Param
7005 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
7006 ArgPtQuals.setAddressSpace(ParamAS);
7007 auto NewArgPtTy =
7008 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
7009 auto NewArgTy =
7010 Context.getQualifiedType(Context.getPointerType(NewArgPtTy),
7011 ArgTy.getQualifiers());
7012
7013 // Finally perform an implicit address space cast
7014 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
7015 CK_AddressSpaceConversion)
7016 .get();
7017 }
7018 }
7019 }
7020
7021 if (Context.isDependenceAllowed() &&
7022 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
7023 assert(!getLangOpts().CPlusPlus);
7024 assert((Fn->containsErrors() ||
7025 llvm::any_of(ArgExprs,
7026 [](clang::Expr *E) { return E->containsErrors(); })) &&
7027 "should only occur in error-recovery path.");
7028 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
7029 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
7030 }
7031 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
7032 ExecConfig, IsExecConfig);
7033}
7034
7036 MultiExprArg CallArgs) {
7037 std::string Name = Context.BuiltinInfo.getName(Id);
7038 LookupResult R(*this, &Context.Idents.get(Name), Loc,
7040 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
7041
7042 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
7043 assert(BuiltInDecl && "failed to find builtin declaration");
7044
7045 ExprResult DeclRef =
7046 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
7047 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
7048
7050 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
7051
7052 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
7053 return Call.get();
7054}
7055
7057 SourceLocation BuiltinLoc,
7058 SourceLocation RParenLoc) {
7059 QualType DstTy = GetTypeFromParser(ParsedDestTy);
7060 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
7061}
7062
7064 SourceLocation BuiltinLoc,
7065 SourceLocation RParenLoc) {
7068 QualType SrcTy = E->getType();
7069 if (!SrcTy->isDependentType() &&
7070 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
7071 return ExprError(
7072 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
7073 << DestTy << SrcTy << E->getSourceRange());
7074 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
7075}
7076
7078 SourceLocation BuiltinLoc,
7079 SourceLocation RParenLoc) {
7080 TypeSourceInfo *TInfo;
7081 GetTypeFromParser(ParsedDestTy, &TInfo);
7082 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
7083}
7084
7086 SourceLocation LParenLoc,
7087 ArrayRef<Expr *> Args,
7088 SourceLocation RParenLoc, Expr *Config,
7089 bool IsExecConfig, ADLCallKind UsesADL) {
7090 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
7091 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
7092
7093 auto IsSJLJ = [&] {
7094 switch (BuiltinID) {
7095 case Builtin::BI__builtin_longjmp:
7096 case Builtin::BI__builtin_setjmp:
7097 case Builtin::BI__sigsetjmp:
7098 case Builtin::BI_longjmp:
7099 case Builtin::BI_setjmp:
7100 case Builtin::BIlongjmp:
7101 case Builtin::BIsetjmp:
7102 case Builtin::BIsiglongjmp:
7103 case Builtin::BIsigsetjmp:
7104 return true;
7105 default:
7106 return false;
7107 }
7108 };
7109
7110 // Forbid any call to setjmp/longjmp and friends inside a '_Defer' statement.
7111 if (!CurrentDefer.empty() && IsSJLJ()) {
7112 // Note: If we ever start supporting '_Defer' in C++ we'll have to check
7113 // for more than just blocks (e.g. lambdas, nested classes...).
7114 Scope *DeferParent = CurrentDefer.back().first;
7115 Scope *Block = CurScope->getBlockParent();
7116 if (DeferParent->Contains(*CurScope) &&
7117 (!Block || !DeferParent->Contains(*Block)))
7118 Diag(Fn->getExprLoc(), diag::err_defer_invalid_sjlj) << FDecl;
7119 }
7120
7121 // Functions with 'interrupt' attribute cannot be called directly.
7122 if (FDecl) {
7123 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
7124 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
7125 return ExprError();
7126 }
7127 if (FDecl->hasAttr<ARMInterruptAttr>()) {
7128 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
7129 return ExprError();
7130 }
7131 }
7132
7133 // X86 interrupt handlers may only call routines with attribute
7134 // no_caller_saved_registers since there is no efficient way to
7135 // save and restore the non-GPR state.
7136 if (auto *Caller = getCurFunctionDecl()) {
7137 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
7138 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
7139 const TargetInfo &TI = Context.getTargetInfo();
7140 bool HasNonGPRRegisters =
7141 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
7142 if (HasNonGPRRegisters &&
7143 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
7144 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
7145 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
7146 if (FDecl)
7147 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
7148 }
7149 }
7150 }
7151
7152 // Extract the return type from the builtin function pointer type.
7153 QualType ResultTy;
7154 if (BuiltinID)
7155 ResultTy = FDecl->getCallResultType();
7156 else
7157 ResultTy = Context.BoolTy;
7158
7159 // Promote the function operand.
7160 // We special-case function promotion here because we only allow promoting
7161 // builtin functions to function pointers in the callee of a call.
7163 if (BuiltinID &&
7164 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
7165 // FIXME Several builtins still have setType in
7166 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7167 // Builtins.td to ensure they are correct before removing setType calls.
7168 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
7169 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
7170 } else
7172 if (Result.isInvalid())
7173 return ExprError();
7174 Fn = Result.get();
7175
7176 // Check for a valid function type, but only if it is not a builtin which
7177 // requires custom type checking. These will be handled by
7178 // CheckBuiltinFunctionCall below just after creation of the call expression.
7179 const FunctionType *FuncT = nullptr;
7180 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7181 retry:
7182 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
7183 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7184 // have type pointer to function".
7185 FuncT = PT->getPointeeType()->getAs<FunctionType>();
7186 if (!FuncT)
7187 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7188 << Fn->getType() << Fn->getSourceRange());
7189 } else if (const BlockPointerType *BPT =
7190 Fn->getType()->getAs<BlockPointerType>()) {
7191 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
7192 } else {
7193 // Handle calls to expressions of unknown-any type.
7194 if (Fn->getType() == Context.UnknownAnyTy) {
7195 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
7196 if (rewrite.isInvalid())
7197 return ExprError();
7198 Fn = rewrite.get();
7199 goto retry;
7200 }
7201
7202 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7203 << Fn->getType() << Fn->getSourceRange());
7204 }
7205 }
7206
7207 // Get the number of parameters in the function prototype, if any.
7208 // We will allocate space for max(Args.size(), NumParams) arguments
7209 // in the call expression.
7210 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7211 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7212
7213 CallExpr *TheCall;
7214 if (Config) {
7215 assert(UsesADL == ADLCallKind::NotADL &&
7216 "CUDAKernelCallExpr should not use ADL");
7217 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7218 Args, ResultTy, VK_PRValue, RParenLoc,
7219 CurFPFeatureOverrides(), NumParams);
7220 } else {
7221 TheCall =
7222 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7223 CurFPFeatureOverrides(), NumParams, UsesADL);
7224 }
7225
7226 // Bail out early if calling a builtin with custom type checking.
7227 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
7228 // For HLSL builtin aliases, the call was resolved via overload resolution
7229 // which may have selected a conversion sequence (e.g., vector-to-scalar
7230 // truncation). Convert arguments to match the declared prototype before
7231 // the custom type checker runs, otherwise the builtin will operate on
7232 // the unconverted argument types.
7233 if (getLangOpts().HLSL && FDecl && FDecl->hasAttr<BuiltinAliasAttr>()) {
7234 if (const auto *P = FDecl->getType()->getAs<FunctionProtoType>()) {
7235 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, P, Args, RParenLoc,
7236 IsExecConfig))
7237 return ExprError();
7238 }
7239 }
7240 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7241 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
7242 E = CheckForImmediateInvocation(E, FDecl);
7243 return E;
7244 }
7245
7246 if (getLangOpts().CUDA) {
7247 if (Config) {
7248 // CUDA: Kernel calls must be to global functions
7249 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7250 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7251 << FDecl << Fn->getSourceRange());
7252
7253 // CUDA: Kernel function must have 'void' return type
7254 if (!FuncT->getReturnType()->isVoidType() &&
7255 !FuncT->getReturnType()->getAs<AutoType>() &&
7257 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7258 << Fn->getType() << Fn->getSourceRange());
7259 } else {
7260 // CUDA: Calls to global functions must be configured
7261 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7262 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7263 << FDecl << Fn->getSourceRange());
7264 }
7265 }
7266
7267 // Check for a valid return type
7268 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7269 FDecl))
7270 return ExprError();
7271
7272 // We know the result type of the call, set it.
7273 TheCall->setType(FuncT->getCallResultType(Context));
7275
7276 // WebAssembly tables can't be used as arguments.
7277 if (Context.getTargetInfo().getTriple().isWasm()) {
7278 for (const Expr *Arg : Args) {
7279 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7280 return ExprError(Diag(Arg->getExprLoc(),
7281 diag::err_wasm_table_as_function_parameter));
7282 }
7283 }
7284 }
7285
7286 if (Proto) {
7287 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7288 IsExecConfig))
7289 return ExprError();
7290 } else {
7291 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7292
7293 if (FDecl) {
7294 // Check if we have too few/too many template arguments, based
7295 // on our knowledge of the function definition.
7296 const FunctionDecl *Def = nullptr;
7297 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7298 Proto = Def->getType()->getAs<FunctionProtoType>();
7299 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7300 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7301 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7302 }
7303
7304 // If the function we're calling isn't a function prototype, but we have
7305 // a function prototype from a prior declaratiom, use that prototype.
7306 if (!FDecl->hasPrototype())
7307 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7308 }
7309
7310 // If we still haven't found a prototype to use but there are arguments to
7311 // the call, diagnose this as calling a function without a prototype.
7312 // However, if we found a function declaration, check to see if
7313 // -Wdeprecated-non-prototype was disabled where the function was declared.
7314 // If so, we will silence the diagnostic here on the assumption that this
7315 // interface is intentional and the user knows what they're doing. We will
7316 // also silence the diagnostic if there is a function declaration but it
7317 // was implicitly defined (the user already gets diagnostics about the
7318 // creation of the implicit function declaration, so the additional warning
7319 // is not helpful).
7320 if (!Proto && !Args.empty() &&
7321 (!FDecl || (!FDecl->isImplicit() &&
7322 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7323 FDecl->getLocation()))))
7324 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7325 << (FDecl != nullptr) << FDecl;
7326
7327 // Promote the arguments (C99 6.5.2.2p6).
7328 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7329 Expr *Arg = Args[i];
7330
7331 if (Proto && i < Proto->getNumParams()) {
7333 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7334 ExprResult ArgE =
7336 if (ArgE.isInvalid())
7337 return true;
7338
7339 Arg = ArgE.getAs<Expr>();
7340
7341 } else {
7343
7344 if (ArgE.isInvalid())
7345 return true;
7346
7347 Arg = ArgE.getAs<Expr>();
7348 }
7349
7350 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7351 diag::err_call_incomplete_argument, Arg))
7352 return ExprError();
7353
7354 TheCall->setArg(i, Arg);
7355 }
7356 TheCall->computeDependence();
7357 }
7358
7359 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7360 if (Method->isImplicitObjectMemberFunction())
7361 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7362 << Fn->getSourceRange() << 0);
7363
7364 // Check for sentinels
7365 if (NDecl)
7366 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7367
7368 // Warn for unions passing across security boundary (CMSE).
7369 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7370 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7371 if (const auto *RT =
7372 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7373 if (RT->getDecl()->isOrContainsUnion())
7374 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7375 << 0 << i;
7376 }
7377 }
7378 }
7379
7380 // Do special checking on direct calls to functions.
7381 if (FDecl) {
7382 if (CheckFunctionCall(FDecl, TheCall, Proto))
7383 return ExprError();
7384
7385 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7386
7387 if (BuiltinID)
7388 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7389 } else if (NDecl) {
7390 if (CheckPointerCall(NDecl, TheCall, Proto))
7391 return ExprError();
7392 } else {
7393 if (CheckOtherCall(TheCall, Proto))
7394 return ExprError();
7395 }
7396
7397 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7398}
7399
7402 SourceLocation RParenLoc, Expr *InitExpr) {
7403 assert(Ty && "ActOnCompoundLiteral(): missing type");
7404 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7405
7406 TypeSourceInfo *TInfo;
7407 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7408 if (!TInfo)
7409 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7410
7411 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7412}
7413
7416 SourceLocation RParenLoc, Expr *LiteralExpr) {
7417 QualType literalType = TInfo->getType();
7418
7419 if (literalType->isArrayType()) {
7421 LParenLoc, Context.getBaseElementType(literalType),
7422 diag::err_array_incomplete_or_sizeless_type,
7423 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7424 return ExprError();
7425 if (literalType->isVariableArrayType()) {
7426 // C23 6.7.10p4: An entity of variable length array type shall not be
7427 // initialized except by an empty initializer.
7428 //
7429 // The C extension warnings are issued from ParseBraceInitializer() and
7430 // do not need to be issued here. However, we continue to issue an error
7431 // in the case there are initializers or we are compiling C++. We allow
7432 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7433 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7434 // FIXME: should we allow this construct in C++ when it makes sense to do
7435 // so?
7436 //
7437 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7438 // shall specify an object type or an array of unknown size, but not a
7439 // variable length array type. This seems odd, as it allows 'int a[size] =
7440 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7441 // says, this is what's implemented here for C (except for the extension
7442 // that permits constant foldable size arrays)
7443
7444 auto diagID = LangOpts.CPlusPlus
7445 ? diag::err_variable_object_no_init
7446 : diag::err_compound_literal_with_vla_type;
7447 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7448 diagID))
7449 return ExprError();
7450 }
7451 } else if (!literalType->isDependentType() &&
7452 RequireCompleteType(LParenLoc, literalType,
7453 diag::err_typecheck_decl_incomplete_type,
7454 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7455 return ExprError();
7456
7457 InitializedEntity Entity
7461 SourceRange(LParenLoc, RParenLoc),
7462 /*InitList=*/true);
7463 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7464 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7465 &literalType);
7466 if (Result.isInvalid())
7467 return ExprError();
7468 LiteralExpr = Result.get();
7469
7470 // We treat the compound literal as being at file scope if it's not in a
7471 // function or method body, or within the function's prototype scope. This
7472 // means the following compound literal is not at file scope:
7473 // void func(char *para[(int [1]){ 0 }[0]);
7474 const Scope *S = getCurScope();
7475 bool IsFileScope = !CurContext->isFunctionOrMethod() &&
7476 !S->isInCFunctionScope() &&
7477 (!S || !S->isFunctionPrototypeScope());
7478
7479 // In C, compound literals are l-values for some reason.
7480 // For GCC compatibility, in C++, file-scope array compound literals with
7481 // constant initializers are also l-values, and compound literals are
7482 // otherwise prvalues.
7483 //
7484 // (GCC also treats C++ list-initialized file-scope array prvalues with
7485 // constant initializers as l-values, but that's non-conforming, so we don't
7486 // follow it there.)
7487 //
7488 // FIXME: It would be better to handle the lvalue cases as materializing and
7489 // lifetime-extending a temporary object, but our materialized temporaries
7490 // representation only supports lifetime extension from a variable, not "out
7491 // of thin air".
7492 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7493 // is bound to the result of applying array-to-pointer decay to the compound
7494 // literal.
7495 // FIXME: GCC supports compound literals of reference type, which should
7496 // obviously have a value kind derived from the kind of reference involved.
7498 (getLangOpts().CPlusPlus && !(IsFileScope && literalType->isArrayType()))
7499 ? VK_PRValue
7500 : VK_LValue;
7501
7502 // C99 6.5.2.5
7503 // "If the compound literal occurs outside the body of a function, the
7504 // initializer list shall consist of constant expressions."
7505 if (IsFileScope)
7506 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7507 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7508 Expr *Init = ILE->getInit(i);
7509 if (!Init->isTypeDependent() && !Init->isValueDependent() &&
7510 !Init->isConstantInitializer(Context)) {
7511 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
7512 << Init->getSourceBitField();
7513 return ExprError();
7514 }
7515
7516 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7517 }
7518
7519 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType, VK,
7520 LiteralExpr, IsFileScope);
7521 if (IsFileScope) {
7522 if (!LiteralExpr->isTypeDependent() &&
7523 !LiteralExpr->isValueDependent() &&
7524 !literalType->isDependentType()) // C99 6.5.2.5p3
7525 if (CheckForConstantInitializer(LiteralExpr))
7526 return ExprError();
7527 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7528 literalType.getAddressSpace() != LangAS::Default) {
7529 // Embedded-C extensions to C99 6.5.2.5:
7530 // "If the compound literal occurs inside the body of a function, the
7531 // type name shall not be qualified by an address-space qualifier."
7532 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7533 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7534 return ExprError();
7535 }
7536
7537 if (!IsFileScope && !getLangOpts().CPlusPlus) {
7538 // Compound literals that have automatic storage duration are destroyed at
7539 // the end of the scope in C; in C++, they're just temporaries.
7540
7541 // Emit diagnostics if it is or contains a C union type that is non-trivial
7542 // to destruct.
7547
7548 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7549 if (literalType.isDestructedType()) {
7550 Cleanup.setExprNeedsCleanups(true);
7551 ExprCleanupObjects.push_back(E);
7553 }
7554 }
7555
7558 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7559 E->getInitializer()->getExprLoc());
7560
7561 return MaybeBindToTemporary(E);
7562}
7563
7566 SourceLocation RBraceLoc) {
7567 // Only produce each kind of designated initialization diagnostic once.
7568 SourceLocation FirstDesignator;
7569 bool DiagnosedArrayDesignator = false;
7570 bool DiagnosedNestedDesignator = false;
7571 bool DiagnosedMixedDesignator = false;
7572
7573 // Check that any designated initializers are syntactically valid in the
7574 // current language mode.
7575 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7576 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7577 if (FirstDesignator.isInvalid())
7578 FirstDesignator = DIE->getBeginLoc();
7579
7580 if (!getLangOpts().CPlusPlus)
7581 break;
7582
7583 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7584 DiagnosedNestedDesignator = true;
7585 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7586 << DIE->getDesignatorsSourceRange();
7587 }
7588
7589 for (auto &Desig : DIE->designators()) {
7590 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7591 DiagnosedArrayDesignator = true;
7592 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7593 << Desig.getSourceRange();
7594 }
7595 }
7596
7597 if (!DiagnosedMixedDesignator &&
7598 !isa<DesignatedInitExpr>(InitArgList[0])) {
7599 DiagnosedMixedDesignator = true;
7600 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7601 << DIE->getSourceRange();
7602 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7603 << InitArgList[0]->getSourceRange();
7604 }
7605 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7606 isa<DesignatedInitExpr>(InitArgList[0])) {
7607 DiagnosedMixedDesignator = true;
7608 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7609 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7610 << DIE->getSourceRange();
7611 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7612 << InitArgList[I]->getSourceRange();
7613 }
7614 }
7615
7616 if (FirstDesignator.isValid()) {
7617 // Only diagnose designated initiaization as a C++20 extension if we didn't
7618 // already diagnose use of (non-C++20) C99 designator syntax.
7619 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7620 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7621 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7622 ? diag::warn_cxx17_compat_designated_init
7623 : diag::ext_cxx_designated_init);
7624 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7625 Diag(FirstDesignator, diag::ext_designated_init);
7626 }
7627 }
7628
7629 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc, /*IsExplicit=*/true);
7630}
7631
7633 MultiExprArg InitArgList,
7634 SourceLocation RBraceLoc, bool IsExplicit) {
7635 // Semantic analysis for initializers is done by ActOnDeclarator() and
7636 // CheckInitializer() - it requires knowledge of the object being initialized.
7637
7638 // Immediately handle non-overload placeholders. Overloads can be
7639 // resolved contextually, but everything else here can't.
7640 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7641 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7642 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7643
7644 // Ignore failures; dropping the entire initializer list because
7645 // of one failure would be terrible for indexing/etc.
7646 if (result.isInvalid()) continue;
7647
7648 InitArgList[I] = result.get();
7649 }
7650 }
7651
7652 InitListExpr *E = new (Context)
7653 InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc, IsExplicit);
7654 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7655 return E;
7656}
7657
7659 assert(E.get()->getType()->isBlockPointerType());
7660 assert(E.get()->isPRValue());
7661
7662 // Only do this in an r-value context.
7663 if (!getLangOpts().ObjCAutoRefCount) return;
7664
7666 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7667 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7668 Cleanup.setExprNeedsCleanups(true);
7669}
7670
7672 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7673 // Also, callers should have filtered out the invalid cases with
7674 // pointers. Everything else should be possible.
7675
7676 QualType SrcTy = Src.get()->getType();
7677 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7678 return CK_NoOp;
7679
7680 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7682 llvm_unreachable("member pointer type in C");
7683
7684 case Type::STK_CPointer:
7687 switch (DestTy->getScalarTypeKind()) {
7688 case Type::STK_CPointer: {
7689 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7690 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7691 if (SrcAS != DestAS)
7692 return CK_AddressSpaceConversion;
7693 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7694 return CK_NoOp;
7695 return CK_BitCast;
7696 }
7698 return (SrcKind == Type::STK_BlockPointer
7699 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7701 if (SrcKind == Type::STK_ObjCObjectPointer)
7702 return CK_BitCast;
7703 if (SrcKind == Type::STK_CPointer)
7704 return CK_CPointerToObjCPointerCast;
7706 return CK_BlockPointerToObjCPointerCast;
7707 case Type::STK_Bool:
7708 return CK_PointerToBoolean;
7709 case Type::STK_Integral:
7710 return CK_PointerToIntegral;
7711 case Type::STK_Floating:
7716 llvm_unreachable("illegal cast from pointer");
7717 }
7718 llvm_unreachable("Should have returned before this");
7719
7721 switch (DestTy->getScalarTypeKind()) {
7723 return CK_FixedPointCast;
7724 case Type::STK_Bool:
7725 return CK_FixedPointToBoolean;
7726 case Type::STK_Integral:
7727 return CK_FixedPointToIntegral;
7728 case Type::STK_Floating:
7729 return CK_FixedPointToFloating;
7732 Diag(Src.get()->getExprLoc(),
7733 diag::err_unimplemented_conversion_with_fixed_point_type)
7734 << DestTy;
7735 return CK_IntegralCast;
7736 case Type::STK_CPointer:
7740 llvm_unreachable("illegal cast to pointer type");
7741 }
7742 llvm_unreachable("Should have returned before this");
7743
7744 case Type::STK_Bool: // casting from bool is like casting from an integer
7745 case Type::STK_Integral:
7746 switch (DestTy->getScalarTypeKind()) {
7747 case Type::STK_CPointer:
7752 return CK_NullToPointer;
7753 return CK_IntegralToPointer;
7754 case Type::STK_Bool:
7755 return CK_IntegralToBoolean;
7756 case Type::STK_Integral:
7757 return CK_IntegralCast;
7758 case Type::STK_Floating:
7759 return CK_IntegralToFloating;
7761 Src = ImpCastExprToType(Src.get(),
7762 DestTy->castAs<ComplexType>()->getElementType(),
7763 CK_IntegralCast);
7764 return CK_IntegralRealToComplex;
7766 Src = ImpCastExprToType(Src.get(),
7767 DestTy->castAs<ComplexType>()->getElementType(),
7768 CK_IntegralToFloating);
7769 return CK_FloatingRealToComplex;
7771 llvm_unreachable("member pointer type in C");
7773 return CK_IntegralToFixedPoint;
7774 }
7775 llvm_unreachable("Should have returned before this");
7776
7777 case Type::STK_Floating:
7778 switch (DestTy->getScalarTypeKind()) {
7779 case Type::STK_Floating:
7780 return CK_FloatingCast;
7781 case Type::STK_Bool:
7782 return CK_FloatingToBoolean;
7783 case Type::STK_Integral:
7784 return CK_FloatingToIntegral;
7786 Src = ImpCastExprToType(Src.get(),
7787 DestTy->castAs<ComplexType>()->getElementType(),
7788 CK_FloatingCast);
7789 return CK_FloatingRealToComplex;
7791 Src = ImpCastExprToType(Src.get(),
7792 DestTy->castAs<ComplexType>()->getElementType(),
7793 CK_FloatingToIntegral);
7794 return CK_IntegralRealToComplex;
7795 case Type::STK_CPointer:
7798 llvm_unreachable("valid float->pointer cast?");
7800 llvm_unreachable("member pointer type in C");
7802 return CK_FloatingToFixedPoint;
7803 }
7804 llvm_unreachable("Should have returned before this");
7805
7807 switch (DestTy->getScalarTypeKind()) {
7809 return CK_FloatingComplexCast;
7811 return CK_FloatingComplexToIntegralComplex;
7812 case Type::STK_Floating: {
7813 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7814 if (Context.hasSameType(ET, DestTy))
7815 return CK_FloatingComplexToReal;
7816 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7817 return CK_FloatingCast;
7818 }
7819 case Type::STK_Bool:
7820 return CK_FloatingComplexToBoolean;
7821 case Type::STK_Integral:
7822 Src = ImpCastExprToType(Src.get(),
7823 SrcTy->castAs<ComplexType>()->getElementType(),
7824 CK_FloatingComplexToReal);
7825 return CK_FloatingToIntegral;
7826 case Type::STK_CPointer:
7829 llvm_unreachable("valid complex float->pointer cast?");
7831 llvm_unreachable("member pointer type in C");
7833 Diag(Src.get()->getExprLoc(),
7834 diag::err_unimplemented_conversion_with_fixed_point_type)
7835 << SrcTy;
7836 return CK_IntegralCast;
7837 }
7838 llvm_unreachable("Should have returned before this");
7839
7841 switch (DestTy->getScalarTypeKind()) {
7843 return CK_IntegralComplexToFloatingComplex;
7845 return CK_IntegralComplexCast;
7846 case Type::STK_Integral: {
7847 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7848 if (Context.hasSameType(ET, DestTy))
7849 return CK_IntegralComplexToReal;
7850 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7851 return CK_IntegralCast;
7852 }
7853 case Type::STK_Bool:
7854 return CK_IntegralComplexToBoolean;
7855 case Type::STK_Floating:
7856 Src = ImpCastExprToType(Src.get(),
7857 SrcTy->castAs<ComplexType>()->getElementType(),
7858 CK_IntegralComplexToReal);
7859 return CK_IntegralToFloating;
7860 case Type::STK_CPointer:
7863 llvm_unreachable("valid complex int->pointer cast?");
7865 llvm_unreachable("member pointer type in C");
7867 Diag(Src.get()->getExprLoc(),
7868 diag::err_unimplemented_conversion_with_fixed_point_type)
7869 << SrcTy;
7870 return CK_IntegralCast;
7871 }
7872 llvm_unreachable("Should have returned before this");
7873 }
7874
7875 llvm_unreachable("Unhandled scalar cast");
7876}
7877
7878static bool breakDownVectorType(QualType type, uint64_t &len,
7879 QualType &eltType) {
7880 // Vectors are simple.
7881 if (const VectorType *vecType = type->getAs<VectorType>()) {
7882 len = vecType->getNumElements();
7883 eltType = vecType->getElementType();
7884 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7885 return true;
7886 }
7887
7888 // We allow lax conversion to and from non-vector types, but only if
7889 // they're real types (i.e. non-complex, non-pointer scalar types).
7890 if (!type->isRealType()) return false;
7891
7892 len = 1;
7893 eltType = type;
7894 return true;
7895}
7896
7898 assert(srcTy->isVectorType() || destTy->isVectorType());
7899
7900 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7901 if (!FirstType->isSVESizelessBuiltinType())
7902 return false;
7903
7904 const auto *VecTy = SecondType->getAs<VectorType>();
7905 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7906 };
7907
7908 return ValidScalableConversion(srcTy, destTy) ||
7909 ValidScalableConversion(destTy, srcTy);
7910}
7911
7913 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7914 return false;
7915
7916 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7917 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7918
7919 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7920 matSrcType->getNumColumns() == matDestType->getNumColumns();
7921}
7922
7924 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7925
7926 uint64_t SrcLen, DestLen;
7927 QualType SrcEltTy, DestEltTy;
7928 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7929 return false;
7930 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7931 return false;
7932
7933 // ASTContext::getTypeSize will return the size rounded up to a
7934 // power of 2, so instead of using that, we need to use the raw
7935 // element size multiplied by the element count.
7936 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7937 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7938
7939 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7940}
7941
7943 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7944 "expected at least one type to be a vector here");
7945
7946 bool IsSrcTyAltivec =
7947 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7949 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7951 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7953
7954 bool IsDestTyAltivec = DestTy->isVectorType() &&
7955 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7957 (DestTy->castAs<VectorType>()->getVectorKind() ==
7959 (DestTy->castAs<VectorType>()->getVectorKind() ==
7961
7962 return (IsSrcTyAltivec || IsDestTyAltivec);
7963}
7964
7966 assert(destTy->isVectorType() || srcTy->isVectorType());
7967
7968 // Disallow lax conversions between scalars and ExtVectors (these
7969 // conversions are allowed for other vector types because common headers
7970 // depend on them). Most scalar OP ExtVector cases are handled by the
7971 // splat path anyway, which does what we want (convert, not bitcast).
7972 // What this rules out for ExtVectors is crazy things like char4*float.
7973 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7974 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7975
7976 return areVectorTypesSameSize(srcTy, destTy);
7977}
7978
7980 assert(destTy->isVectorType() || srcTy->isVectorType());
7981
7982 switch (Context.getLangOpts().getLaxVectorConversions()) {
7984 return false;
7985
7987 if (!srcTy->isIntegralOrEnumerationType()) {
7988 auto *Vec = srcTy->getAs<VectorType>();
7989 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7990 return false;
7991 }
7992 if (!destTy->isIntegralOrEnumerationType()) {
7993 auto *Vec = destTy->getAs<VectorType>();
7994 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7995 return false;
7996 }
7997 // OK, integer (vector) -> integer (vector) bitcast.
7998 break;
7999
8001 break;
8002 }
8003
8004 return areLaxCompatibleVectorTypes(srcTy, destTy);
8005}
8006
8008 CastKind &Kind) {
8009 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
8010 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
8011 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
8012 << DestTy << SrcTy << R;
8013 }
8014 } else if (SrcTy->isMatrixType()) {
8015 return Diag(R.getBegin(),
8016 diag::err_invalid_conversion_between_matrix_and_type)
8017 << SrcTy << DestTy << R;
8018 } else if (DestTy->isMatrixType()) {
8019 return Diag(R.getBegin(),
8020 diag::err_invalid_conversion_between_matrix_and_type)
8021 << DestTy << SrcTy << R;
8022 }
8023
8024 Kind = CK_MatrixCast;
8025 return false;
8026}
8027
8029 CastKind &Kind) {
8030 assert(VectorTy->isVectorType() && "Not a vector type!");
8031
8032 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
8033 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
8034 return Diag(R.getBegin(),
8035 Ty->isVectorType() ?
8036 diag::err_invalid_conversion_between_vectors :
8037 diag::err_invalid_conversion_between_vector_and_integer)
8038 << VectorTy << Ty << R;
8039 } else
8040 return Diag(R.getBegin(),
8041 diag::err_invalid_conversion_between_vector_and_scalar)
8042 << VectorTy << Ty << R;
8043
8044 Kind = CK_BitCast;
8045 return false;
8046}
8047
8049 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
8050
8051 if (DestElemTy == SplattedExpr->getType())
8052 return SplattedExpr;
8053
8054 assert(DestElemTy->isFloatingType() ||
8055 DestElemTy->isIntegralOrEnumerationType());
8056
8057 CastKind CK;
8058 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
8059 // OpenCL requires that we convert `true` boolean expressions to -1, but
8060 // only when splatting vectors.
8061 if (DestElemTy->isFloatingType()) {
8062 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8063 // in two steps: boolean to signed integral, then to floating.
8064 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
8065 CK_BooleanToSignedIntegral);
8066 SplattedExpr = CastExprRes.get();
8067 CK = CK_IntegralToFloating;
8068 } else {
8069 CK = CK_BooleanToSignedIntegral;
8070 }
8071 } else {
8072 ExprResult CastExprRes = SplattedExpr;
8073 CK = PrepareScalarCast(CastExprRes, DestElemTy);
8074 if (CastExprRes.isInvalid())
8075 return ExprError();
8076 SplattedExpr = CastExprRes.get();
8077 }
8078 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8079}
8080
8082 QualType DestElemTy = MatrixTy->castAs<MatrixType>()->getElementType();
8083
8084 if (DestElemTy == SplattedExpr->getType())
8085 return SplattedExpr;
8086
8087 assert(DestElemTy->isFloatingType() ||
8088 DestElemTy->isIntegralOrEnumerationType());
8089
8090 ExprResult CastExprRes = SplattedExpr;
8091 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
8092 if (CastExprRes.isInvalid())
8093 return ExprError();
8094 SplattedExpr = CastExprRes.get();
8095
8096 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
8097}
8098
8100 Expr *CastExpr, CastKind &Kind) {
8101 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
8102
8103 QualType SrcTy = CastExpr->getType();
8104
8105 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8106 // an ExtVectorType.
8107 // In OpenCL, casts between vectors of different types are not allowed.
8108 // (See OpenCL 6.2).
8109 if (SrcTy->isVectorType()) {
8110 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
8111 (getLangOpts().OpenCL &&
8112 !Context.hasSameUnqualifiedType(DestTy, SrcTy) &&
8113 !Context.areCompatibleVectorTypes(DestTy, SrcTy))) {
8114 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
8115 << DestTy << SrcTy << R;
8116 return ExprError();
8117 }
8118 Kind = CK_BitCast;
8119 return CastExpr;
8120 }
8121
8122 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8123 // conversion will take place first from scalar to elt type, and then
8124 // splat from elt type to vector.
8125 if (SrcTy->isPointerType())
8126 return Diag(R.getBegin(),
8127 diag::err_invalid_conversion_between_vector_and_scalar)
8128 << DestTy << SrcTy << R;
8129
8130 Kind = CK_VectorSplat;
8131 return prepareVectorSplat(DestTy, CastExpr);
8132}
8133
8134/// Check that a call to alloc_size function specifies sufficient space for the
8135/// destination type.
8136static void CheckSufficientAllocSize(Sema &S, QualType DestType,
8137 const Expr *E) {
8138 QualType SourceType = E->getType();
8139 if (!DestType->isPointerType() || !SourceType->isPointerType() ||
8140 DestType == SourceType)
8141 return;
8142
8143 const auto *CE = dyn_cast<CallExpr>(E->IgnoreParenCasts());
8144 if (!CE)
8145 return;
8146
8147 // Find the total size allocated by the function call.
8148 if (!CE->getCalleeAllocSizeAttr())
8149 return;
8150 std::optional<llvm::APInt> AllocSize =
8151 CE->evaluateBytesReturnedByAllocSizeCall(S.Context);
8152 // Allocations of size zero are permitted as a special case. They are usually
8153 // done intentionally.
8154 if (!AllocSize || AllocSize->isZero())
8155 return;
8156 auto Size = CharUnits::fromQuantity(AllocSize->getZExtValue());
8157
8158 QualType TargetType = DestType->getPointeeType();
8159 // Find the destination size. As a special case function types have size of
8160 // one byte to match the sizeof operator behavior.
8161 auto LhsSize = TargetType->isFunctionType()
8162 ? CharUnits::One()
8163 : S.Context.getTypeSizeInCharsIfKnown(TargetType);
8164 if (LhsSize && Size < LhsSize)
8165 S.Diag(E->getExprLoc(), diag::warn_alloc_size)
8166 << Size.getQuantity() << TargetType << LhsSize->getQuantity();
8167}
8168
8171 Declarator &D, ParsedType &Ty,
8172 SourceLocation RParenLoc, Expr *CastExpr) {
8173 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
8174 "ActOnCastExpr(): missing type or expr");
8175
8177 if (D.isInvalidType())
8178 return ExprError();
8179
8180 if (getLangOpts().CPlusPlus) {
8181 // Check that there are no default arguments (C++ only).
8183 }
8184
8186
8187 QualType castType = castTInfo->getType();
8188 Ty = CreateParsedType(castType, castTInfo);
8189
8190 bool isVectorLiteral = false;
8191
8192 // Check for an altivec or OpenCL literal,
8193 // i.e. all the elements are integer constants.
8194 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8195 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8196 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8197 && castType->isVectorType() && (PE || PLE)) {
8198 if (PLE && PLE->getNumExprs() == 0) {
8199 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8200 return ExprError();
8201 }
8202 if (PE || PLE->getNumExprs() == 1) {
8203 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8204 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8205 isVectorLiteral = true;
8206 }
8207 else
8208 isVectorLiteral = true;
8209 }
8210
8211 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8212 // then handle it as such.
8213 if (isVectorLiteral)
8214 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8215
8216 // If the Expr being casted is a ParenListExpr, handle it specially.
8217 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8218 // sequence of BinOp comma operators.
8221 if (Result.isInvalid()) return ExprError();
8222 CastExpr = Result.get();
8223 }
8224
8225 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8226 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8227
8229
8231
8233
8234 CheckSufficientAllocSize(*this, castType, CastExpr);
8235
8236 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8237}
8238
8240 SourceLocation RParenLoc, Expr *E,
8241 TypeSourceInfo *TInfo) {
8242 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8243 "Expected paren or paren list expression");
8244
8245 Expr **exprs;
8246 unsigned numExprs;
8247 Expr *subExpr;
8248 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8249 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8250 LiteralLParenLoc = PE->getLParenLoc();
8251 LiteralRParenLoc = PE->getRParenLoc();
8252 exprs = PE->getExprs();
8253 numExprs = PE->getNumExprs();
8254 } else { // isa<ParenExpr> by assertion at function entrance
8255 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8256 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8257 subExpr = cast<ParenExpr>(E)->getSubExpr();
8258 exprs = &subExpr;
8259 numExprs = 1;
8260 }
8261
8262 QualType Ty = TInfo->getType();
8263 assert(Ty->isVectorType() && "Expected vector type");
8264
8265 SmallVector<Expr *, 8> initExprs;
8266 const VectorType *VTy = Ty->castAs<VectorType>();
8267 unsigned numElems = VTy->getNumElements();
8268
8269 // '(...)' form of vector initialization in AltiVec: the number of
8270 // initializers must be one or must match the size of the vector.
8271 // If a single value is specified in the initializer then it will be
8272 // replicated to all the components of the vector
8274 VTy->getElementType()))
8275 return ExprError();
8277 // The number of initializers must be one or must match the size of the
8278 // vector. If a single value is specified in the initializer then it will
8279 // be replicated to all the components of the vector
8280 if (numExprs == 1) {
8281 QualType ElemTy = VTy->getElementType();
8282 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8283 if (Literal.isInvalid())
8284 return ExprError();
8285 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8286 PrepareScalarCast(Literal, ElemTy));
8287 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8288 }
8289 else if (numExprs < numElems) {
8290 Diag(E->getExprLoc(),
8291 diag::err_incorrect_number_of_vector_initializers);
8292 return ExprError();
8293 }
8294 else
8295 initExprs.append(exprs, exprs + numExprs);
8296 }
8297 else {
8298 // For OpenCL, when the number of initializers is a single value,
8299 // it will be replicated to all components of the vector.
8301 numExprs == 1) {
8302 QualType SrcTy = exprs[0]->getType();
8303 if (!SrcTy->isArithmeticType()) {
8304 Diag(exprs[0]->getBeginLoc(), diag::err_typecheck_convert_incompatible)
8305 << Ty << SrcTy << AssignmentAction::Initializing << /*elidable=*/0
8306 << /*c_style=*/0 << /*cast_kind=*/"" << exprs[0]->getSourceRange();
8307 return ExprError();
8308 }
8309 QualType ElemTy = VTy->getElementType();
8310 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8311 if (Literal.isInvalid())
8312 return ExprError();
8313 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8314 PrepareScalarCast(Literal, ElemTy));
8315 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8316 }
8317
8318 initExprs.append(exprs, exprs + numExprs);
8319 }
8320 // FIXME: This means that pretty-printing the final AST will produce curly
8321 // braces instead of the original commas.
8322 InitListExpr *initE =
8323 new (Context) InitListExpr(Context, LiteralLParenLoc, initExprs,
8324 LiteralRParenLoc, /*isExplicit=*/false);
8325 initE->setType(Ty);
8326 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8327}
8328
8331 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8332 if (!E)
8333 return OrigExpr;
8334
8335 ExprResult Result(E->getExpr(0));
8336
8337 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8338 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8339 E->getExpr(i));
8340
8341 if (Result.isInvalid()) return ExprError();
8342
8343 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8344}
8345
8351
8353 unsigned NumUserSpecifiedExprs,
8354 SourceLocation InitLoc,
8355 SourceLocation LParenLoc,
8356 SourceLocation RParenLoc) {
8357 return CXXParenListInitExpr::Create(Context, Args, T, NumUserSpecifiedExprs,
8358 InitLoc, LParenLoc, RParenLoc);
8359}
8360
8361bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8362 SourceLocation QuestionLoc) {
8363 const Expr *NullExpr = LHSExpr;
8364 const Expr *NonPointerExpr = RHSExpr;
8368
8369 if (NullKind == Expr::NPCK_NotNull) {
8370 NullExpr = RHSExpr;
8371 NonPointerExpr = LHSExpr;
8372 NullKind =
8375 }
8376
8377 if (NullKind == Expr::NPCK_NotNull)
8378 return false;
8379
8380 if (NullKind == Expr::NPCK_ZeroExpression)
8381 return false;
8382
8383 if (NullKind == Expr::NPCK_ZeroLiteral) {
8384 // In this case, check to make sure that we got here from a "NULL"
8385 // string in the source code.
8386 NullExpr = NullExpr->IgnoreParenImpCasts();
8387 SourceLocation loc = NullExpr->getExprLoc();
8388 if (!findMacroSpelling(loc, "NULL"))
8389 return false;
8390 }
8391
8392 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8393 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8394 << NonPointerExpr->getType() << DiagType
8395 << NonPointerExpr->getSourceRange();
8396 return true;
8397}
8398
8399/// Return false if the condition expression is valid, true otherwise.
8400static bool checkCondition(Sema &S, const Expr *Cond,
8401 SourceLocation QuestionLoc) {
8402 QualType CondTy = Cond->getType();
8403
8404 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8405 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8406 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8407 << CondTy << Cond->getSourceRange();
8408 return true;
8409 }
8410
8411 // C99 6.5.15p2
8412 if (CondTy->isScalarType()) return false;
8413
8414 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8415 << CondTy << Cond->getSourceRange();
8416 return true;
8417}
8418
8419/// Return false if the NullExpr can be promoted to PointerTy,
8420/// true otherwise.
8422 QualType PointerTy) {
8423 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8424 !NullExpr.get()->isNullPointerConstant(S.Context,
8426 return true;
8427
8428 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8429 return false;
8430}
8431
8432/// Checks compatibility between two pointers and return the resulting
8433/// type.
8435 ExprResult &RHS,
8436 SourceLocation Loc) {
8437 QualType LHSTy = LHS.get()->getType();
8438 QualType RHSTy = RHS.get()->getType();
8439
8440 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8441 // Two identical pointers types are always compatible.
8442 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8443 }
8444
8445 QualType lhptee, rhptee;
8446
8447 // Get the pointee types.
8448 bool IsBlockPointer = false;
8449 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8450 lhptee = LHSBTy->getPointeeType();
8451 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8452 IsBlockPointer = true;
8453 } else {
8454 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8455 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8456 }
8457
8458 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8459 // differently qualified versions of compatible types, the result type is
8460 // a pointer to an appropriately qualified version of the composite
8461 // type.
8462
8463 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8464 // clause doesn't make sense for our extensions. E.g. address space 2 should
8465 // be incompatible with address space 3: they may live on different devices or
8466 // anything.
8467 Qualifiers lhQual = lhptee.getQualifiers();
8468 Qualifiers rhQual = rhptee.getQualifiers();
8469
8470 LangAS ResultAddrSpace = LangAS::Default;
8471 LangAS LAddrSpace = lhQual.getAddressSpace();
8472 LangAS RAddrSpace = rhQual.getAddressSpace();
8473
8474 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8475 // spaces is disallowed.
8476 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8477 ResultAddrSpace = LAddrSpace;
8478 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8479 ResultAddrSpace = RAddrSpace;
8480 else {
8481 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8482 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8483 << RHS.get()->getSourceRange();
8484 return QualType();
8485 }
8486
8487 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8488 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8489 lhQual.removeCVRQualifiers();
8490 rhQual.removeCVRQualifiers();
8491
8492 if (!lhQual.getPointerAuth().isEquivalent(rhQual.getPointerAuth())) {
8493 S.Diag(Loc, diag::err_typecheck_cond_incompatible_ptrauth)
8494 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8495 << RHS.get()->getSourceRange();
8496 return QualType();
8497 }
8498
8499 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8500 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8501 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8502 // qual types are compatible iff
8503 // * corresponded types are compatible
8504 // * CVR qualifiers are equal
8505 // * address spaces are equal
8506 // Thus for conditional operator we merge CVR and address space unqualified
8507 // pointees and if there is a composite type we return a pointer to it with
8508 // merged qualifiers.
8509 LHSCastKind =
8510 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8511 RHSCastKind =
8512 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8513 lhQual.removeAddressSpace();
8514 rhQual.removeAddressSpace();
8515
8516 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8517 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8518
8519 QualType CompositeTy = S.Context.mergeTypes(
8520 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8521 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8522
8523 if (CompositeTy.isNull()) {
8524 // In this situation, we assume void* type. No especially good
8525 // reason, but this is what gcc does, and we do have to pick
8526 // to get a consistent AST.
8527 QualType incompatTy;
8528 incompatTy = S.Context.getPointerType(
8529 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8530 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8531 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8532
8533 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8534 // for casts between types with incompatible address space qualifiers.
8535 // For the following code the compiler produces casts between global and
8536 // local address spaces of the corresponded innermost pointees:
8537 // local int *global *a;
8538 // global int *global *b;
8539 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8540 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8541 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8542 << RHS.get()->getSourceRange();
8543
8544 return incompatTy;
8545 }
8546
8547 // The pointer types are compatible.
8548 // In case of OpenCL ResultTy should have the address space qualifier
8549 // which is a superset of address spaces of both the 2nd and the 3rd
8550 // operands of the conditional operator.
8551 QualType ResultTy = [&, ResultAddrSpace]() {
8552 if (S.getLangOpts().OpenCL) {
8553 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8554 CompositeQuals.setAddressSpace(ResultAddrSpace);
8555 return S.Context
8556 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8557 .withCVRQualifiers(MergedCVRQual);
8558 }
8559 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8560 }();
8561 if (IsBlockPointer)
8562 ResultTy = S.Context.getBlockPointerType(ResultTy);
8563 else
8564 ResultTy = S.Context.getPointerType(ResultTy);
8565
8566 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8567 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8568 return ResultTy;
8569}
8570
8571/// Return the resulting type when the operands are both block pointers.
8573 ExprResult &LHS,
8574 ExprResult &RHS,
8575 SourceLocation Loc) {
8576 QualType LHSTy = LHS.get()->getType();
8577 QualType RHSTy = RHS.get()->getType();
8578
8579 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8580 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8582 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8583 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8584 return destType;
8585 }
8586 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8587 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8588 << RHS.get()->getSourceRange();
8589 return QualType();
8590 }
8591
8592 // We have 2 block pointer types.
8593 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8594}
8595
8596/// Return the resulting type when the operands are both pointers.
8597static QualType
8599 ExprResult &RHS,
8600 SourceLocation Loc) {
8601 // get the pointer types
8602 QualType LHSTy = LHS.get()->getType();
8603 QualType RHSTy = RHS.get()->getType();
8604
8605 // get the "pointed to" types
8606 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8607 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8608
8609 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8610 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8611 // Figure out necessary qualifiers (C99 6.5.15p6)
8612 QualType destPointee
8613 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8614 QualType destType = S.Context.getPointerType(destPointee);
8615 // Add qualifiers if necessary.
8616 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8617 // Promote to void*.
8618 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8619 return destType;
8620 }
8621 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8622 QualType destPointee
8623 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8624 QualType destType = S.Context.getPointerType(destPointee);
8625 // Add qualifiers if necessary.
8626 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8627 // Promote to void*.
8628 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8629 return destType;
8630 }
8631
8632 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8633}
8634
8635/// Return false if the first expression is not an integer and the second
8636/// expression is not a pointer, true otherwise.
8638 Expr* PointerExpr, SourceLocation Loc,
8639 bool IsIntFirstExpr) {
8640 if (!PointerExpr->getType()->isPointerType() ||
8641 !Int.get()->getType()->isIntegerType())
8642 return false;
8643
8644 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8645 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8646
8647 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8648 << Expr1->getType() << Expr2->getType()
8649 << Expr1->getSourceRange() << Expr2->getSourceRange();
8650 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8651 CK_IntegralToPointer);
8652 return true;
8653}
8654
8655/// Simple conversion between integer and floating point types.
8656///
8657/// Used when handling the OpenCL conditional operator where the
8658/// condition is a vector while the other operands are scalar.
8659///
8660/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8661/// types are either integer or floating type. Between the two
8662/// operands, the type with the higher rank is defined as the "result
8663/// type". The other operand needs to be promoted to the same type. No
8664/// other type promotion is allowed. We cannot use
8665/// UsualArithmeticConversions() for this purpose, since it always
8666/// promotes promotable types.
8668 ExprResult &RHS,
8669 SourceLocation QuestionLoc) {
8671 if (LHS.isInvalid())
8672 return QualType();
8674 if (RHS.isInvalid())
8675 return QualType();
8676
8677 // For conversion purposes, we ignore any qualifiers.
8678 // For example, "const float" and "float" are equivalent.
8679 QualType LHSType =
8681 QualType RHSType =
8683
8684 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8685 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8686 << LHSType << LHS.get()->getSourceRange();
8687 return QualType();
8688 }
8689
8690 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8691 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8692 << RHSType << RHS.get()->getSourceRange();
8693 return QualType();
8694 }
8695
8696 // If both types are identical, no conversion is needed.
8697 if (LHSType == RHSType)
8698 return LHSType;
8699
8700 // Now handle "real" floating types (i.e. float, double, long double).
8701 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8702 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8703 /*IsCompAssign = */ false);
8704
8705 // Finally, we have two differing integer types.
8707 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8708}
8709
8710/// Convert scalar operands to a vector that matches the
8711/// condition in length.
8712///
8713/// Used when handling the OpenCL conditional operator where the
8714/// condition is a vector while the other operands are scalar.
8715///
8716/// We first compute the "result type" for the scalar operands
8717/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8718/// into a vector of that type where the length matches the condition
8719/// vector type. s6.11.6 requires that the element types of the result
8720/// and the condition must have the same number of bits.
8721static QualType
8723 QualType CondTy, SourceLocation QuestionLoc) {
8724 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8725 if (ResTy.isNull()) return QualType();
8726
8727 const VectorType *CV = CondTy->getAs<VectorType>();
8728 assert(CV);
8729
8730 // Determine the vector result type
8731 unsigned NumElements = CV->getNumElements();
8732 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8733
8734 // Ensure that all types have the same number of bits
8736 != S.Context.getTypeSize(ResTy)) {
8737 // Since VectorTy is created internally, it does not pretty print
8738 // with an OpenCL name. Instead, we just print a description.
8739 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8740 SmallString<64> Str;
8741 llvm::raw_svector_ostream OS(Str);
8742 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8743 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8744 << CondTy << OS.str();
8745 return QualType();
8746 }
8747
8748 // Convert operands to the vector result type
8749 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8750 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8751
8752 return VectorTy;
8753}
8754
8755/// Return false if this is a valid OpenCL condition vector
8757 SourceLocation QuestionLoc) {
8758 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8759 // integral type.
8760 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8761 assert(CondTy);
8762 QualType EleTy = CondTy->getElementType();
8763 if (EleTy->isIntegerType()) return false;
8764
8765 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8766 << Cond->getType() << Cond->getSourceRange();
8767 return true;
8768}
8769
8770/// Return false if the vector condition type and the vector
8771/// result type are compatible.
8772///
8773/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8774/// number of elements, and their element types have the same number
8775/// of bits.
8776static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8777 SourceLocation QuestionLoc) {
8778 const VectorType *CV = CondTy->getAs<VectorType>();
8779 const VectorType *RV = VecResTy->getAs<VectorType>();
8780 assert(CV && RV);
8781
8782 if (CV->getNumElements() != RV->getNumElements()) {
8783 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8784 << CondTy << VecResTy;
8785 return true;
8786 }
8787
8788 QualType CVE = CV->getElementType();
8789 QualType RVE = RV->getElementType();
8790
8791 // Boolean vectors are permitted outside of OpenCL mode.
8792 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE) &&
8793 (!CVE->isBooleanType() || S.LangOpts.OpenCL)) {
8794 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8795 << CondTy << VecResTy;
8796 return true;
8797 }
8798
8799 return false;
8800}
8801
8802/// Return the resulting type for the conditional operator in
8803/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8804/// s6.3.i) when the condition is a vector type.
8805static QualType
8807 ExprResult &LHS, ExprResult &RHS,
8808 SourceLocation QuestionLoc) {
8810 if (Cond.isInvalid())
8811 return QualType();
8812 QualType CondTy = Cond.get()->getType();
8813
8814 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8815 return QualType();
8816
8817 // If either operand is a vector then find the vector type of the
8818 // result as specified in OpenCL v1.1 s6.3.i.
8819 if (LHS.get()->getType()->isVectorType() ||
8820 RHS.get()->getType()->isVectorType()) {
8821 bool IsBoolVecLang =
8822 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8823 QualType VecResTy =
8824 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8825 /*isCompAssign*/ false,
8826 /*AllowBothBool*/ true,
8827 /*AllowBoolConversions*/ false,
8828 /*AllowBooleanOperation*/ IsBoolVecLang,
8829 /*ReportInvalid*/ true);
8830 if (VecResTy.isNull())
8831 return QualType();
8832 // The result type must match the condition type as specified in
8833 // OpenCL v1.1 s6.11.6.
8834 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8835 return QualType();
8836 return VecResTy;
8837 }
8838
8839 // Both operands are scalar.
8840 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8841}
8842
8843/// Return true if the Expr is block type
8844static bool checkBlockType(Sema &S, const Expr *E) {
8845 if (E->getType()->isBlockPointerType()) {
8846 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8847 return true;
8848 }
8849
8850 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8851 QualType Ty = CE->getCallee()->getType();
8852 if (Ty->isBlockPointerType()) {
8853 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8854 return true;
8855 }
8856 }
8857 return false;
8858}
8859
8860/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8861/// In that case, LHS = cond.
8862/// C99 6.5.15
8865 ExprObjectKind &OK,
8866 SourceLocation QuestionLoc) {
8867
8868 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8869 if (!LHSResult.isUsable()) return QualType();
8870 LHS = LHSResult;
8871
8872 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8873 if (!RHSResult.isUsable()) return QualType();
8874 RHS = RHSResult;
8875
8876 // C++ is sufficiently different to merit its own checker.
8877 if (getLangOpts().CPlusPlus)
8878 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8879
8880 VK = VK_PRValue;
8881 OK = OK_Ordinary;
8882
8883 if (Context.isDependenceAllowed() &&
8884 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8885 RHS.get()->isTypeDependent())) {
8886 assert(!getLangOpts().CPlusPlus);
8887 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8888 RHS.get()->containsErrors()) &&
8889 "should only occur in error-recovery path.");
8890 return Context.DependentTy;
8891 }
8892
8893 // The OpenCL operator with a vector condition is sufficiently
8894 // different to merit its own checker.
8895 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8896 Cond.get()->getType()->isExtVectorType())
8897 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8898
8899 // First, check the condition.
8901 if (Cond.isInvalid())
8902 return QualType();
8903 if (checkCondition(*this, Cond.get(), QuestionLoc))
8904 return QualType();
8905
8906 // Handle vectors.
8907 if (LHS.get()->getType()->isVectorType() ||
8908 RHS.get()->getType()->isVectorType())
8909 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8910 /*AllowBothBool*/ true,
8911 /*AllowBoolConversions*/ false,
8912 /*AllowBooleanOperation*/ false,
8913 /*ReportInvalid*/ true);
8914
8915 QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc,
8917 if (LHS.isInvalid() || RHS.isInvalid())
8918 return QualType();
8919
8920 // WebAssembly tables are not allowed as conditional LHS or RHS.
8921 QualType LHSTy = LHS.get()->getType();
8922 QualType RHSTy = RHS.get()->getType();
8923 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8924 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8925 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8926 return QualType();
8927 }
8928
8929 // Diagnose attempts to convert between __ibm128, __float128 and long double
8930 // where such conversions currently can't be handled.
8931 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8932 Diag(QuestionLoc,
8933 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8934 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8935 return QualType();
8936 }
8937
8938 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8939 // selection operator (?:).
8940 if (getLangOpts().OpenCL &&
8941 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8942 return QualType();
8943 }
8944
8945 // If both operands have arithmetic type, do the usual arithmetic conversions
8946 // to find a common type: C99 6.5.15p3,5.
8947 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8948 // Disallow invalid arithmetic conversions, such as those between bit-
8949 // precise integers types of different sizes, or between a bit-precise
8950 // integer and another type.
8951 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8952 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8953 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8954 << RHS.get()->getSourceRange();
8955 return QualType();
8956 }
8957
8958 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8959 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8960
8961 return ResTy;
8962 }
8963
8964 // If both operands are the same structure or union type, the result is that
8965 // type.
8966 // FIXME: Type of conditional expression must be complete in C mode.
8967 if (LHSTy->isRecordType() &&
8968 Context.hasSameUnqualifiedType(LHSTy, RHSTy)) // C99 6.5.15p3
8969 return Context.getCommonSugaredType(LHSTy.getUnqualifiedType(),
8970 RHSTy.getUnqualifiedType());
8971
8972 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8973 // The following || allows only one side to be void (a GCC-ism).
8974 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8975 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8976 // UsualArithmeticConversions already handled the case where both sides
8977 // are the same type.
8978 } else if (RHSTy->isVoidType()) {
8979 ResTy = RHSTy;
8980 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8981 << RHS.get()->getSourceRange();
8982 } else {
8983 ResTy = LHSTy;
8984 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8985 << LHS.get()->getSourceRange();
8986 }
8987 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8988 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8989 return ResTy;
8990 }
8991
8992 // C23 6.5.15p7:
8993 // ... if both the second and third operands have nullptr_t type, the
8994 // result also has that type.
8995 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8996 return ResTy;
8997
8998 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8999 // the type of the other operand."
9000 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
9001 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
9002
9003 // All objective-c pointer type analysis is done here.
9004 QualType compositeType =
9005 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
9006 if (LHS.isInvalid() || RHS.isInvalid())
9007 return QualType();
9008 if (!compositeType.isNull())
9009 return compositeType;
9010
9011
9012 // Handle block pointer types.
9013 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
9014 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
9015 QuestionLoc);
9016
9017 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9018 if (LHSTy->isPointerType() && RHSTy->isPointerType())
9019 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
9020 QuestionLoc);
9021
9022 // GCC compatibility: soften pointer/integer mismatch. Note that
9023 // null pointers have been filtered out by this point.
9024 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
9025 /*IsIntFirstExpr=*/true))
9026 return RHSTy;
9027 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
9028 /*IsIntFirstExpr=*/false))
9029 return LHSTy;
9030
9031 // Emit a better diagnostic if one of the expressions is a null pointer
9032 // constant and the other is not a pointer type. In this case, the user most
9033 // likely forgot to take the address of the other expression.
9034 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
9035 return QualType();
9036
9037 // Finally, if the LHS and RHS types are canonically the same type, we can
9038 // use the common sugared type.
9039 if (Context.hasSameType(LHSTy, RHSTy))
9040 return Context.getCommonSugaredType(LHSTy, RHSTy);
9041
9042 // Otherwise, the operands are not compatible.
9043 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
9044 << LHSTy << RHSTy << LHS.get()->getSourceRange()
9045 << RHS.get()->getSourceRange();
9046 return QualType();
9047}
9048
9049/// SuggestParentheses - Emit a note with a fixit hint that wraps
9050/// ParenRange in parentheses.
9052 const PartialDiagnostic &Note,
9053 SourceRange ParenRange) {
9054 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
9055 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
9056 EndLoc.isValid()) {
9057 Self.Diag(Loc, Note)
9058 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
9059 << FixItHint::CreateInsertion(EndLoc, ")");
9060 } else {
9061 // We can't display the parentheses, so just show the bare note.
9062 Self.Diag(Loc, Note) << ParenRange;
9063 }
9064}
9065
9067 return BinaryOperator::isAdditiveOp(Opc) ||
9069 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
9070 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9071 // not any of the logical operators. Bitwise-xor is commonly used as a
9072 // logical-xor because there is no logical-xor operator. The logical
9073 // operators, including uses of xor, have a high false positive rate for
9074 // precedence warnings.
9075}
9076
9077/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9078/// expression, either using a built-in or overloaded operator,
9079/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9080/// expression.
9081static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9082 const Expr **RHSExprs) {
9083 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9084 E = E->IgnoreImpCasts();
9086 E = E->IgnoreImpCasts();
9087 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9088 E = MTE->getSubExpr();
9089 E = E->IgnoreImpCasts();
9090 }
9091
9092 // Built-in binary operator.
9093 if (const auto *OP = dyn_cast<BinaryOperator>(E);
9094 OP && IsArithmeticOp(OP->getOpcode())) {
9095 *Opcode = OP->getOpcode();
9096 *RHSExprs = OP->getRHS();
9097 return true;
9098 }
9099
9100 // Overloaded operator.
9101 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9102 if (Call->getNumArgs() != 2)
9103 return false;
9104
9105 // Make sure this is really a binary operator that is safe to pass into
9106 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9107 OverloadedOperatorKind OO = Call->getOperator();
9108 if (OO < OO_Plus || OO > OO_Arrow ||
9109 OO == OO_PlusPlus || OO == OO_MinusMinus)
9110 return false;
9111
9113 if (IsArithmeticOp(OpKind)) {
9114 *Opcode = OpKind;
9115 *RHSExprs = Call->getArg(1);
9116 return true;
9117 }
9118 }
9119
9120 return false;
9121}
9122
9123/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9124/// or is a logical expression such as (x==y) which has int type, but is
9125/// commonly interpreted as boolean.
9126static bool ExprLooksBoolean(const Expr *E) {
9127 E = E->IgnoreParenImpCasts();
9128
9129 if (E->getType()->isBooleanType())
9130 return true;
9131 if (const auto *OP = dyn_cast<BinaryOperator>(E))
9132 return OP->isComparisonOp() || OP->isLogicalOp();
9133 if (const auto *OP = dyn_cast<UnaryOperator>(E))
9134 return OP->getOpcode() == UO_LNot;
9135 if (E->getType()->isPointerType())
9136 return true;
9137 // FIXME: What about overloaded operator calls returning "unspecified boolean
9138 // type"s (commonly pointer-to-members)?
9139
9140 return false;
9141}
9142
9143/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9144/// and binary operator are mixed in a way that suggests the programmer assumed
9145/// the conditional operator has higher precedence, for example:
9146/// "int x = a + someBinaryCondition ? 1 : 2".
9148 Expr *Condition, const Expr *LHSExpr,
9149 const Expr *RHSExpr) {
9150 BinaryOperatorKind CondOpcode;
9151 const Expr *CondRHS;
9152
9153 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9154 return;
9155 if (!ExprLooksBoolean(CondRHS))
9156 return;
9157
9158 // The condition is an arithmetic binary expression, with a right-
9159 // hand side that looks boolean, so warn.
9160
9161 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9162 ? diag::warn_precedence_bitwise_conditional
9163 : diag::warn_precedence_conditional;
9164
9165 Self.Diag(OpLoc, DiagID)
9166 << Condition->getSourceRange()
9167 << BinaryOperator::getOpcodeStr(CondOpcode);
9168
9170 Self, OpLoc,
9171 Self.PDiag(diag::note_precedence_silence)
9172 << BinaryOperator::getOpcodeStr(CondOpcode),
9173 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9174
9175 SuggestParentheses(Self, OpLoc,
9176 Self.PDiag(diag::note_precedence_conditional_first),
9177 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9178}
9179
9180/// Compute the nullability of a conditional expression.
9182 QualType LHSTy, QualType RHSTy,
9183 ASTContext &Ctx) {
9184 if (!ResTy->isAnyPointerType())
9185 return ResTy;
9186
9187 auto GetNullability = [](QualType Ty) {
9188 NullabilityKindOrNone Kind = Ty->getNullability();
9189 if (Kind) {
9190 // For our purposes, treat _Nullable_result as _Nullable.
9193 return *Kind;
9194 }
9196 };
9197
9198 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9199 NullabilityKind MergedKind;
9200
9201 // Compute nullability of a binary conditional expression.
9202 if (IsBin) {
9203 if (LHSKind == NullabilityKind::NonNull)
9204 MergedKind = NullabilityKind::NonNull;
9205 else
9206 MergedKind = RHSKind;
9207 // Compute nullability of a normal conditional expression.
9208 } else {
9209 if (LHSKind == NullabilityKind::Nullable ||
9210 RHSKind == NullabilityKind::Nullable)
9211 MergedKind = NullabilityKind::Nullable;
9212 else if (LHSKind == NullabilityKind::NonNull)
9213 MergedKind = RHSKind;
9214 else if (RHSKind == NullabilityKind::NonNull)
9215 MergedKind = LHSKind;
9216 else
9217 MergedKind = NullabilityKind::Unspecified;
9218 }
9219
9220 // Return if ResTy already has the correct nullability.
9221 if (GetNullability(ResTy) == MergedKind)
9222 return ResTy;
9223
9224 // Strip all nullability from ResTy.
9225 while (ResTy->getNullability())
9226 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9227
9228 // Create a new AttributedType with the new nullability kind.
9229 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
9230}
9231
9233 SourceLocation ColonLoc,
9234 Expr *CondExpr, Expr *LHSExpr,
9235 Expr *RHSExpr) {
9236 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9237 // was the condition.
9238 OpaqueValueExpr *opaqueValue = nullptr;
9239 Expr *commonExpr = nullptr;
9240 if (!LHSExpr) {
9241 commonExpr = CondExpr;
9242 // Lower out placeholder types first. This is important so that we don't
9243 // try to capture a placeholder. This happens in few cases in C++; such
9244 // as Objective-C++'s dictionary subscripting syntax.
9245 if (commonExpr->hasPlaceholderType()) {
9246 ExprResult result = CheckPlaceholderExpr(commonExpr);
9247 if (!result.isUsable()) return ExprError();
9248 commonExpr = result.get();
9249 }
9250 // We usually want to apply unary conversions *before* saving, except
9251 // in the special case of a C++ l-value conditional.
9252 if (!(getLangOpts().CPlusPlus
9253 && !commonExpr->isTypeDependent()
9254 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9255 && commonExpr->isGLValue()
9256 && commonExpr->isOrdinaryOrBitFieldObject()
9257 && RHSExpr->isOrdinaryOrBitFieldObject()
9258 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9259 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9260 if (commonRes.isInvalid())
9261 return ExprError();
9262 commonExpr = commonRes.get();
9263 }
9264
9265 // If the common expression is a class or array prvalue, materialize it
9266 // so that we can safely refer to it multiple times.
9267 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9268 commonExpr->getType()->isArrayType())) {
9269 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9270 if (MatExpr.isInvalid())
9271 return ExprError();
9272 commonExpr = MatExpr.get();
9273 }
9274
9275 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9276 commonExpr->getType(),
9277 commonExpr->getValueKind(),
9278 commonExpr->getObjectKind(),
9279 commonExpr);
9280 LHSExpr = CondExpr = opaqueValue;
9281 }
9282
9283 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9286 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9287 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9288 VK, OK, QuestionLoc);
9289 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9290 RHS.isInvalid())
9291 return ExprError();
9292
9293 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9294 RHS.get());
9295
9296 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9297
9298 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9299 Context);
9300
9301 if (!commonExpr)
9302 return new (Context)
9303 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9304 RHS.get(), result, VK, OK);
9305
9307 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9308 ColonLoc, result, VK, OK);
9309}
9310
9312 unsigned FromAttributes = 0, ToAttributes = 0;
9313 if (const auto *FromFn =
9314 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9315 FromAttributes =
9316 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9317 if (const auto *ToFn =
9318 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9319 ToAttributes =
9320 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9321
9322 return FromAttributes != ToAttributes;
9323}
9324
9325// checkPointerTypesForAssignment - This is a very tricky routine (despite
9326// being closely modeled after the C99 spec:-). The odd characteristic of this
9327// routine is it effectively iqnores the qualifiers on the top level pointee.
9328// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9329// FIXME: add a couple examples in this comment.
9331 QualType LHSType,
9332 QualType RHSType,
9333 SourceLocation Loc) {
9334 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9335 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9336
9337 // get the "pointed to" type (ignoring qualifiers at the top level)
9338 const Type *lhptee, *rhptee;
9339 Qualifiers lhq, rhq;
9340 std::tie(lhptee, lhq) =
9341 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9342 std::tie(rhptee, rhq) =
9343 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9344
9346
9347 // C99 6.5.16.1p1: This following citation is common to constraints
9348 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9349 // qualifiers of the type *pointed to* by the right;
9350
9351 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9352 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9354 // Ignore lifetime for further calculation.
9355 lhq.removeObjCLifetime();
9356 rhq.removeObjCLifetime();
9357 }
9358
9359 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
9360 // Treat address-space mismatches as fatal.
9361 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
9363
9364 // It's okay to add or remove GC or lifetime qualifiers when converting to
9365 // and from void*.
9368 S.getASTContext()) &&
9369 (lhptee->isVoidType() || rhptee->isVoidType()))
9370 ; // keep old
9371
9372 // Treat lifetime mismatches as fatal.
9373 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9375
9376 // Treat pointer-auth mismatches as fatal.
9377 else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth()))
9379
9380 // For GCC/MS compatibility, other qualifier mismatches are treated
9381 // as still compatible in C.
9382 else
9384 }
9385
9386 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9387 // incomplete type and the other is a pointer to a qualified or unqualified
9388 // version of void...
9389 if (lhptee->isVoidType()) {
9390 if (rhptee->isIncompleteOrObjectType())
9391 return ConvTy;
9392
9393 // As an extension, we allow cast to/from void* to function pointer.
9394 assert(rhptee->isFunctionType());
9396 }
9397
9398 if (rhptee->isVoidType()) {
9399 // In C, void * to another pointer type is compatible, but we want to note
9400 // that there will be an implicit conversion happening here.
9401 if (lhptee->isIncompleteOrObjectType())
9402 return ConvTy == AssignConvertType::Compatible &&
9403 !S.getLangOpts().CPlusPlus
9405 : ConvTy;
9406
9407 // As an extension, we allow cast to/from void* to function pointer.
9408 assert(lhptee->isFunctionType());
9410 }
9411
9412 if (!S.Diags.isIgnored(
9413 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9414 Loc) &&
9415 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9416 !S.TryFunctionConversion(RHSType, LHSType, RHSType))
9418
9419 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9420 // unqualified versions of compatible types, ...
9421 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9422
9423 if (ltrans->isOverflowBehaviorType() || rtrans->isOverflowBehaviorType()) {
9424 if (!S.Context.hasSameType(ltrans, rtrans)) {
9425 QualType LUnderlying =
9426 ltrans->isOverflowBehaviorType()
9427 ? ltrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9428 : ltrans;
9429 QualType RUnderlying =
9430 rtrans->isOverflowBehaviorType()
9431 ? rtrans->castAs<OverflowBehaviorType>()->getUnderlyingType()
9432 : rtrans;
9433
9434 if (S.Context.hasSameType(LUnderlying, RUnderlying))
9436
9437 ltrans = LUnderlying;
9438 rtrans = RUnderlying;
9439 }
9440 }
9441
9442 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9443 // Check if the pointee types are compatible ignoring the sign.
9444 // We explicitly check for char so that we catch "char" vs
9445 // "unsigned char" on systems where "char" is unsigned.
9446 if (lhptee->isCharType())
9447 ltrans = S.Context.UnsignedCharTy;
9448 else if (lhptee->hasSignedIntegerRepresentation())
9449 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9450
9451 if (rhptee->isCharType())
9452 rtrans = S.Context.UnsignedCharTy;
9453 else if (rhptee->hasSignedIntegerRepresentation())
9454 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9455
9456 if (ltrans == rtrans) {
9457 // Types are compatible ignoring the sign. Qualifier incompatibility
9458 // takes priority over sign incompatibility because the sign
9459 // warning can be disabled.
9460 if (!S.IsAssignConvertCompatible(ConvTy))
9461 return ConvTy;
9462
9464 }
9465
9466 // If we are a multi-level pointer, it's possible that our issue is simply
9467 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9468 // the eventual target type is the same and the pointers have the same
9469 // level of indirection, this must be the issue.
9470 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9471 do {
9472 std::tie(lhptee, lhq) =
9473 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9474 std::tie(rhptee, rhq) =
9475 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9476
9477 // Inconsistent address spaces at this point is invalid, even if the
9478 // address spaces would be compatible.
9479 // FIXME: This doesn't catch address space mismatches for pointers of
9480 // different nesting levels, like:
9481 // __local int *** a;
9482 // int ** b = a;
9483 // It's not clear how to actually determine when such pointers are
9484 // invalidly incompatible.
9485 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9486 return AssignConvertType::
9487 IncompatibleNestedPointerAddressSpaceMismatch;
9488
9489 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9490
9491 if (lhptee == rhptee)
9493 }
9494
9495 // General pointer incompatibility takes priority over qualifiers.
9496 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9499 }
9500 // Note: in C++, typesAreCompatible(ltrans, rtrans) will have guaranteed
9501 // hasSameType, so we can skip further checks.
9502 const auto *LFT = ltrans->getAs<FunctionType>();
9503 const auto *RFT = rtrans->getAs<FunctionType>();
9504 if (!S.getLangOpts().CPlusPlus && LFT && RFT) {
9505 // The invocation of IsFunctionConversion below will try to transform rtrans
9506 // to obtain an exact match for ltrans. This should not fail because of
9507 // mismatches in result type and parameter types, they were already checked
9508 // by typesAreCompatible above. So we will recreate rtrans (or where
9509 // appropriate ltrans) using the result type and parameter types from ltrans
9510 // (respectively rtrans), but keeping its ExtInfo/ExtProtoInfo.
9511 const auto *LFPT = dyn_cast<FunctionProtoType>(LFT);
9512 const auto *RFPT = dyn_cast<FunctionProtoType>(RFT);
9513 if (LFPT && RFPT) {
9514 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9515 LFPT->getParamTypes(),
9516 RFPT->getExtProtoInfo());
9517 } else if (LFPT) {
9519 EPI.ExtInfo = RFT->getExtInfo();
9520 rtrans = S.Context.getFunctionType(LFPT->getReturnType(),
9521 LFPT->getParamTypes(), EPI);
9522 } else if (RFPT) {
9523 // In this case, we want to retain rtrans as a FunctionProtoType, to keep
9524 // all of its ExtProtoInfo. Transform ltrans instead.
9526 EPI.ExtInfo = LFT->getExtInfo();
9527 ltrans = S.Context.getFunctionType(RFPT->getReturnType(),
9528 RFPT->getParamTypes(), EPI);
9529 } else {
9530 rtrans = S.Context.getFunctionNoProtoType(LFT->getReturnType(),
9531 RFT->getExtInfo());
9532 }
9533 if (!S.Context.hasSameUnqualifiedType(rtrans, ltrans) &&
9534 !S.IsFunctionConversion(rtrans, ltrans))
9536 }
9537 return ConvTy;
9538}
9539
9540/// checkBlockPointerTypesForAssignment - This routine determines whether two
9541/// block pointer types are compatible or whether a block and normal pointer
9542/// are compatible. It is more restrict than comparing two function pointer
9543// types.
9545 QualType LHSType,
9546 QualType RHSType) {
9547 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9548 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9549
9550 QualType lhptee, rhptee;
9551
9552 // get the "pointed to" type (ignoring qualifiers at the top level)
9553 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9554 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9555
9556 // In C++, the types have to match exactly.
9557 if (S.getLangOpts().CPlusPlus)
9559
9561
9562 // For blocks we enforce that qualifiers are identical.
9563 Qualifiers LQuals = lhptee.getLocalQualifiers();
9564 Qualifiers RQuals = rhptee.getLocalQualifiers();
9565 if (S.getLangOpts().OpenCL) {
9566 LQuals.removeAddressSpace();
9567 RQuals.removeAddressSpace();
9568 }
9569 if (LQuals != RQuals)
9571
9572 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9573 // assignment.
9574 // The current behavior is similar to C++ lambdas. A block might be
9575 // assigned to a variable iff its return type and parameters are compatible
9576 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9577 // an assignment. Presumably it should behave in way that a function pointer
9578 // assignment does in C, so for each parameter and return type:
9579 // * CVR and address space of LHS should be a superset of CVR and address
9580 // space of RHS.
9581 // * unqualified types should be compatible.
9582 if (S.getLangOpts().OpenCL) {
9584 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9585 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9587 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9589
9590 return ConvTy;
9591}
9592
9593/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9594/// for assignment compatibility.
9596 QualType LHSType,
9597 QualType RHSType) {
9598 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9599 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9600
9601 if (LHSType->isObjCBuiltinType()) {
9602 // Class is not compatible with ObjC object pointers.
9603 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9604 !RHSType->isObjCQualifiedClassType())
9607 }
9608 if (RHSType->isObjCBuiltinType()) {
9609 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9610 !LHSType->isObjCQualifiedClassType())
9613 }
9614 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9615 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9616
9617 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9618 // make an exception for id<P>
9619 !LHSType->isObjCQualifiedIdType())
9621
9622 if (S.Context.typesAreCompatible(LHSType, RHSType))
9624 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9627}
9628
9630 QualType LHSType,
9631 QualType RHSType) {
9632 // Fake up an opaque expression. We don't actually care about what
9633 // cast operations are required, so if CheckAssignmentConstraints
9634 // adds casts to this they'll be wasted, but fortunately that doesn't
9635 // usually happen on valid code.
9636 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9637 ExprResult RHSPtr = &RHSExpr;
9638 CastKind K;
9639
9640 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9641}
9642
9643/// This helper function returns true if QT is a vector type that has element
9644/// type ElementType.
9645static bool isVector(QualType QT, QualType ElementType) {
9646 if (const VectorType *VT = QT->getAs<VectorType>())
9647 return VT->getElementType().getCanonicalType() == ElementType;
9648 return false;
9649}
9650
9651/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9652/// has code to accommodate several GCC extensions when type checking
9653/// pointers. Here are some objectionable examples that GCC considers warnings:
9654///
9655/// int a, *pint;
9656/// short *pshort;
9657/// struct foo *pfoo;
9658///
9659/// pint = pshort; // warning: assignment from incompatible pointer type
9660/// a = pint; // warning: assignment makes integer from pointer without a cast
9661/// pint = a; // warning: assignment makes pointer from integer without a cast
9662/// pint = pfoo; // warning: assignment from incompatible pointer type
9663///
9664/// As a result, the code for dealing with pointers is more complex than the
9665/// C99 spec dictates.
9666///
9667/// Sets 'Kind' for any result kind except Incompatible.
9669 ExprResult &RHS,
9670 CastKind &Kind,
9671 bool ConvertRHS) {
9672 QualType RHSType = RHS.get()->getType();
9673 QualType OrigLHSType = LHSType;
9674
9675 // Get canonical types. We're not formatting these types, just comparing
9676 // them.
9677 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9678 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9679
9680 // Common case: no conversion required.
9681 if (LHSType == RHSType) {
9682 Kind = CK_NoOp;
9684 }
9685
9686 // If the LHS has an __auto_type, there are no additional type constraints
9687 // to be worried about.
9688 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9689 if (AT->isGNUAutoType()) {
9690 Kind = CK_NoOp;
9692 }
9693 }
9694
9695 auto OBTResult = Context.checkOBTAssignmentCompatibility(LHSType, RHSType);
9696 switch (OBTResult) {
9698 Kind = CK_NoOp;
9701 Kind = LHSType->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast;
9705 break;
9706 }
9707
9708 // Check for incompatible OBT types in pointer pointee types
9709 if (LHSType->isPointerType() && RHSType->isPointerType()) {
9710 QualType LHSPointee = LHSType->getPointeeType();
9711 QualType RHSPointee = RHSType->getPointeeType();
9712 if ((LHSPointee->isOverflowBehaviorType() ||
9713 RHSPointee->isOverflowBehaviorType()) &&
9714 !Context.areCompatibleOverflowBehaviorTypes(LHSPointee, RHSPointee)) {
9715 Kind = CK_NoOp;
9717 }
9718 }
9719
9720 // If we have an atomic type, try a non-atomic assignment, then just add an
9721 // atomic qualification step.
9722 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9724 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9726 return Result;
9727 if (Kind != CK_NoOp && ConvertRHS)
9728 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9729 Kind = CK_NonAtomicToAtomic;
9730 return Result;
9731 }
9732
9733 // If the left-hand side is a reference type, then we are in a
9734 // (rare!) case where we've allowed the use of references in C,
9735 // e.g., as a parameter type in a built-in function. In this case,
9736 // just make sure that the type referenced is compatible with the
9737 // right-hand side type. The caller is responsible for adjusting
9738 // LHSType so that the resulting expression does not have reference
9739 // type.
9740 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9741 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9742 Kind = CK_LValueBitCast;
9744 }
9746 }
9747
9748 // Allow scalar to ExtVector assignments, assignment to bool, and assignments
9749 // of an ExtVector type to the same ExtVector type.
9750 if (auto *LHSExtType = LHSType->getAs<ExtVectorType>()) {
9751 if (auto *RHSExtType = RHSType->getAs<ExtVectorType>()) {
9752 // Implicit conversions require the same number of elements.
9753 if (LHSExtType->getNumElements() != RHSExtType->getNumElements())
9755
9756 if (LHSType->isExtVectorBoolType() &&
9757 RHSExtType->getElementType()->isIntegerType()) {
9758 Kind = CK_IntegralToBoolean;
9760 }
9761 // In OpenCL, allow compatible vector types (e.g. half to _Float16)
9762 if (Context.getLangOpts().OpenCL &&
9763 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9764 Kind = CK_BitCast;
9766 }
9768 }
9769 if (RHSType->isArithmeticType()) {
9770 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9771 if (ConvertRHS)
9772 RHS = prepareVectorSplat(LHSType, RHS.get());
9773 Kind = CK_VectorSplat;
9775 }
9776 }
9777
9778 // Conversions to or from vector type.
9779 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9780 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9781 // Allow assignments of an AltiVec vector type to an equivalent GCC
9782 // vector type and vice versa
9783 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9784 Kind = CK_BitCast;
9786 }
9787
9788 // If we are allowing lax vector conversions, and LHS and RHS are both
9789 // vectors, the total size only needs to be the same. This is a bitcast;
9790 // no bits are changed but the result type is different.
9791 if (isLaxVectorConversion(RHSType, LHSType)) {
9792 // The default for lax vector conversions with Altivec vectors will
9793 // change, so if we are converting between vector types where
9794 // at least one is an Altivec vector, emit a warning.
9795 if (Context.getTargetInfo().getTriple().isPPC() &&
9796 anyAltivecTypes(RHSType, LHSType) &&
9797 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9798 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9799 << RHSType << LHSType;
9800 Kind = CK_BitCast;
9802 }
9803 }
9804
9805 // When the RHS comes from another lax conversion (e.g. binops between
9806 // scalars and vectors) the result is canonicalized as a vector. When the
9807 // LHS is also a vector, the lax is allowed by the condition above. Handle
9808 // the case where LHS is a scalar.
9809 if (LHSType->isScalarType()) {
9810 const VectorType *VecType = RHSType->getAs<VectorType>();
9811 if (VecType && VecType->getNumElements() == 1 &&
9812 isLaxVectorConversion(RHSType, LHSType)) {
9813 if (Context.getTargetInfo().getTriple().isPPC() &&
9815 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9817 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9818 << RHSType << LHSType;
9819 ExprResult *VecExpr = &RHS;
9820 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9821 Kind = CK_BitCast;
9823 }
9824 }
9825
9826 // Allow assignments between fixed-length and sizeless SVE vectors.
9827 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9828 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9829 if (ARM().areCompatibleSveTypes(LHSType, RHSType) ||
9830 ARM().areLaxCompatibleSveTypes(LHSType, RHSType)) {
9831 Kind = CK_BitCast;
9833 }
9834
9835 // Allow assignments between fixed-length and sizeless RVV vectors.
9836 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9837 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9838 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9839 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9840 Kind = CK_BitCast;
9842 }
9843 }
9844
9846 }
9847
9848 // Diagnose attempts to convert between __ibm128, __float128 and long double
9849 // where such conversions currently can't be handled.
9850 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9852
9853 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9854 // discards the imaginary part.
9855 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9856 !LHSType->getAs<ComplexType>())
9858
9859 // Arithmetic conversions.
9860 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9861 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9862 if (ConvertRHS)
9863 Kind = PrepareScalarCast(RHS, LHSType);
9865 }
9866
9867 // Conversions to normal pointers.
9868 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9869 // U* -> T*
9870 if (isa<PointerType>(RHSType)) {
9871 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9872 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9873 if (AddrSpaceL != AddrSpaceR)
9874 Kind = CK_AddressSpaceConversion;
9875 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9876 Kind = CK_NoOp;
9877 else
9878 Kind = CK_BitCast;
9879 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9880 RHS.get()->getBeginLoc());
9881 }
9882
9883 // int -> T*
9884 if (RHSType->isIntegerType()) {
9885 Kind = CK_IntegralToPointer; // FIXME: null?
9887 }
9888
9889 // C pointers are not compatible with ObjC object pointers,
9890 // with two exceptions:
9891 if (isa<ObjCObjectPointerType>(RHSType)) {
9892 // - conversions to void*
9893 if (LHSPointer->getPointeeType()->isVoidType()) {
9894 Kind = CK_BitCast;
9896 }
9897
9898 // - conversions from 'Class' to the redefinition type
9899 if (RHSType->isObjCClassType() &&
9900 Context.hasSameType(LHSType,
9901 Context.getObjCClassRedefinitionType())) {
9902 Kind = CK_BitCast;
9904 }
9905
9906 Kind = CK_BitCast;
9908 }
9909
9910 // U^ -> void*
9911 if (RHSType->getAs<BlockPointerType>()) {
9912 if (LHSPointer->getPointeeType()->isVoidType()) {
9913 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9914 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9915 ->getPointeeType()
9916 .getAddressSpace();
9917 Kind =
9918 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9920 }
9921 }
9922
9924 }
9925
9926 // Conversions to block pointers.
9927 if (isa<BlockPointerType>(LHSType)) {
9928 // U^ -> T^
9929 if (RHSType->isBlockPointerType()) {
9930 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9931 ->getPointeeType()
9932 .getAddressSpace();
9933 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9934 ->getPointeeType()
9935 .getAddressSpace();
9936 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9937 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9938 }
9939
9940 // int or null -> T^
9941 if (RHSType->isIntegerType()) {
9942 Kind = CK_IntegralToPointer; // FIXME: null
9944 }
9945
9946 // id -> T^
9947 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9948 Kind = CK_AnyPointerToBlockPointerCast;
9950 }
9951
9952 // void* -> T^
9953 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9954 if (RHSPT->getPointeeType()->isVoidType()) {
9955 Kind = CK_AnyPointerToBlockPointerCast;
9957 }
9958
9960 }
9961
9962 // Conversions to Objective-C pointers.
9963 if (isa<ObjCObjectPointerType>(LHSType)) {
9964 // A* -> B*
9965 if (RHSType->isObjCObjectPointerType()) {
9966 Kind = CK_BitCast;
9967 AssignConvertType result =
9968 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9969 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9971 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9973 return result;
9974 }
9975
9976 // int or null -> A*
9977 if (RHSType->isIntegerType()) {
9978 Kind = CK_IntegralToPointer; // FIXME: null
9980 }
9981
9982 // In general, C pointers are not compatible with ObjC object pointers,
9983 // with two exceptions:
9984 if (isa<PointerType>(RHSType)) {
9985 Kind = CK_CPointerToObjCPointerCast;
9986
9987 // - conversions from 'void*'
9988 if (RHSType->isVoidPointerType()) {
9990 }
9991
9992 // - conversions to 'Class' from its redefinition type
9993 if (LHSType->isObjCClassType() &&
9994 Context.hasSameType(RHSType,
9995 Context.getObjCClassRedefinitionType())) {
9997 }
9998
10000 }
10001
10002 // Only under strict condition T^ is compatible with an Objective-C pointer.
10003 if (RHSType->isBlockPointerType() &&
10005 if (ConvertRHS)
10007 Kind = CK_BlockPointerToObjCPointerCast;
10009 }
10010
10012 }
10013
10014 // Conversion to nullptr_t (C23 only)
10015 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
10018 // null -> nullptr_t
10019 Kind = CK_NullToPointer;
10021 }
10022
10023 // Conversions from pointers that are not covered by the above.
10024 if (isa<PointerType>(RHSType)) {
10025 // T* -> _Bool
10026 if (LHSType == Context.BoolTy) {
10027 Kind = CK_PointerToBoolean;
10029 }
10030
10031 // T* -> int
10032 if (LHSType->isIntegerType()) {
10033 Kind = CK_PointerToIntegral;
10035 }
10036
10038 }
10039
10040 // Conversions from Objective-C pointers that are not covered by the above.
10041 if (isa<ObjCObjectPointerType>(RHSType)) {
10042 // T* -> _Bool
10043 if (LHSType == Context.BoolTy) {
10044 Kind = CK_PointerToBoolean;
10046 }
10047
10048 // T* -> int
10049 if (LHSType->isIntegerType()) {
10050 Kind = CK_PointerToIntegral;
10052 }
10053
10055 }
10056
10057 // struct A -> struct B
10058 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
10059 if (Context.typesAreCompatible(LHSType, RHSType)) {
10060 Kind = CK_NoOp;
10062 }
10063 }
10064
10065 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
10066 Kind = CK_IntToOCLSampler;
10068 }
10069
10071}
10072
10073/// Constructs a transparent union from an expression that is
10074/// used to initialize the transparent union.
10076 ExprResult &EResult, QualType UnionType,
10077 FieldDecl *Field) {
10078 // Build an initializer list that designates the appropriate member
10079 // of the transparent union.
10080 Expr *E = EResult.get();
10082 C, SourceLocation(), E, SourceLocation(), /*isExplicit=*/false);
10083 Initializer->setType(UnionType);
10084 Initializer->setInitializedFieldInUnion(Field);
10085
10086 // Build a compound literal constructing a value of the transparent
10087 // union type from this initializer list.
10088 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
10089 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
10090 VK_PRValue, Initializer, false);
10091}
10092
10095 ExprResult &RHS) {
10096 QualType RHSType = RHS.get()->getType();
10097
10098 // If the ArgType is a Union type, we want to handle a potential
10099 // transparent_union GCC extension.
10100 const RecordType *UT = ArgType->getAsUnionType();
10101 if (!UT)
10103
10104 RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
10105 if (!UD->hasAttr<TransparentUnionAttr>())
10107
10108 // The field to initialize within the transparent union.
10109 FieldDecl *InitField = nullptr;
10110 // It's compatible if the expression matches any of the fields.
10111 for (auto *it : UD->fields()) {
10112 if (it->getType()->isPointerType()) {
10113 // If the transparent union contains a pointer type, we allow:
10114 // 1) void pointer
10115 // 2) null pointer constant
10116 if (RHSType->isPointerType())
10117 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
10118 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
10119 InitField = it;
10120 break;
10121 }
10122
10125 RHS = ImpCastExprToType(RHS.get(), it->getType(),
10126 CK_NullToPointer);
10127 InitField = it;
10128 break;
10129 }
10130 }
10131
10132 CastKind Kind;
10133 if (CheckAssignmentConstraints(it->getType(), RHS, Kind) ==
10135 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
10136 InitField = it;
10137 break;
10138 }
10139 }
10140
10141 if (!InitField)
10143
10144 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10146}
10147
10149 ExprResult &CallerRHS,
10150 bool Diagnose,
10151 bool DiagnoseCFAudited,
10152 bool ConvertRHS) {
10153 // We need to be able to tell the caller whether we diagnosed a problem, if
10154 // they ask us to issue diagnostics.
10155 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10156
10157 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10158 // we can't avoid *all* modifications at the moment, so we need some somewhere
10159 // to put the updated value.
10160 ExprResult LocalRHS = CallerRHS;
10161 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10162
10163 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10164 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10165 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10166 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10167 Diag(RHS.get()->getExprLoc(),
10168 diag::warn_noderef_to_dereferenceable_pointer)
10169 << RHS.get()->getSourceRange();
10170 }
10171 }
10172 }
10173
10174 if (getLangOpts().CPlusPlus) {
10175 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10176 // C++ 5.17p3: If the left operand is not of class type, the
10177 // expression is implicitly converted (C++ 4) to the
10178 // cv-unqualified type of the left operand.
10179 QualType RHSType = RHS.get()->getType();
10180 if (Diagnose) {
10181 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10183 } else {
10186 /*SuppressUserConversions=*/false,
10187 AllowedExplicit::None,
10188 /*InOverloadResolution=*/false,
10189 /*CStyle=*/false,
10190 /*AllowObjCWritebackConversion=*/false);
10191 if (ICS.isFailure())
10193 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10195 }
10196 if (RHS.isInvalid())
10199 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10200 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10202
10203 // Check if OBT is being discarded during assignment
10204 // The RHS may have propagated OBT, but if LHS doesn't have it, warn
10205 if (RHSType->isOverflowBehaviorType() &&
10206 !LHSType->isOverflowBehaviorType()) {
10208 }
10209
10210 return result;
10211 }
10212
10213 // FIXME: Currently, we fall through and treat C++ classes like C
10214 // structures.
10215 // FIXME: We also fall through for atomics; not sure what should
10216 // happen there, though.
10217 } else if (RHS.get()->getType() == Context.OverloadTy) {
10218 // As a set of extensions to C, we support overloading on functions. These
10219 // functions need to be resolved here.
10220 DeclAccessPair DAP;
10222 RHS.get(), LHSType, /*Complain=*/false, DAP))
10223 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10224 else
10226 }
10227
10228 // For HLSL records, insert derived-to-base conversion if needed.
10229 if (getLangOpts().HLSL && LHSType->isRecordType()) {
10230 QualType RHSType = RHS.get()->getType();
10231 if (!Context.hasSameUnqualifiedType(RHSType, LHSType)) {
10232 CXXBasePaths Paths;
10233 if (IsDerivedFrom(RHS.get()->getBeginLoc(), RHSType, LHSType, Paths)) {
10234 CXXCastPath CastPath;
10235 BuildBasePathArray(Paths, CastPath);
10236 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_DerivedToBase, VK_LValue,
10237 &CastPath);
10238 }
10239 }
10240 }
10241
10242 // This check seems unnatural, however it is necessary to ensure the proper
10243 // conversion of functions/arrays. If the conversion were done for all
10244 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10245 // expressions that suppress this implicit conversion (&, sizeof). This needs
10246 // to happen before we check for null pointer conversions because C does not
10247 // undergo the same implicit conversions as C++ does above (by the calls to
10248 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10249 // lvalue to rvalue cast before checking for null pointer constraints. This
10250 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10251 //
10252 // Suppress this for references: C++ 8.5.3p5.
10253 if (!LHSType->isReferenceType()) {
10254 // FIXME: We potentially allocate here even if ConvertRHS is false.
10256 if (RHS.isInvalid())
10258 }
10259
10260 // The constraints are expressed in terms of the atomic, qualified, or
10261 // unqualified type of the LHS.
10262 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10263
10264 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10265 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10266 if ((LHSTypeAfterConversion->isPointerType() ||
10267 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10268 LHSTypeAfterConversion->isBlockPointerType()) &&
10269 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10273 if (Diagnose || ConvertRHS) {
10274 CastKind Kind;
10275 CXXCastPath Path;
10276 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10277 /*IgnoreBaseAccess=*/false, Diagnose);
10278
10279 // If there is a conversion of some kind, check to see what kind of
10280 // pointer conversion happened so we can diagnose a C++ compatibility
10281 // diagnostic if the conversion is invalid. This only matters if the RHS
10282 // is some kind of void pointer. We have a carve-out when the RHS is from
10283 // a macro expansion because the use of a macro may indicate different
10284 // code between C and C++. Consider: char *s = NULL; where NULL is
10285 // defined as (void *)0 in C (which would be invalid in C++), but 0 in
10286 // C++, which is valid in C++.
10287 if (Kind != CK_NoOp && !getLangOpts().CPlusPlus &&
10288 !RHS.get()->getBeginLoc().isMacroID()) {
10289 QualType CanRHS =
10291 QualType CanLHS = LHSType.getCanonicalType().getUnqualifiedType();
10292 if (CanRHS->isVoidPointerType() && CanLHS->isPointerType()) {
10293 Ret = checkPointerTypesForAssignment(*this, CanLHS, CanRHS,
10294 RHS.get()->getExprLoc());
10295 // Anything that's not considered perfectly compatible would be
10296 // incompatible in C++.
10299 }
10300 }
10301
10302 if (ConvertRHS)
10303 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10304 }
10305 return Ret;
10306 }
10307 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10308 // unqualified bool, and the right operand is a pointer or its type is
10309 // nullptr_t.
10310 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10311 RHS.get()->getType()->isNullPtrType()) {
10312 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10313 // only handles nullptr -> _Bool due to needing an extra conversion
10314 // step.
10315 // We model this by converting from nullptr -> void * and then let the
10316 // conversion from void * -> _Bool happen naturally.
10317 if (Diagnose || ConvertRHS) {
10318 CastKind Kind;
10319 CXXCastPath Path;
10320 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10321 /*IgnoreBaseAccess=*/false, Diagnose);
10322 if (ConvertRHS)
10323 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10324 &Path);
10325 }
10326 }
10327
10328 // OpenCL queue_t type assignment.
10329 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10331 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10333 }
10334
10335 CastKind Kind;
10336 AssignConvertType result =
10337 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10338
10339 // If assigning a void * created by an allocation function call to some other
10340 // type, check that the allocated size is sufficient for that type.
10341 if (result != AssignConvertType::Incompatible &&
10342 RHS.get()->getType()->isVoidPointerType())
10343 CheckSufficientAllocSize(*this, LHSType, RHS.get());
10344
10345 // C99 6.5.16.1p2: The value of the right operand is converted to the
10346 // type of the assignment expression.
10347 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10348 // so that we can use references in built-in functions even in C.
10349 // The getNonReferenceType() call makes sure that the resulting expression
10350 // does not have reference type.
10351 if (result != AssignConvertType::Incompatible &&
10352 RHS.get()->getType() != LHSType) {
10354 Expr *E = RHS.get();
10355
10356 // Check for various Objective-C errors. If we are not reporting
10357 // diagnostics and just checking for errors, e.g., during overload
10358 // resolution, return Incompatible to indicate the failure.
10359 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10360 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
10362 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
10363 if (!Diagnose)
10365 }
10366 if (getLangOpts().ObjC &&
10367 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
10368 E->getType(), E, Diagnose) ||
10369 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10370 if (!Diagnose)
10372 // Replace the expression with a corrected version and continue so we
10373 // can find further errors.
10374 RHS = E;
10376 }
10377
10378 if (ConvertRHS)
10379 RHS = ImpCastExprToType(E, Ty, Kind);
10380 }
10381
10382 return result;
10383}
10384
10385namespace {
10386/// The original operand to an operator, prior to the application of the usual
10387/// arithmetic conversions and converting the arguments of a builtin operator
10388/// candidate.
10389struct OriginalOperand {
10390 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10391 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10392 Op = MTE->getSubExpr();
10393 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10394 Op = BTE->getSubExpr();
10395 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10396 Orig = ICE->getSubExprAsWritten();
10397 Conversion = ICE->getConversionFunction();
10398 }
10399 }
10400
10401 QualType getType() const { return Orig->getType(); }
10402
10403 Expr *Orig;
10404 NamedDecl *Conversion;
10405};
10406}
10407
10409 ExprResult &RHS) {
10410 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10411
10412 Diag(Loc, diag::err_typecheck_invalid_operands)
10413 << OrigLHS.getType() << OrigRHS.getType()
10414 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10415
10416 // If a user-defined conversion was applied to either of the operands prior
10417 // to applying the built-in operator rules, tell the user about it.
10418 if (OrigLHS.Conversion) {
10419 Diag(OrigLHS.Conversion->getLocation(),
10420 diag::note_typecheck_invalid_operands_converted)
10421 << 0 << LHS.get()->getType();
10422 }
10423 if (OrigRHS.Conversion) {
10424 Diag(OrigRHS.Conversion->getLocation(),
10425 diag::note_typecheck_invalid_operands_converted)
10426 << 1 << RHS.get()->getType();
10427 }
10428
10429 return QualType();
10430}
10431
10433 ExprResult &RHS) {
10434 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10435 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10436
10437 bool LHSNatVec = LHSType->isVectorType();
10438 bool RHSNatVec = RHSType->isVectorType();
10439
10440 if (!(LHSNatVec && RHSNatVec)) {
10441 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10442 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10443 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10444 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10445 << Vector->getSourceRange();
10446 return QualType();
10447 }
10448
10449 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10450 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10451 << RHS.get()->getSourceRange();
10452
10453 return QualType();
10454}
10455
10456/// Try to convert a value of non-vector type to a vector type by converting
10457/// the type to the element type of the vector and then performing a splat.
10458/// If the language is OpenCL, we only use conversions that promote scalar
10459/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10460/// for float->int.
10461///
10462/// OpenCL V2.0 6.2.6.p2:
10463/// An error shall occur if any scalar operand type has greater rank
10464/// than the type of the vector element.
10465///
10466/// \param scalar - if non-null, actually perform the conversions
10467/// \return true if the operation fails (but without diagnosing the failure)
10469 QualType scalarTy,
10470 QualType vectorEltTy,
10471 QualType vectorTy,
10472 unsigned &DiagID) {
10473 // The conversion to apply to the scalar before splatting it,
10474 // if necessary.
10475 CastKind scalarCast = CK_NoOp;
10476
10477 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
10478 scalarCast = CK_IntegralToBoolean;
10479 } else if (vectorEltTy->isIntegralType(S.Context)) {
10480 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10481 (scalarTy->isIntegerType() &&
10482 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10483 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10484 return true;
10485 }
10486 if (!scalarTy->isIntegralType(S.Context))
10487 return true;
10488 scalarCast = CK_IntegralCast;
10489 } else if (vectorEltTy->isRealFloatingType()) {
10490 if (scalarTy->isRealFloatingType()) {
10491 if (S.getLangOpts().OpenCL &&
10492 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10493 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10494 return true;
10495 }
10496 scalarCast = CK_FloatingCast;
10497 }
10498 else if (scalarTy->isIntegralType(S.Context))
10499 scalarCast = CK_IntegralToFloating;
10500 else
10501 return true;
10502 } else {
10503 return true;
10504 }
10505
10506 // Adjust scalar if desired.
10507 if (scalar) {
10508 if (scalarCast != CK_NoOp)
10509 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10510 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10511 }
10512 return false;
10513}
10514
10515/// Convert vector E to a vector with the same number of elements but different
10516/// element type.
10517static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10518 const auto *VecTy = E->getType()->getAs<VectorType>();
10519 assert(VecTy && "Expression E must be a vector");
10520 QualType NewVecTy =
10521 VecTy->isExtVectorType()
10522 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10523 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10524 VecTy->getVectorKind());
10525
10526 // Look through the implicit cast. Return the subexpression if its type is
10527 // NewVecTy.
10528 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10529 if (ICE->getSubExpr()->getType() == NewVecTy)
10530 return ICE->getSubExpr();
10531
10532 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10533 return S.ImpCastExprToType(E, NewVecTy, Cast);
10534}
10535
10536/// Test if a (constant) integer Int can be casted to another integer type
10537/// IntTy without losing precision.
10539 QualType OtherIntTy) {
10540 Expr *E = Int->get();
10542 return false;
10543
10544 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10545
10546 // Reject cases where the value of the Int is unknown as that would
10547 // possibly cause truncation, but accept cases where the scalar can be
10548 // demoted without loss of precision.
10549 Expr::EvalResult EVResult;
10550 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10551 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10552 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10553 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10554
10555 if (CstInt) {
10556 // If the scalar is constant and is of a higher order and has more active
10557 // bits that the vector element type, reject it.
10558 llvm::APSInt Result = EVResult.Val.getInt();
10559 unsigned NumBits = IntSigned
10560 ? (Result.isNegative() ? Result.getSignificantBits()
10561 : Result.getActiveBits())
10562 : Result.getActiveBits();
10563 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10564 return true;
10565
10566 // If the signedness of the scalar type and the vector element type
10567 // differs and the number of bits is greater than that of the vector
10568 // element reject it.
10569 return (IntSigned != OtherIntSigned &&
10570 NumBits > S.Context.getIntWidth(OtherIntTy));
10571 }
10572
10573 // Reject cases where the value of the scalar is not constant and it's
10574 // order is greater than that of the vector element type.
10575 return (Order < 0);
10576}
10577
10578/// Test if a (constant) integer Int can be casted to floating point type
10579/// FloatTy without losing precision.
10581 QualType FloatTy) {
10582 if (Int->get()->containsErrors())
10583 return false;
10584
10585 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10586
10587 // Determine if the integer constant can be expressed as a floating point
10588 // number of the appropriate type.
10589 Expr::EvalResult EVResult;
10590 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10591
10592 uint64_t Bits = 0;
10593 if (CstInt) {
10594 // Reject constants that would be truncated if they were converted to
10595 // the floating point type. Test by simple to/from conversion.
10596 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10597 // could be avoided if there was a convertFromAPInt method
10598 // which could signal back if implicit truncation occurred.
10599 llvm::APSInt Result = EVResult.Val.getInt();
10600 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10601 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10602 llvm::APFloat::rmTowardZero);
10603 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10605 bool Ignored = false;
10606 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10607 &Ignored);
10608 if (Result != ConvertBack)
10609 return true;
10610 } else {
10611 // Reject types that cannot be fully encoded into the mantissa of
10612 // the float.
10613 Bits = S.Context.getTypeSize(IntTy);
10614 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10615 S.Context.getFloatTypeSemantics(FloatTy));
10616 if (Bits > FloatPrec)
10617 return true;
10618 }
10619
10620 return false;
10621}
10622
10623/// Attempt to convert and splat Scalar into a vector whose types matches
10624/// Vector following GCC conversion rules. The rule is that implicit
10625/// conversion can occur when Scalar can be casted to match Vector's element
10626/// type without causing truncation of Scalar.
10628 ExprResult *Vector) {
10629 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10630 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10631 QualType VectorEltTy;
10632
10633 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10634 assert(!isa<ExtVectorType>(VT) &&
10635 "ExtVectorTypes should not be handled here!");
10636 VectorEltTy = VT->getElementType();
10637 } else if (VectorTy->isSveVLSBuiltinType()) {
10638 VectorEltTy =
10639 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10640 } else {
10641 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10642 }
10643
10644 // Reject cases where the vector element type or the scalar element type are
10645 // not integral or floating point types.
10646 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10647 return true;
10648
10649 // The conversion to apply to the scalar before splatting it,
10650 // if necessary.
10651 CastKind ScalarCast = CK_NoOp;
10652
10653 // Accept cases where the vector elements are integers and the scalar is
10654 // an integer.
10655 // FIXME: Notionally if the scalar was a floating point value with a precise
10656 // integral representation, we could cast it to an appropriate integer
10657 // type and then perform the rest of the checks here. GCC will perform
10658 // this conversion in some cases as determined by the input language.
10659 // We should accept it on a language independent basis.
10660 if (VectorEltTy->isIntegralType(S.Context) &&
10661 ScalarTy->isIntegralType(S.Context) &&
10662 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10663
10664 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10665 return true;
10666
10667 ScalarCast = CK_IntegralCast;
10668 } else if (VectorEltTy->isIntegralType(S.Context) &&
10669 ScalarTy->isRealFloatingType()) {
10670 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10671 ScalarCast = CK_FloatingToIntegral;
10672 else
10673 return true;
10674 } else if (VectorEltTy->isRealFloatingType()) {
10675 if (ScalarTy->isRealFloatingType()) {
10676
10677 // Reject cases where the scalar type is not a constant and has a higher
10678 // Order than the vector element type.
10679 llvm::APFloat Result(0.0);
10680
10681 // Determine whether this is a constant scalar. In the event that the
10682 // value is dependent (and thus cannot be evaluated by the constant
10683 // evaluator), skip the evaluation. This will then diagnose once the
10684 // expression is instantiated.
10685 bool CstScalar = Scalar->get()->isValueDependent() ||
10686 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10687 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10688 if (!CstScalar && Order < 0)
10689 return true;
10690
10691 // If the scalar cannot be safely casted to the vector element type,
10692 // reject it.
10693 if (CstScalar) {
10694 bool Truncated = false;
10695 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10696 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10697 if (Truncated)
10698 return true;
10699 }
10700
10701 ScalarCast = CK_FloatingCast;
10702 } else if (ScalarTy->isIntegralType(S.Context)) {
10703 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10704 return true;
10705
10706 ScalarCast = CK_IntegralToFloating;
10707 } else
10708 return true;
10709 } else if (ScalarTy->isEnumeralType())
10710 return true;
10711
10712 // Adjust scalar if desired.
10713 if (ScalarCast != CK_NoOp)
10714 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10715 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10716 return false;
10717}
10718
10720 SourceLocation Loc, bool IsCompAssign,
10721 bool AllowBothBool,
10722 bool AllowBoolConversions,
10723 bool AllowBoolOperation,
10724 bool ReportInvalid) {
10725 if (!IsCompAssign) {
10727 if (LHS.isInvalid())
10728 return QualType();
10729 }
10731 if (RHS.isInvalid())
10732 return QualType();
10733
10734 // For conversion purposes, we ignore any qualifiers.
10735 // For example, "const float" and "float" are equivalent.
10736 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10737 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10738
10739 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10740 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10741 assert(LHSVecType || RHSVecType);
10742
10743 if (getLangOpts().HLSL)
10744 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10745 IsCompAssign);
10746
10747 // Any operation with MFloat8 type is only possible with C intrinsics
10748 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10749 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10750 return InvalidOperands(Loc, LHS, RHS);
10751
10752 // AltiVec-style "vector bool op vector bool" combinations are allowed
10753 // for some operators but not others.
10754 if (!AllowBothBool && LHSVecType &&
10755 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10756 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10757 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10758
10759 // This operation may not be performed on boolean vectors.
10760 if (!AllowBoolOperation &&
10761 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10762 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10763
10764 // If the vector types are identical, return.
10765 if (Context.hasSameType(LHSType, RHSType))
10766 return Context.getCommonSugaredType(LHSType, RHSType);
10767
10768 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10769 if (LHSVecType && RHSVecType &&
10770 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10771 if (isa<ExtVectorType>(LHSVecType)) {
10772 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10773 return LHSType;
10774 }
10775
10776 if (!IsCompAssign)
10777 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10778 return RHSType;
10779 }
10780
10781 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10782 // can be mixed, with the result being the non-bool type. The non-bool
10783 // operand must have integer element type.
10784 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10785 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10786 (Context.getTypeSize(LHSVecType->getElementType()) ==
10787 Context.getTypeSize(RHSVecType->getElementType()))) {
10788 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10789 LHSVecType->getElementType()->isIntegerType() &&
10790 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10791 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10792 return LHSType;
10793 }
10794 if (!IsCompAssign &&
10795 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10796 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10797 RHSVecType->getElementType()->isIntegerType()) {
10798 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10799 return RHSType;
10800 }
10801 }
10802
10803 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10804 // invalid since the ambiguity can affect the ABI.
10805 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10806 unsigned &SVEorRVV) {
10807 const VectorType *VecType = SecondType->getAs<VectorType>();
10808 SVEorRVV = 0;
10809 if (FirstType->isSizelessBuiltinType() && VecType) {
10812 return true;
10818 SVEorRVV = 1;
10819 return true;
10820 }
10821 }
10822
10823 return false;
10824 };
10825
10826 unsigned SVEorRVV;
10827 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10828 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10829 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10830 << SVEorRVV << LHSType << RHSType;
10831 return QualType();
10832 }
10833
10834 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10835 // invalid since the ambiguity can affect the ABI.
10836 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10837 unsigned &SVEorRVV) {
10838 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10839 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10840
10841 SVEorRVV = 0;
10842 if (FirstVecType && SecondVecType) {
10843 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10844 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10845 SecondVecType->getVectorKind() ==
10847 return true;
10848 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10849 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10850 SecondVecType->getVectorKind() ==
10852 SecondVecType->getVectorKind() ==
10854 SecondVecType->getVectorKind() ==
10856 SVEorRVV = 1;
10857 return true;
10858 }
10859 }
10860 return false;
10861 }
10862
10863 if (SecondVecType &&
10864 SecondVecType->getVectorKind() == VectorKind::Generic) {
10865 if (FirstType->isSVESizelessBuiltinType())
10866 return true;
10867 if (FirstType->isRVVSizelessBuiltinType()) {
10868 SVEorRVV = 1;
10869 return true;
10870 }
10871 }
10872
10873 return false;
10874 };
10875
10876 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10877 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10878 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10879 << SVEorRVV << LHSType << RHSType;
10880 return QualType();
10881 }
10882
10883 // If there's a vector type and a scalar, try to convert the scalar to
10884 // the vector element type and splat.
10885 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10886 if (!RHSVecType) {
10887 if (isa<ExtVectorType>(LHSVecType)) {
10888 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10889 LHSVecType->getElementType(), LHSType,
10890 DiagID))
10891 return LHSType;
10892 } else {
10893 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10894 return LHSType;
10895 }
10896 }
10897 if (!LHSVecType) {
10898 if (isa<ExtVectorType>(RHSVecType)) {
10899 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10900 LHSType, RHSVecType->getElementType(),
10901 RHSType, DiagID))
10902 return RHSType;
10903 } else {
10904 if (LHS.get()->isLValue() ||
10905 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10906 return RHSType;
10907 }
10908 }
10909
10910 // FIXME: The code below also handles conversion between vectors and
10911 // non-scalars, we should break this down into fine grained specific checks
10912 // and emit proper diagnostics.
10913 QualType VecType = LHSVecType ? LHSType : RHSType;
10914 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10915 QualType OtherType = LHSVecType ? RHSType : LHSType;
10916 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10917 if (isLaxVectorConversion(OtherType, VecType)) {
10918 if (Context.getTargetInfo().getTriple().isPPC() &&
10919 anyAltivecTypes(RHSType, LHSType) &&
10920 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10921 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10922 // If we're allowing lax vector conversions, only the total (data) size
10923 // needs to be the same. For non compound assignment, if one of the types is
10924 // scalar, the result is always the vector type.
10925 if (!IsCompAssign) {
10926 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10927 return VecType;
10928 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10929 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10930 // type. Note that this is already done by non-compound assignments in
10931 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10932 // <1 x T> -> T. The result is also a vector type.
10933 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10934 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10935 ExprResult *RHSExpr = &RHS;
10936 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10937 return VecType;
10938 }
10939 }
10940
10941 // Okay, the expression is invalid.
10942
10943 // If there's a non-vector, non-real operand, diagnose that.
10944 if ((!RHSVecType && !RHSType->isRealType()) ||
10945 (!LHSVecType && !LHSType->isRealType())) {
10946 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10947 << LHSType << RHSType
10948 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10949 return QualType();
10950 }
10951
10952 // OpenCL V1.1 6.2.6.p1:
10953 // If the operands are of more than one vector type, then an error shall
10954 // occur. Implicit conversions between vector types are not permitted, per
10955 // section 6.2.1.
10956 if (getLangOpts().OpenCL &&
10957 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10958 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10959 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10960 << RHSType;
10961 return QualType();
10962 }
10963
10964
10965 // If there is a vector type that is not a ExtVector and a scalar, we reach
10966 // this point if scalar could not be converted to the vector's element type
10967 // without truncation.
10968 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10969 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10970 QualType Scalar = LHSVecType ? RHSType : LHSType;
10971 QualType Vector = LHSVecType ? LHSType : RHSType;
10972 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10973 Diag(Loc,
10974 diag::err_typecheck_vector_not_convertable_implict_truncation)
10975 << ScalarOrVector << Scalar << Vector;
10976
10977 return QualType();
10978 }
10979
10980 // Otherwise, use the generic diagnostic.
10981 Diag(Loc, DiagID)
10982 << LHSType << RHSType
10983 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10984 return QualType();
10985}
10986
10988 SourceLocation Loc,
10989 bool IsCompAssign,
10990 ArithConvKind OperationKind) {
10991 if (!IsCompAssign) {
10993 if (LHS.isInvalid())
10994 return QualType();
10995 }
10997 if (RHS.isInvalid())
10998 return QualType();
10999
11000 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
11001 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
11002
11003 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
11004 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
11005
11006 unsigned DiagID = diag::err_typecheck_invalid_operands;
11007 if ((OperationKind == ArithConvKind::Arithmetic) &&
11008 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11009 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
11010 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11011 << RHS.get()->getSourceRange();
11012 return QualType();
11013 }
11014
11015 if (Context.hasSameType(LHSType, RHSType))
11016 return LHSType;
11017
11018 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
11019 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
11020 return LHSType;
11021 }
11022 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
11023 if (LHS.get()->isLValue() ||
11024 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
11025 return RHSType;
11026 }
11027
11028 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
11029 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
11030 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
11031 << LHSType << RHSType << LHS.get()->getSourceRange()
11032 << RHS.get()->getSourceRange();
11033 return QualType();
11034 }
11035
11036 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11037 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11038 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
11039 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11040 << LHSType << RHSType << LHS.get()->getSourceRange()
11041 << RHS.get()->getSourceRange();
11042 return QualType();
11043 }
11044
11045 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
11046 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
11047 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
11048 bool ScalarOrVector =
11049 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
11050
11051 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
11052 << ScalarOrVector << Scalar << Vector;
11053
11054 return QualType();
11055 }
11056
11057 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
11058 << RHS.get()->getSourceRange();
11059 return QualType();
11060}
11061
11062// checkArithmeticNull - Detect when a NULL constant is used improperly in an
11063// expression. These are mainly cases where the null pointer is used as an
11064// integer instead of a pointer.
11066 SourceLocation Loc, bool IsCompare) {
11067 // The canonical way to check for a GNU null is with isNullPointerConstant,
11068 // but we use a bit of a hack here for speed; this is a relatively
11069 // hot path, and isNullPointerConstant is slow.
11070 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
11071 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
11072
11073 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
11074
11075 // Avoid analyzing cases where the result will either be invalid (and
11076 // diagnosed as such) or entirely valid and not something to warn about.
11077 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
11078 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
11079 return;
11080
11081 // Comparison operations would not make sense with a null pointer no matter
11082 // what the other expression is.
11083 if (!IsCompare) {
11084 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
11085 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
11086 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
11087 return;
11088 }
11089
11090 // The rest of the operations only make sense with a null pointer
11091 // if the other expression is a pointer.
11092 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
11093 NonNullType->canDecayToPointerType())
11094 return;
11095
11096 S.Diag(Loc, diag::warn_null_in_comparison_operation)
11097 << LHSNull /* LHS is NULL */ << NonNullType
11098 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11099}
11100
11102 SourceLocation OpLoc) {
11103 // If the divisor is real, then this is real/real or complex/real division.
11104 // Either way there can be no precision loss.
11105 auto *CT = DivisorTy->getAs<ComplexType>();
11106 if (!CT)
11107 return;
11108
11109 QualType ElementType = CT->getElementType().getCanonicalType();
11110 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
11112 if (!ElementType->isFloatingType() || !IsComplexRangePromoted)
11113 return;
11114
11115 ASTContext &Ctx = S.getASTContext();
11116 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
11117 const llvm::fltSemantics &ElementTypeSemantics =
11118 Ctx.getFloatTypeSemantics(ElementType);
11119 const llvm::fltSemantics &HigherElementTypeSemantics =
11120 Ctx.getFloatTypeSemantics(HigherElementType);
11121
11122 if ((llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
11123 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) ||
11124 (HigherElementType == Ctx.LongDoubleTy &&
11125 !Ctx.getTargetInfo().hasLongDoubleType())) {
11126 // Retain the location of the first use of higher precision type.
11129 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
11130 if (Type == HigherElementType) {
11131 Num++;
11132 return;
11133 }
11134 }
11135 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
11136 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
11137 }
11138}
11139
11141 SourceLocation Loc) {
11142 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
11143 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
11144 if (!LUE || !RUE)
11145 return;
11146 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
11147 RUE->getKind() != UETT_SizeOf)
11148 return;
11149
11150 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
11151 QualType LHSTy = LHSArg->getType();
11152 QualType RHSTy;
11153
11154 if (RUE->isArgumentType())
11155 RHSTy = RUE->getArgumentType().getNonReferenceType();
11156 else
11157 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
11158
11159 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
11160 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
11161 return;
11162
11163 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
11164 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11165 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11166 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
11167 << LHSArgDecl;
11168 }
11169 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
11170 QualType ArrayElemTy = ArrayTy->getElementType();
11171 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
11172 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
11173 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
11174 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
11175 return;
11176 S.Diag(Loc, diag::warn_division_sizeof_array)
11177 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
11178 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
11179 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
11180 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
11181 << LHSArgDecl;
11182 }
11183
11184 S.Diag(Loc, diag::note_precedence_silence) << RHS;
11185 }
11186}
11187
11189 ExprResult &RHS,
11190 SourceLocation Loc, bool IsDiv) {
11191 // Check for division/remainder by zero.
11192 Expr::EvalResult RHSValue;
11193 if (!RHS.get()->isValueDependent() &&
11194 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
11195 RHSValue.Val.getInt() == 0)
11196 S.DiagRuntimeBehavior(Loc, RHS.get(),
11197 S.PDiag(diag::warn_remainder_division_by_zero)
11198 << IsDiv << RHS.get()->getSourceRange());
11199}
11200
11201static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc,
11202 const ExprResult &LHS, const ExprResult &RHS,
11203 BinaryOperatorKind Opc) {
11204 if (!LHS.isUsable() || !RHS.isUsable())
11205 return;
11206 const Expr *LHSExpr = LHS.get();
11207 const Expr *RHSExpr = RHS.get();
11208 const QualType LHSType = LHSExpr->getType();
11209 const QualType RHSType = RHSExpr->getType();
11210 const bool LHSIsScoped = LHSType->isScopedEnumeralType();
11211 const bool RHSIsScoped = RHSType->isScopedEnumeralType();
11212 if (!LHSIsScoped && !RHSIsScoped)
11213 return;
11214 if (BinaryOperator::isAssignmentOp(Opc) && LHSIsScoped)
11215 return;
11216 if (!LHSIsScoped && !LHSType->isIntegralOrUnscopedEnumerationType())
11217 return;
11218 if (!RHSIsScoped && !RHSType->isIntegralOrUnscopedEnumerationType())
11219 return;
11220 auto DiagnosticHelper = [&S](const Expr *expr, const QualType type) {
11221 SourceLocation BeginLoc = expr->getBeginLoc();
11222 QualType IntType = type->castAs<EnumType>()
11223 ->getDecl()
11224 ->getDefinitionOrSelf()
11225 ->getIntegerType();
11226 std::string InsertionString = "static_cast<" + IntType.getAsString() + ">(";
11227 S.Diag(BeginLoc, diag::note_no_implicit_conversion_for_scoped_enum)
11228 << FixItHint::CreateInsertion(BeginLoc, InsertionString)
11229 << FixItHint::CreateInsertion(expr->getEndLoc(), ")");
11230 };
11231 if (LHSIsScoped) {
11232 DiagnosticHelper(LHSExpr, LHSType);
11233 }
11234 if (RHSIsScoped) {
11235 DiagnosticHelper(RHSExpr, RHSType);
11236 }
11237}
11238
11240 SourceLocation Loc,
11241 BinaryOperatorKind Opc) {
11242 bool IsCompAssign = Opc == BO_MulAssign || Opc == BO_DivAssign;
11243 bool IsDiv = Opc == BO_Div || Opc == BO_DivAssign;
11244
11245 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11246
11247 QualType LHSTy = LHS.get()->getType();
11248 QualType RHSTy = RHS.get()->getType();
11249 if (LHSTy->isVectorType() || RHSTy->isVectorType())
11250 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11251 /*AllowBothBool*/ getLangOpts().AltiVec,
11252 /*AllowBoolConversions*/ false,
11253 /*AllowBooleanOperation*/ false,
11254 /*ReportInvalid*/ true);
11255 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
11256 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11258 if (!IsDiv &&
11259 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
11260 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
11261 // For division, only matrix-by-scalar is supported. Other combinations with
11262 // matrix types are invalid.
11263 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
11264 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
11265
11267 LHS, RHS, Loc,
11269 if (LHS.isInvalid() || RHS.isInvalid())
11270 return QualType();
11271
11272 if (compType.isNull() || !compType->isArithmeticType()) {
11273 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11274 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11275 return ResultTy;
11276 }
11277 if (IsDiv) {
11278 DetectPrecisionLossInComplexDivision(*this, RHS.get()->getType(), Loc);
11279 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
11280 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
11281 }
11282 return compType;
11283}
11284
11286 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
11287 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11288
11289 // Note: This check is here to simplify the double exclusions of
11290 // scalar and vector HLSL checks. No getLangOpts().HLSL
11291 // is needed since all languages exlcude doubles.
11292 if (LHS.get()->getType()->isDoubleType() ||
11293 RHS.get()->getType()->isDoubleType() ||
11294 (LHS.get()->getType()->isVectorType() && LHS.get()
11295 ->getType()
11296 ->getAs<VectorType>()
11297 ->getElementType()
11298 ->isDoubleType()) ||
11299 (RHS.get()->getType()->isVectorType() && RHS.get()
11300 ->getType()
11301 ->getAs<VectorType>()
11302 ->getElementType()
11303 ->isDoubleType()))
11304 return InvalidOperands(Loc, LHS, RHS);
11305
11306 if (LHS.get()->getType()->isVectorType() ||
11307 RHS.get()->getType()->isVectorType()) {
11308 if ((LHS.get()->getType()->hasIntegerRepresentation() &&
11309 RHS.get()->getType()->hasIntegerRepresentation()) ||
11310 (getLangOpts().HLSL &&
11311 (LHS.get()->getType()->hasFloatingRepresentation() ||
11313 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
11314 /*AllowBothBool*/ getLangOpts().AltiVec,
11315 /*AllowBoolConversions*/ false,
11316 /*AllowBooleanOperation*/ false,
11317 /*ReportInvalid*/ true);
11318 return InvalidOperands(Loc, LHS, RHS);
11319 }
11320
11321 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11322 RHS.get()->getType()->isSveVLSBuiltinType()) {
11323 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11325 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11327
11328 return InvalidOperands(Loc, LHS, RHS);
11329 }
11330
11332 LHS, RHS, Loc,
11334 if (LHS.isInvalid() || RHS.isInvalid())
11335 return QualType();
11336
11337 if (compType.isNull() ||
11338 (!compType->isIntegerType() &&
11339 !(getLangOpts().HLSL && compType->isFloatingType()))) {
11340 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11341 diagnoseScopedEnums(*this, Loc, LHS, RHS,
11342 IsCompAssign ? BO_RemAssign : BO_Rem);
11343 return ResultTy;
11344 }
11345 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11346 return compType;
11347}
11348
11349/// Diagnose invalid arithmetic on two void pointers.
11351 Expr *LHSExpr, Expr *RHSExpr) {
11352 S.Diag(Loc, S.getLangOpts().CPlusPlus
11353 ? diag::err_typecheck_pointer_arith_void_type
11354 : diag::ext_gnu_void_ptr)
11355 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11356 << RHSExpr->getSourceRange();
11357}
11358
11359/// Diagnose invalid arithmetic on a void pointer.
11361 Expr *Pointer) {
11362 S.Diag(Loc, S.getLangOpts().CPlusPlus
11363 ? diag::err_typecheck_pointer_arith_void_type
11364 : diag::ext_gnu_void_ptr)
11365 << 0 /* one pointer */ << Pointer->getSourceRange();
11366}
11367
11368/// Diagnose invalid arithmetic on a null pointer.
11369///
11370/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11371/// idiom, which we recognize as a GNU extension.
11372///
11374 Expr *Pointer, bool IsGNUIdiom) {
11375 if (IsGNUIdiom)
11376 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11377 << Pointer->getSourceRange();
11378 else
11379 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11380 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11381}
11382
11383/// Diagnose invalid subraction on a null pointer.
11384///
11386 Expr *Pointer, bool BothNull) {
11387 // Null - null is valid in C++ [expr.add]p7
11388 if (BothNull && S.getLangOpts().CPlusPlus)
11389 return;
11390
11391 // Is this s a macro from a system header?
11393 return;
11394
11396 S.PDiag(diag::warn_pointer_sub_null_ptr)
11397 << S.getLangOpts().CPlusPlus
11398 << Pointer->getSourceRange());
11399}
11400
11401/// Diagnose invalid arithmetic on two function pointers.
11403 Expr *LHS, Expr *RHS) {
11404 assert(LHS->getType()->isAnyPointerType());
11405 assert(RHS->getType()->isAnyPointerType());
11406 S.Diag(Loc, S.getLangOpts().CPlusPlus
11407 ? diag::err_typecheck_pointer_arith_function_type
11408 : diag::ext_gnu_ptr_func_arith)
11409 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11410 // We only show the second type if it differs from the first.
11412 RHS->getType())
11413 << RHS->getType()->getPointeeType()
11414 << LHS->getSourceRange() << RHS->getSourceRange();
11415}
11416
11417/// Diagnose invalid arithmetic on a function pointer.
11419 Expr *Pointer) {
11420 assert(Pointer->getType()->isAnyPointerType());
11421 S.Diag(Loc, S.getLangOpts().CPlusPlus
11422 ? diag::err_typecheck_pointer_arith_function_type
11423 : diag::ext_gnu_ptr_func_arith)
11424 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11425 << 0 /* one pointer, so only one type */
11426 << Pointer->getSourceRange();
11427}
11428
11429/// Emit error if Operand is incomplete pointer type
11430///
11431/// \returns True if pointer has incomplete type
11433 Expr *Operand) {
11434 QualType ResType = Operand->getType();
11435 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11436 ResType = ResAtomicType->getValueType();
11437
11438 assert(ResType->isAnyPointerType());
11439 QualType PointeeTy = ResType->getPointeeType();
11440 return S.RequireCompleteSizedType(
11441 Loc, PointeeTy,
11442 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11443 Operand->getSourceRange());
11444}
11445
11446/// Check the validity of an arithmetic pointer operand.
11447///
11448/// If the operand has pointer type, this code will check for pointer types
11449/// which are invalid in arithmetic operations. These will be diagnosed
11450/// appropriately, including whether or not the use is supported as an
11451/// extension.
11452///
11453/// \returns True when the operand is valid to use (even if as an extension).
11455 Expr *Operand) {
11456 QualType ResType = Operand->getType();
11457 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11458 ResType = ResAtomicType->getValueType();
11459
11460 if (!ResType->isAnyPointerType()) return true;
11461
11462 QualType PointeeTy = ResType->getPointeeType();
11463 if (PointeeTy->isVoidType()) {
11464 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11465 return !S.getLangOpts().CPlusPlus;
11466 }
11467 if (PointeeTy->isFunctionType()) {
11468 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11469 return !S.getLangOpts().CPlusPlus;
11470 }
11471
11472 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11473
11474 return true;
11475}
11476
11477/// Check the validity of a binary arithmetic operation w.r.t. pointer
11478/// operands.
11479///
11480/// This routine will diagnose any invalid arithmetic on pointer operands much
11481/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11482/// for emitting a single diagnostic even for operations where both LHS and RHS
11483/// are (potentially problematic) pointers.
11484///
11485/// \returns True when the operand is valid to use (even if as an extension).
11487 Expr *LHSExpr, Expr *RHSExpr) {
11488 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11489 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11490 if (!isLHSPointer && !isRHSPointer) return true;
11491
11492 QualType LHSPointeeTy, RHSPointeeTy;
11493 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11494 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11495
11496 // if both are pointers check if operation is valid wrt address spaces
11497 if (isLHSPointer && isRHSPointer) {
11498 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
11499 S.getASTContext())) {
11500 S.Diag(Loc,
11501 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11502 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11503 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11504 return false;
11505 }
11506 }
11507
11508 // Check for arithmetic on pointers to incomplete types.
11509 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11510 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11511 if (isLHSVoidPtr || isRHSVoidPtr) {
11512 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11513 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11514 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11515
11516 return !S.getLangOpts().CPlusPlus;
11517 }
11518
11519 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11520 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11521 if (isLHSFuncPtr || isRHSFuncPtr) {
11522 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11523 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11524 RHSExpr);
11525 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11526
11527 return !S.getLangOpts().CPlusPlus;
11528 }
11529
11530 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11531 return false;
11532 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11533 return false;
11534
11535 return true;
11536}
11537
11538/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11539/// literal.
11541 Expr *LHSExpr, Expr *RHSExpr) {
11542 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11543 Expr* IndexExpr = RHSExpr;
11544 if (!StrExpr) {
11545 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11546 IndexExpr = LHSExpr;
11547 }
11548
11549 bool IsStringPlusInt = StrExpr &&
11551 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11552 return;
11553
11554 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11555 Self.Diag(OpLoc, diag::warn_string_plus_int)
11556 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11557
11558 // Only print a fixit for "str" + int, not for int + "str".
11559 if (IndexExpr == RHSExpr) {
11560 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11561 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11562 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11564 << FixItHint::CreateInsertion(EndLoc, "]");
11565 } else
11566 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11567}
11568
11569/// Emit a warning when adding a char literal to a string.
11571 Expr *LHSExpr, Expr *RHSExpr) {
11572 const Expr *StringRefExpr = LHSExpr;
11573 const CharacterLiteral *CharExpr =
11574 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11575
11576 if (!CharExpr) {
11577 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11578 StringRefExpr = RHSExpr;
11579 }
11580
11581 if (!CharExpr || !StringRefExpr)
11582 return;
11583
11584 const QualType StringType = StringRefExpr->getType();
11585
11586 // Return if not a PointerType.
11587 if (!StringType->isAnyPointerType())
11588 return;
11589
11590 // Return if not a CharacterType.
11591 if (!StringType->getPointeeType()->isAnyCharacterType())
11592 return;
11593
11594 ASTContext &Ctx = Self.getASTContext();
11595 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11596
11597 const QualType CharType = CharExpr->getType();
11598 if (!CharType->isAnyCharacterType() &&
11599 CharType->isIntegerType() &&
11600 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11601 Self.Diag(OpLoc, diag::warn_string_plus_char)
11602 << DiagRange << Ctx.CharTy;
11603 } else {
11604 Self.Diag(OpLoc, diag::warn_string_plus_char)
11605 << DiagRange << CharExpr->getType();
11606 }
11607
11608 // Only print a fixit for str + char, not for char + str.
11609 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11610 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11611 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11612 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11614 << FixItHint::CreateInsertion(EndLoc, "]");
11615 } else {
11616 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11617 }
11618}
11619
11620/// Emit error when two pointers are incompatible.
11622 Expr *LHSExpr, Expr *RHSExpr) {
11623 assert(LHSExpr->getType()->isAnyPointerType());
11624 assert(RHSExpr->getType()->isAnyPointerType());
11625 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11626 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11627 << RHSExpr->getSourceRange();
11628}
11629
11630// C99 6.5.6
11633 QualType* CompLHSTy) {
11634 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11635
11636 if (LHS.get()->getType()->isVectorType() ||
11637 RHS.get()->getType()->isVectorType()) {
11638 QualType compType =
11639 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11640 /*AllowBothBool*/ getLangOpts().AltiVec,
11641 /*AllowBoolConversions*/ getLangOpts().ZVector,
11642 /*AllowBooleanOperation*/ false,
11643 /*ReportInvalid*/ true);
11644 if (CompLHSTy) *CompLHSTy = compType;
11645 return compType;
11646 }
11647
11648 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11649 RHS.get()->getType()->isSveVLSBuiltinType()) {
11650 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11652 if (CompLHSTy)
11653 *CompLHSTy = compType;
11654 return compType;
11655 }
11656
11657 if (LHS.get()->getType()->isConstantMatrixType() ||
11658 RHS.get()->getType()->isConstantMatrixType()) {
11659 QualType compType =
11660 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11661 if (CompLHSTy)
11662 *CompLHSTy = compType;
11663 return compType;
11664 }
11665
11667 LHS, RHS, Loc,
11669 if (LHS.isInvalid() || RHS.isInvalid())
11670 return QualType();
11671
11672 // Diagnose "string literal" '+' int and string '+' "char literal".
11673 if (Opc == BO_Add) {
11674 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11675 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11676 }
11677
11678 // handle the common case first (both operands are arithmetic).
11679 if (!compType.isNull() && compType->isArithmeticType()) {
11680 if (CompLHSTy) *CompLHSTy = compType;
11681 return compType;
11682 }
11683
11684 // Type-checking. Ultimately the pointer's going to be in PExp;
11685 // note that we bias towards the LHS being the pointer.
11686 Expr *PExp = LHS.get(), *IExp = RHS.get();
11687
11688 bool isObjCPointer;
11689 if (PExp->getType()->isPointerType()) {
11690 isObjCPointer = false;
11691 } else if (PExp->getType()->isObjCObjectPointerType()) {
11692 isObjCPointer = true;
11693 } else {
11694 std::swap(PExp, IExp);
11695 if (PExp->getType()->isPointerType()) {
11696 isObjCPointer = false;
11697 } else if (PExp->getType()->isObjCObjectPointerType()) {
11698 isObjCPointer = true;
11699 } else {
11700 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11701 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11702 return ResultTy;
11703 }
11704 }
11705 assert(PExp->getType()->isAnyPointerType());
11706
11707 if (!IExp->getType()->isIntegerType())
11708 return InvalidOperands(Loc, LHS, RHS);
11709
11710 // Adding to a null pointer results in undefined behavior.
11713 // In C++ adding zero to a null pointer is defined.
11714 Expr::EvalResult KnownVal;
11715 if (!getLangOpts().CPlusPlus ||
11716 (!IExp->isValueDependent() &&
11717 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11718 KnownVal.Val.getInt() != 0))) {
11719 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11721 Context, BO_Add, PExp, IExp);
11722 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11723 }
11724 }
11725
11726 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11727 return QualType();
11728
11729 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11730 return QualType();
11731
11732 // Arithmetic on label addresses is normally allowed, except when we add
11733 // a ptrauth signature to the addresses.
11734 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
11735 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11736 << /*addition*/ 1;
11737 return QualType();
11738 }
11739
11740 // Check array bounds for pointer arithemtic
11741 CheckArrayAccess(PExp, IExp);
11742
11743 if (CompLHSTy) {
11744 QualType LHSTy = Context.isPromotableBitField(LHS.get());
11745 if (LHSTy.isNull()) {
11746 LHSTy = LHS.get()->getType();
11747 if (Context.isPromotableIntegerType(LHSTy))
11748 LHSTy = Context.getPromotedIntegerType(LHSTy);
11749 }
11750 *CompLHSTy = LHSTy;
11751 }
11752
11753 return PExp->getType();
11754}
11755
11756// C99 6.5.6
11758 SourceLocation Loc,
11760 QualType *CompLHSTy) {
11761 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11762
11763 if (LHS.get()->getType()->isVectorType() ||
11764 RHS.get()->getType()->isVectorType()) {
11765 QualType compType =
11766 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11767 /*AllowBothBool*/ getLangOpts().AltiVec,
11768 /*AllowBoolConversions*/ getLangOpts().ZVector,
11769 /*AllowBooleanOperation*/ false,
11770 /*ReportInvalid*/ true);
11771 if (CompLHSTy) *CompLHSTy = compType;
11772 return compType;
11773 }
11774
11775 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11776 RHS.get()->getType()->isSveVLSBuiltinType()) {
11777 QualType compType = CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy,
11779 if (CompLHSTy)
11780 *CompLHSTy = compType;
11781 return compType;
11782 }
11783
11784 if (LHS.get()->getType()->isConstantMatrixType() ||
11785 RHS.get()->getType()->isConstantMatrixType()) {
11786 QualType compType =
11787 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11788 if (CompLHSTy)
11789 *CompLHSTy = compType;
11790 return compType;
11791 }
11792
11794 LHS, RHS, Loc,
11796 if (LHS.isInvalid() || RHS.isInvalid())
11797 return QualType();
11798
11799 // Enforce type constraints: C99 6.5.6p3.
11800
11801 // Handle the common case first (both operands are arithmetic).
11802 if (!compType.isNull() && compType->isArithmeticType()) {
11803 if (CompLHSTy) *CompLHSTy = compType;
11804 return compType;
11805 }
11806
11807 // Either ptr - int or ptr - ptr.
11808 if (LHS.get()->getType()->isAnyPointerType()) {
11809 QualType lpointee = LHS.get()->getType()->getPointeeType();
11810
11811 // Diagnose bad cases where we step over interface counts.
11812 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11813 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11814 return QualType();
11815
11816 // Arithmetic on label addresses is normally allowed, except when we add
11817 // a ptrauth signature to the addresses.
11818 if (isa<AddrLabelExpr>(LHS.get()) &&
11819 getLangOpts().PointerAuthIndirectGotos) {
11820 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11821 << /*subtraction*/ 0;
11822 return QualType();
11823 }
11824
11825 // The result type of a pointer-int computation is the pointer type.
11826 if (RHS.get()->getType()->isIntegerType()) {
11827 // Subtracting from a null pointer should produce a warning.
11828 // The last argument to the diagnose call says this doesn't match the
11829 // GNU int-to-pointer idiom.
11832 // In C++ adding zero to a null pointer is defined.
11833 Expr::EvalResult KnownVal;
11834 if (!getLangOpts().CPlusPlus ||
11835 (!RHS.get()->isValueDependent() &&
11836 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11837 KnownVal.Val.getInt() != 0))) {
11838 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11839 }
11840 }
11841
11842 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11843 return QualType();
11844
11845 // Check array bounds for pointer arithemtic
11846 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11847 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11848
11849 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11850 return LHS.get()->getType();
11851 }
11852
11853 // Handle pointer-pointer subtractions.
11854 if (const PointerType *RHSPTy
11855 = RHS.get()->getType()->getAs<PointerType>()) {
11856 QualType rpointee = RHSPTy->getPointeeType();
11857
11858 if (getLangOpts().CPlusPlus) {
11859 // Pointee types must be the same: C++ [expr.add]
11860 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11861 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11862 }
11863 } else {
11864 // Pointee types must be compatible C99 6.5.6p3
11865 if (!Context.typesAreCompatible(
11866 Context.getCanonicalType(lpointee).getUnqualifiedType(),
11867 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
11868 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11869 return QualType();
11870 }
11871 }
11872
11874 LHS.get(), RHS.get()))
11875 return QualType();
11876
11877 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11879 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11881
11882 // Subtracting nullptr or from nullptr is suspect
11883 if (LHSIsNullPtr)
11884 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11885 if (RHSIsNullPtr)
11886 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11887
11888 // The pointee type may have zero size. As an extension, a structure or
11889 // union may have zero size or an array may have zero length. In this
11890 // case subtraction does not make sense.
11891 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11892 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11893 if (ElementSize.isZero()) {
11894 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11895 << rpointee.getUnqualifiedType()
11896 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11897 }
11898 }
11899
11900 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11901 return Context.getPointerDiffType();
11902 }
11903 }
11904
11905 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
11906 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
11907 return ResultTy;
11908}
11909
11911 if (const EnumType *ET = T->getAsCanonical<EnumType>())
11912 return ET->getDecl()->isScoped();
11913 return false;
11914}
11915
11918 QualType LHSType) {
11919 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11920 // so skip remaining warnings as we don't want to modify values within Sema.
11921 if (S.getLangOpts().OpenCL)
11922 return;
11923
11924 if (Opc == BO_Shr &&
11926 S.Diag(Loc, diag::warn_shift_bool) << LHS.get()->getSourceRange();
11927
11928 // Check right/shifter operand
11929 Expr::EvalResult RHSResult;
11930 if (RHS.get()->isValueDependent() ||
11931 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11932 return;
11933 llvm::APSInt Right = RHSResult.Val.getInt();
11934
11935 if (Right.isNegative()) {
11936 S.DiagRuntimeBehavior(Loc, RHS.get(),
11937 S.PDiag(diag::warn_shift_negative)
11938 << RHS.get()->getSourceRange());
11939 return;
11940 }
11941
11942 QualType LHSExprType = LHS.get()->getType();
11943 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11944 if (LHSExprType->isBitIntType())
11945 LeftSize = S.Context.getIntWidth(LHSExprType);
11946 else if (LHSExprType->isFixedPointType()) {
11947 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11948 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11949 }
11950 if (Right.uge(LeftSize)) {
11951 S.DiagRuntimeBehavior(Loc, RHS.get(),
11952 S.PDiag(diag::warn_shift_gt_typewidth)
11953 << RHS.get()->getSourceRange());
11954 return;
11955 }
11956
11957 // FIXME: We probably need to handle fixed point types specially here.
11958 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11959 return;
11960
11961 // When left shifting an ICE which is signed, we can check for overflow which
11962 // according to C++ standards prior to C++2a has undefined behavior
11963 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11964 // more than the maximum value representable in the result type, so never
11965 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11966 // expression is still probably a bug.)
11967 Expr::EvalResult LHSResult;
11968 if (LHS.get()->isValueDependent() ||
11970 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11971 return;
11972 llvm::APSInt Left = LHSResult.Val.getInt();
11973
11974 // Don't warn if signed overflow is defined, then all the rest of the
11975 // diagnostics will not be triggered because the behavior is defined.
11976 // Also don't warn in C++20 mode (and newer), as signed left shifts
11977 // always wrap and never overflow.
11978 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11979 return;
11980
11981 // If LHS does not have a non-negative value then, the
11982 // behavior is undefined before C++2a. Warn about it.
11983 if (Left.isNegative()) {
11984 S.DiagRuntimeBehavior(Loc, LHS.get(),
11985 S.PDiag(diag::warn_shift_lhs_negative)
11986 << LHS.get()->getSourceRange());
11987 return;
11988 }
11989
11990 llvm::APInt ResultBits =
11991 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11992 if (ResultBits.ule(LeftSize))
11993 return;
11994 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11995 Result = Result.shl(Right);
11996
11997 // Print the bit representation of the signed integer as an unsigned
11998 // hexadecimal number.
11999 SmallString<40> HexResult;
12000 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
12001
12002 // If we are only missing a sign bit, this is less likely to result in actual
12003 // bugs -- if the result is cast back to an unsigned type, it will have the
12004 // expected value. Thus we place this behind a different warning that can be
12005 // turned off separately if needed.
12006 if (ResultBits - 1 == LeftSize) {
12007 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
12008 << HexResult << LHSType
12009 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12010 return;
12011 }
12012
12013 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
12014 << HexResult.str() << Result.getSignificantBits() << LHSType
12015 << Left.getBitWidth() << LHS.get()->getSourceRange()
12016 << RHS.get()->getSourceRange();
12017}
12018
12019/// Return the resulting type when a vector is shifted
12020/// by a scalar or vector shift amount.
12022 SourceLocation Loc, bool IsCompAssign) {
12023 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12024 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
12025 !LHS.get()->getType()->isVectorType()) {
12026 S.Diag(Loc, diag::err_shift_rhs_only_vector)
12027 << RHS.get()->getType() << LHS.get()->getType()
12028 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12029 return QualType();
12030 }
12031
12032 if (!IsCompAssign) {
12033 LHS = S.UsualUnaryConversions(LHS.get());
12034 if (LHS.isInvalid()) return QualType();
12035 }
12036
12037 RHS = S.UsualUnaryConversions(RHS.get());
12038 if (RHS.isInvalid()) return QualType();
12039
12040 QualType LHSType = LHS.get()->getType();
12041 // Note that LHS might be a scalar because the routine calls not only in
12042 // OpenCL case.
12043 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
12044 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
12045
12046 // Note that RHS might not be a vector.
12047 QualType RHSType = RHS.get()->getType();
12048 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
12049 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
12050
12051 // Do not allow shifts for boolean vectors.
12052 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
12053 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
12054 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12055 << LHS.get()->getType() << RHS.get()->getType()
12056 << LHS.get()->getSourceRange();
12057 return QualType();
12058 }
12059
12060 // The operands need to be integers.
12061 if (!LHSEleType->isIntegerType()) {
12062 S.Diag(Loc, diag::err_typecheck_expect_int)
12063 << LHS.get()->getType() << LHS.get()->getSourceRange();
12064 return QualType();
12065 }
12066
12067 if (!RHSEleType->isIntegerType()) {
12068 S.Diag(Loc, diag::err_typecheck_expect_int)
12069 << RHS.get()->getType() << RHS.get()->getSourceRange();
12070 return QualType();
12071 }
12072
12073 if (!LHSVecTy) {
12074 assert(RHSVecTy);
12075 if (IsCompAssign)
12076 return RHSType;
12077 if (LHSEleType != RHSEleType) {
12078 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
12079 LHSEleType = RHSEleType;
12080 }
12081 QualType VecTy =
12082 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
12083 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
12084 LHSType = VecTy;
12085 } else if (RHSVecTy) {
12086 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12087 // are applied component-wise. So if RHS is a vector, then ensure
12088 // that the number of elements is the same as LHS...
12089 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
12090 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12091 << LHS.get()->getType() << RHS.get()->getType()
12092 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12093 return QualType();
12094 }
12095 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
12096 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
12097 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
12098 if (LHSBT != RHSBT &&
12099 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
12100 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
12101 << LHS.get()->getType() << RHS.get()->getType()
12102 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12103 }
12104 }
12105 } else {
12106 // ...else expand RHS to match the number of elements in LHS.
12107 QualType VecTy =
12108 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
12109 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12110 }
12111
12112 return LHSType;
12113}
12114
12116 ExprResult &RHS, SourceLocation Loc,
12117 bool IsCompAssign) {
12118 if (!IsCompAssign) {
12119 LHS = S.UsualUnaryConversions(LHS.get());
12120 if (LHS.isInvalid())
12121 return QualType();
12122 }
12123
12124 RHS = S.UsualUnaryConversions(RHS.get());
12125 if (RHS.isInvalid())
12126 return QualType();
12127
12128 QualType LHSType = LHS.get()->getType();
12129 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
12130 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
12131 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
12132 : LHSType;
12133
12134 // Note that RHS might not be a vector
12135 QualType RHSType = RHS.get()->getType();
12136 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
12137 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
12138 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
12139 : RHSType;
12140
12141 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
12142 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
12143 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12144 << LHSType << RHSType << LHS.get()->getSourceRange();
12145 return QualType();
12146 }
12147
12148 if (!LHSEleType->isIntegerType()) {
12149 S.Diag(Loc, diag::err_typecheck_expect_int)
12150 << LHS.get()->getType() << LHS.get()->getSourceRange();
12151 return QualType();
12152 }
12153
12154 if (!RHSEleType->isIntegerType()) {
12155 S.Diag(Loc, diag::err_typecheck_expect_int)
12156 << RHS.get()->getType() << RHS.get()->getSourceRange();
12157 return QualType();
12158 }
12159
12160 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
12161 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
12162 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
12163 S.Diag(Loc, diag::err_typecheck_invalid_operands)
12164 << LHSType << RHSType << LHS.get()->getSourceRange()
12165 << RHS.get()->getSourceRange();
12166 return QualType();
12167 }
12168
12169 if (!LHSType->isSveVLSBuiltinType()) {
12170 assert(RHSType->isSveVLSBuiltinType());
12171 if (IsCompAssign)
12172 return RHSType;
12173 if (LHSEleType != RHSEleType) {
12174 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
12175 LHSEleType = RHSEleType;
12176 }
12177 const llvm::ElementCount VecSize =
12178 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
12179 QualType VecTy =
12180 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
12181 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
12182 LHSType = VecTy;
12183 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
12184 if (S.Context.getTypeSize(RHSBuiltinTy) !=
12185 S.Context.getTypeSize(LHSBuiltinTy)) {
12186 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
12187 << LHSType << RHSType << LHS.get()->getSourceRange()
12188 << RHS.get()->getSourceRange();
12189 return QualType();
12190 }
12191 } else {
12192 const llvm::ElementCount VecSize =
12193 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
12194 if (LHSEleType != RHSEleType) {
12195 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
12196 RHSEleType = LHSEleType;
12197 }
12198 QualType VecTy =
12199 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
12200 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
12201 }
12202
12203 return LHSType;
12204}
12205
12206// C99 6.5.7
12209 bool IsCompAssign) {
12210 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
12211
12212 // Vector shifts promote their scalar inputs to vector type.
12213 if (LHS.get()->getType()->isVectorType() ||
12214 RHS.get()->getType()->isVectorType()) {
12215 if (LangOpts.ZVector) {
12216 // The shift operators for the z vector extensions work basically
12217 // like general shifts, except that neither the LHS nor the RHS is
12218 // allowed to be a "vector bool".
12219 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
12220 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12221 return InvalidOperands(Loc, LHS, RHS);
12222 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
12223 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
12224 return InvalidOperands(Loc, LHS, RHS);
12225 }
12226 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12227 }
12228
12229 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12230 RHS.get()->getType()->isSveVLSBuiltinType())
12231 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
12232
12233 // Shifts don't perform usual arithmetic conversions, they just do integer
12234 // promotions on each operand. C99 6.5.7p3
12235
12236 // For the LHS, do usual unary conversions, but then reset them away
12237 // if this is a compound assignment.
12238 ExprResult OldLHS = LHS;
12239 LHS = UsualUnaryConversions(LHS.get());
12240 if (LHS.isInvalid())
12241 return QualType();
12242 QualType LHSType = LHS.get()->getType();
12243 if (IsCompAssign) LHS = OldLHS;
12244
12245 // The RHS is simpler.
12246 RHS = UsualUnaryConversions(RHS.get());
12247 if (RHS.isInvalid())
12248 return QualType();
12249 QualType RHSType = RHS.get()->getType();
12250
12251 // C99 6.5.7p2: Each of the operands shall have integer type.
12252 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12253 if ((!LHSType->isFixedPointOrIntegerType() &&
12254 !LHSType->hasIntegerRepresentation()) ||
12255 !RHSType->hasIntegerRepresentation()) {
12256 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
12257 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
12258 return ResultTy;
12259 }
12260
12261 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
12262
12263 // "The type of the result is that of the promoted left operand."
12264 return LHSType;
12265}
12266
12267/// Diagnose bad pointer comparisons.
12269 ExprResult &LHS, ExprResult &RHS,
12270 bool IsError) {
12271 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
12272 : diag::ext_typecheck_comparison_of_distinct_pointers)
12273 << LHS.get()->getType() << RHS.get()->getType()
12274 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12275}
12276
12277/// Returns false if the pointers are converted to a composite type,
12278/// true otherwise.
12280 ExprResult &LHS, ExprResult &RHS) {
12281 // C++ [expr.rel]p2:
12282 // [...] Pointer conversions (4.10) and qualification
12283 // conversions (4.4) are performed on pointer operands (or on
12284 // a pointer operand and a null pointer constant) to bring
12285 // them to their composite pointer type. [...]
12286 //
12287 // C++ [expr.eq]p1 uses the same notion for (in)equality
12288 // comparisons of pointers.
12289
12290 QualType LHSType = LHS.get()->getType();
12291 QualType RHSType = RHS.get()->getType();
12292 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
12293 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
12294
12295 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
12296 if (T.isNull()) {
12297 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
12298 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
12299 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
12300 else
12301 S.InvalidOperands(Loc, LHS, RHS);
12302 return true;
12303 }
12304
12305 return false;
12306}
12307
12309 ExprResult &LHS,
12310 ExprResult &RHS,
12311 bool IsError) {
12312 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
12313 : diag::ext_typecheck_comparison_of_fptr_to_void)
12314 << LHS.get()->getType() << RHS.get()->getType()
12315 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12316}
12317
12319 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
12320 case Stmt::ObjCArrayLiteralClass:
12321 case Stmt::ObjCDictionaryLiteralClass:
12322 case Stmt::ObjCStringLiteralClass:
12323 case Stmt::ObjCBoxedExprClass:
12324 return true;
12325 default:
12326 // Note that ObjCBoolLiteral is NOT an object literal!
12327 return false;
12328 }
12329}
12330
12331static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
12334
12335 // If this is not actually an Objective-C object, bail out.
12336 if (!Type)
12337 return false;
12338
12339 // Get the LHS object's interface type.
12340 QualType InterfaceType = Type->getPointeeType();
12341
12342 // If the RHS isn't an Objective-C object, bail out.
12343 if (!RHS->getType()->isObjCObjectPointerType())
12344 return false;
12345
12346 // Try to find the -isEqual: method.
12347 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
12348 ObjCMethodDecl *Method =
12349 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
12350 /*IsInstance=*/true);
12351 if (!Method) {
12352 if (Type->isObjCIdType()) {
12353 // For 'id', just check the global pool.
12354 Method =
12356 /*receiverId=*/true);
12357 } else {
12358 // Check protocols.
12359 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
12360 /*IsInstance=*/true);
12361 }
12362 }
12363
12364 if (!Method)
12365 return false;
12366
12367 QualType T = Method->parameters()[0]->getType();
12368 if (!T->isObjCObjectPointerType())
12369 return false;
12370
12371 QualType R = Method->getReturnType();
12372 if (!R->isScalarType())
12373 return false;
12374
12375 return true;
12376}
12377
12379 ExprResult &LHS, ExprResult &RHS,
12381 Expr *Literal;
12382 Expr *Other;
12383 if (isObjCObjectLiteral(LHS)) {
12384 Literal = LHS.get();
12385 Other = RHS.get();
12386 } else {
12387 Literal = RHS.get();
12388 Other = LHS.get();
12389 }
12390
12391 // Don't warn on comparisons against nil.
12392 Other = Other->IgnoreParenCasts();
12393 if (Other->isNullPointerConstant(S.getASTContext(),
12395 return;
12396
12397 // This should be kept in sync with warn_objc_literal_comparison.
12398 // LK_String should always be after the other literals, since it has its own
12399 // warning flag.
12400 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
12401 assert(LiteralKind != SemaObjC::LK_Block);
12402 if (LiteralKind == SemaObjC::LK_None) {
12403 llvm_unreachable("Unknown Objective-C object literal kind");
12404 }
12405
12406 if (LiteralKind == SemaObjC::LK_String)
12407 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12408 << Literal->getSourceRange();
12409 else
12410 S.Diag(Loc, diag::warn_objc_literal_comparison)
12411 << LiteralKind << Literal->getSourceRange();
12412
12414 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12415 SourceLocation Start = LHS.get()->getBeginLoc();
12417 CharSourceRange OpRange =
12419
12420 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12421 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12422 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12423 << FixItHint::CreateInsertion(End, "]");
12424 }
12425}
12426
12427/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12429 ExprResult &RHS, SourceLocation Loc,
12430 BinaryOperatorKind Opc) {
12431 // Check that left hand side is !something.
12432 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12433 if (!UO || UO->getOpcode() != UO_LNot) return;
12434
12435 // Only check if the right hand side is non-bool arithmetic type.
12436 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12437
12438 // Make sure that the something in !something is not bool.
12439 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12440 if (SubExpr->isKnownToHaveBooleanValue()) return;
12441
12442 // Emit warning.
12443 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12444 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12445 << Loc << IsBitwiseOp;
12446
12447 // First note suggest !(x < y)
12448 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12449 SourceLocation FirstClose = RHS.get()->getEndLoc();
12450 FirstClose = S.getLocForEndOfToken(FirstClose);
12451 if (FirstClose.isInvalid())
12452 FirstOpen = SourceLocation();
12453 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12454 << IsBitwiseOp
12455 << FixItHint::CreateInsertion(FirstOpen, "(")
12456 << FixItHint::CreateInsertion(FirstClose, ")");
12457
12458 // Second note suggests (!x) < y
12459 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12460 SourceLocation SecondClose = LHS.get()->getEndLoc();
12461 SecondClose = S.getLocForEndOfToken(SecondClose);
12462 if (SecondClose.isInvalid())
12463 SecondOpen = SourceLocation();
12464 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12465 << FixItHint::CreateInsertion(SecondOpen, "(")
12466 << FixItHint::CreateInsertion(SecondClose, ")");
12467}
12468
12469// Returns true if E refers to a non-weak array.
12470static bool checkForArray(const Expr *E) {
12471 const ValueDecl *D = nullptr;
12472 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12473 D = DR->getDecl();
12474 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12475 if (Mem->isImplicitAccess())
12476 D = Mem->getMemberDecl();
12477 }
12478 if (!D)
12479 return false;
12480 return D->getType()->isArrayType() && !D->isWeak();
12481}
12482
12483/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
12484/// pointer and size is an unsigned integer. Return whether the result is
12485/// always true/false.
12486static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
12487 const Expr *RHS,
12488 BinaryOperatorKind Opc) {
12489 if (!LHS->getType()->isPointerType() ||
12490 S.getLangOpts().PointerOverflowDefined)
12491 return std::nullopt;
12492
12493 // Canonicalize to >= or < predicate.
12494 switch (Opc) {
12495 case BO_GE:
12496 case BO_LT:
12497 break;
12498 case BO_GT:
12499 std::swap(LHS, RHS);
12500 Opc = BO_LT;
12501 break;
12502 case BO_LE:
12503 std::swap(LHS, RHS);
12504 Opc = BO_GE;
12505 break;
12506 default:
12507 return std::nullopt;
12508 }
12509
12510 auto *BO = dyn_cast<BinaryOperator>(LHS);
12511 if (!BO || BO->getOpcode() != BO_Add)
12512 return std::nullopt;
12513
12514 Expr *Other;
12515 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
12516 Other = BO->getRHS();
12517 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
12518 Other = BO->getLHS();
12519 else
12520 return std::nullopt;
12521
12522 if (!Other->getType()->isUnsignedIntegerType())
12523 return std::nullopt;
12524
12525 return Opc == BO_GE;
12526}
12527
12528/// Diagnose some forms of syntactically-obvious tautological comparison.
12530 Expr *LHS, Expr *RHS,
12531 BinaryOperatorKind Opc) {
12532 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12533 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12534
12535 QualType LHSType = LHS->getType();
12536 QualType RHSType = RHS->getType();
12537 if (LHSType->hasFloatingRepresentation() ||
12538 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12540 return;
12541
12542 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12543 // Tautological diagnostics.
12544 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12545 return;
12546
12547 // Comparisons between two array types are ill-formed for operator<=>, so
12548 // we shouldn't emit any additional warnings about it.
12549 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12550 return;
12551
12552 // For non-floating point types, check for self-comparisons of the form
12553 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12554 // often indicate logic errors in the program.
12555 //
12556 // NOTE: Don't warn about comparison expressions resulting from macro
12557 // expansion. Also don't warn about comparisons which are only self
12558 // comparisons within a template instantiation. The warnings should catch
12559 // obvious cases in the definition of the template anyways. The idea is to
12560 // warn when the typed comparison operator will always evaluate to the same
12561 // result.
12562
12563 // Used for indexing into %select in warn_comparison_always
12564 enum {
12565 AlwaysConstant,
12566 AlwaysTrue,
12567 AlwaysFalse,
12568 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12569 };
12570
12571 // C++1a [array.comp]:
12572 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12573 // operands of array type.
12574 // C++2a [depr.array.comp]:
12575 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12576 // operands of array type are deprecated.
12577 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
12578 RHSStripped->getType()->isArrayType()) {
12579 auto IsDeprArrayComparionIgnored =
12580 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
12581 auto DiagID = S.getLangOpts().CPlusPlus26
12582 ? diag::warn_array_comparison_cxx26
12583 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
12584 ? diag::warn_array_comparison
12585 : diag::warn_depr_array_comparison;
12586 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
12587 << LHSStripped->getType() << RHSStripped->getType();
12588 // Carry on to produce the tautological comparison warning, if this
12589 // expression is potentially-evaluated, we can resolve the array to a
12590 // non-weak declaration, and so on.
12591 }
12592
12593 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12594 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12595 unsigned Result;
12596 switch (Opc) {
12597 case BO_EQ:
12598 case BO_LE:
12599 case BO_GE:
12600 Result = AlwaysTrue;
12601 break;
12602 case BO_NE:
12603 case BO_LT:
12604 case BO_GT:
12605 Result = AlwaysFalse;
12606 break;
12607 case BO_Cmp:
12608 Result = AlwaysEqual;
12609 break;
12610 default:
12611 Result = AlwaysConstant;
12612 break;
12613 }
12614 S.DiagRuntimeBehavior(Loc, nullptr,
12615 S.PDiag(diag::warn_comparison_always)
12616 << 0 /*self-comparison*/
12617 << Result);
12618 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12619 // What is it always going to evaluate to?
12620 unsigned Result;
12621 switch (Opc) {
12622 case BO_EQ: // e.g. array1 == array2
12623 Result = AlwaysFalse;
12624 break;
12625 case BO_NE: // e.g. array1 != array2
12626 Result = AlwaysTrue;
12627 break;
12628 default: // e.g. array1 <= array2
12629 // The best we can say is 'a constant'
12630 Result = AlwaysConstant;
12631 break;
12632 }
12633 S.DiagRuntimeBehavior(Loc, nullptr,
12634 S.PDiag(diag::warn_comparison_always)
12635 << 1 /*array comparison*/
12636 << Result);
12637 } else if (std::optional<bool> Res =
12638 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
12639 S.DiagRuntimeBehavior(Loc, nullptr,
12640 S.PDiag(diag::warn_comparison_always)
12641 << 2 /*pointer comparison*/
12642 << (*Res ? AlwaysTrue : AlwaysFalse));
12643 }
12644 }
12645
12646 if (isa<CastExpr>(LHSStripped))
12647 LHSStripped = LHSStripped->IgnoreParenCasts();
12648 if (isa<CastExpr>(RHSStripped))
12649 RHSStripped = RHSStripped->IgnoreParenCasts();
12650
12651 // Warn about comparisons against a string constant (unless the other
12652 // operand is null); the user probably wants string comparison function.
12653 Expr *LiteralString = nullptr;
12654 Expr *LiteralStringStripped = nullptr;
12655 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12656 !RHSStripped->isNullPointerConstant(S.Context,
12658 LiteralString = LHS;
12659 LiteralStringStripped = LHSStripped;
12660 } else if ((isa<StringLiteral>(RHSStripped) ||
12661 isa<ObjCEncodeExpr>(RHSStripped)) &&
12662 !LHSStripped->isNullPointerConstant(S.Context,
12664 LiteralString = RHS;
12665 LiteralStringStripped = RHSStripped;
12666 }
12667
12668 if (LiteralString) {
12669 S.DiagRuntimeBehavior(Loc, nullptr,
12670 S.PDiag(diag::warn_stringcompare)
12671 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12672 << LiteralString->getSourceRange());
12673 }
12674}
12675
12677 switch (CK) {
12678 default: {
12679#ifndef NDEBUG
12680 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12681 << "\n";
12682#endif
12683 llvm_unreachable("unhandled cast kind");
12684 }
12685 case CK_UserDefinedConversion:
12686 return ICK_Identity;
12687 case CK_LValueToRValue:
12688 return ICK_Lvalue_To_Rvalue;
12689 case CK_ArrayToPointerDecay:
12690 return ICK_Array_To_Pointer;
12691 case CK_FunctionToPointerDecay:
12693 case CK_IntegralCast:
12695 case CK_FloatingCast:
12697 case CK_IntegralToFloating:
12698 case CK_FloatingToIntegral:
12699 return ICK_Floating_Integral;
12700 case CK_IntegralComplexCast:
12701 case CK_FloatingComplexCast:
12702 case CK_FloatingComplexToIntegralComplex:
12703 case CK_IntegralComplexToFloatingComplex:
12705 case CK_FloatingComplexToReal:
12706 case CK_FloatingRealToComplex:
12707 case CK_IntegralComplexToReal:
12708 case CK_IntegralRealToComplex:
12709 return ICK_Complex_Real;
12710 case CK_HLSLArrayRValue:
12711 return ICK_HLSL_Array_RValue;
12712 }
12713}
12714
12716 QualType FromType,
12717 SourceLocation Loc) {
12718 // Check for a narrowing implicit conversion.
12721 SCS.setToType(0, FromType);
12722 SCS.setToType(1, ToType);
12723 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12724 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12725
12726 APValue PreNarrowingValue;
12727 QualType PreNarrowingType;
12728 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12729 PreNarrowingType,
12730 /*IgnoreFloatToIntegralConversion*/ true)) {
12732 // Implicit conversion to a narrower type, but the expression is
12733 // value-dependent so we can't tell whether it's actually narrowing.
12734 case NK_Not_Narrowing:
12735 return false;
12736
12738 // Implicit conversion to a narrower type, and the value is not a constant
12739 // expression.
12740 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12741 << /*Constant*/ 1
12742 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12743 return true;
12744
12746 // Implicit conversion to a narrower type, and the value is not a constant
12747 // expression.
12748 case NK_Type_Narrowing:
12749 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12750 << /*Constant*/ 0 << FromType << ToType;
12751 // TODO: It's not a constant expression, but what if the user intended it
12752 // to be? Can we produce notes to help them figure out why it isn't?
12753 return true;
12754 }
12755 llvm_unreachable("unhandled case in switch");
12756}
12757
12759 ExprResult &LHS,
12760 ExprResult &RHS,
12761 SourceLocation Loc) {
12762 QualType LHSType = LHS.get()->getType();
12763 QualType RHSType = RHS.get()->getType();
12764 // Dig out the original argument type and expression before implicit casts
12765 // were applied. These are the types/expressions we need to check the
12766 // [expr.spaceship] requirements against.
12767 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12768 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12769 QualType LHSStrippedType = LHSStripped.get()->getType();
12770 QualType RHSStrippedType = RHSStripped.get()->getType();
12771
12772 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12773 // other is not, the program is ill-formed.
12774 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12775 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12776 return QualType();
12777 }
12778
12779 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12780 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12781 RHSStrippedType->isEnumeralType();
12782 if (NumEnumArgs == 1) {
12783 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12784 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12785 if (OtherTy->hasFloatingRepresentation()) {
12786 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12787 return QualType();
12788 }
12789 }
12790 if (NumEnumArgs == 2) {
12791 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12792 // type E, the operator yields the result of converting the operands
12793 // to the underlying type of E and applying <=> to the converted operands.
12794 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12795 S.InvalidOperands(Loc, LHS, RHS);
12796 return QualType();
12797 }
12798 QualType IntType = LHSStrippedType->castAsEnumDecl()->getIntegerType();
12799 assert(IntType->isArithmeticType());
12800
12801 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12802 // promote the boolean type, and all other promotable integer types, to
12803 // avoid this.
12804 if (S.Context.isPromotableIntegerType(IntType))
12805 IntType = S.Context.getPromotedIntegerType(IntType);
12806
12807 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12808 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12809 LHSType = RHSType = IntType;
12810 }
12811
12812 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12813 // usual arithmetic conversions are applied to the operands.
12814 QualType Type =
12816 if (LHS.isInvalid() || RHS.isInvalid())
12817 return QualType();
12818 if (Type.isNull()) {
12819 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12820 diagnoseScopedEnums(S, Loc, LHS, RHS, BO_Cmp);
12821 return ResultTy;
12822 }
12823
12824 std::optional<ComparisonCategoryType> CCT =
12826 if (!CCT)
12827 return S.InvalidOperands(Loc, LHS, RHS);
12828
12829 bool HasNarrowing = checkThreeWayNarrowingConversion(
12830 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12831 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12832 RHS.get()->getBeginLoc());
12833 if (HasNarrowing)
12834 return QualType();
12835
12836 assert(!Type.isNull() && "composite type for <=> has not been set");
12837
12840}
12841
12843 ExprResult &RHS,
12844 SourceLocation Loc,
12845 BinaryOperatorKind Opc) {
12846 if (Opc == BO_Cmp)
12847 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12848
12849 // C99 6.5.8p3 / C99 6.5.9p4
12850 QualType Type =
12852 if (LHS.isInvalid() || RHS.isInvalid())
12853 return QualType();
12854 if (Type.isNull()) {
12855 QualType ResultTy = S.InvalidOperands(Loc, LHS, RHS);
12856 diagnoseScopedEnums(S, Loc, LHS, RHS, Opc);
12857 return ResultTy;
12858 }
12859 assert(Type->isArithmeticType() || Type->isEnumeralType());
12860
12862 return S.InvalidOperands(Loc, LHS, RHS);
12863
12864 // Check for comparisons of floating point operands using != and ==.
12866 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12867
12868 // The result of comparisons is 'bool' in C++, 'int' in C.
12870}
12871
12873 if (!NullE.get()->getType()->isAnyPointerType())
12874 return;
12875 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12876 if (!E.get()->getType()->isAnyPointerType() &&
12880 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12881 if (CL->getValue() == 0)
12882 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12883 << NullValue
12885 NullValue ? "NULL" : "(void *)0");
12886 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12887 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12888 QualType T = Context.getCanonicalType(TI->getType()).getUnqualifiedType();
12889 if (T == Context.CharTy)
12890 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12891 << NullValue
12893 NullValue ? "NULL" : "(void *)0");
12894 }
12895 }
12896}
12897
12898// C99 6.5.8, C++ [expr.rel]
12900 SourceLocation Loc,
12901 BinaryOperatorKind Opc) {
12902 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12903 bool IsThreeWay = Opc == BO_Cmp;
12904 bool IsOrdered = IsRelational || IsThreeWay;
12905 auto IsAnyPointerType = [](ExprResult E) {
12906 QualType Ty = E.get()->getType();
12907 return Ty->isPointerType() || Ty->isMemberPointerType();
12908 };
12909
12910 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12911 // type, array-to-pointer, ..., conversions are performed on both operands to
12912 // bring them to their composite type.
12913 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12914 // any type-related checks.
12915 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12917 if (LHS.isInvalid())
12918 return QualType();
12920 if (RHS.isInvalid())
12921 return QualType();
12922 } else {
12923 LHS = DefaultLvalueConversion(LHS.get());
12924 if (LHS.isInvalid())
12925 return QualType();
12926 RHS = DefaultLvalueConversion(RHS.get());
12927 if (RHS.isInvalid())
12928 return QualType();
12929 }
12930
12931 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12935 }
12936
12937 // Handle vector comparisons separately.
12938 if (LHS.get()->getType()->isVectorType() ||
12939 RHS.get()->getType()->isVectorType())
12940 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12941
12942 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12943 RHS.get()->getType()->isSveVLSBuiltinType())
12944 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12945
12946 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12947 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12948
12949 QualType LHSType = LHS.get()->getType();
12950 QualType RHSType = RHS.get()->getType();
12951 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12952 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12953 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12954
12955 if ((LHSType->isPointerType() &&
12957 (RHSType->isPointerType() &&
12959 return InvalidOperands(Loc, LHS, RHS);
12960
12961 const Expr::NullPointerConstantKind LHSNullKind =
12963 const Expr::NullPointerConstantKind RHSNullKind =
12965 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12966 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12967
12968 auto computeResultTy = [&]() {
12969 if (Opc != BO_Cmp)
12970 return QualType(Context.getLogicalOperationType());
12971 assert(getLangOpts().CPlusPlus);
12972 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12973
12974 QualType CompositeTy = LHS.get()->getType();
12975 assert(!CompositeTy->isReferenceType());
12976
12977 std::optional<ComparisonCategoryType> CCT =
12979 if (!CCT)
12980 return InvalidOperands(Loc, LHS, RHS);
12981
12982 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12983 // P0946R0: Comparisons between a null pointer constant and an object
12984 // pointer result in std::strong_equality, which is ill-formed under
12985 // P1959R0.
12986 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12987 << (LHSIsNull ? LHS.get()->getSourceRange()
12988 : RHS.get()->getSourceRange());
12989 return QualType();
12990 }
12991
12994 };
12995
12996 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12997 bool IsEquality = Opc == BO_EQ;
12998 if (RHSIsNull)
12999 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
13000 RHS.get()->getSourceRange());
13001 else
13002 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
13003 LHS.get()->getSourceRange());
13004 }
13005
13006 if (IsOrdered && LHSType->isFunctionPointerType() &&
13007 RHSType->isFunctionPointerType()) {
13008 // Valid unless a relational comparison of function pointers
13009 bool IsError = Opc == BO_Cmp;
13010 auto DiagID =
13011 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
13012 : getLangOpts().CPlusPlus
13013 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13014 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
13015 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
13016 << RHS.get()->getSourceRange();
13017 if (IsError)
13018 return QualType();
13019 }
13020
13021 if ((LHSType->isIntegerType() && !LHSIsNull) ||
13022 (RHSType->isIntegerType() && !RHSIsNull)) {
13023 // Skip normal pointer conversion checks in this case; we have better
13024 // diagnostics for this below.
13025 } else if (getLangOpts().CPlusPlus) {
13026 // Equality comparison of a function pointer to a void pointer is invalid,
13027 // but we allow it as an extension.
13028 // FIXME: If we really want to allow this, should it be part of composite
13029 // pointer type computation so it works in conditionals too?
13030 if (!IsOrdered &&
13031 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
13032 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
13033 // This is a gcc extension compatibility comparison.
13034 // In a SFINAE context, we treat this as a hard error to maintain
13035 // conformance with the C++ standard.
13036 bool IsError = isSFINAEContext();
13037 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS, IsError);
13038
13039 if (IsError)
13040 return QualType();
13041
13042 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13043 return computeResultTy();
13044 }
13045
13046 // C++ [expr.eq]p2:
13047 // If at least one operand is a pointer [...] bring them to their
13048 // composite pointer type.
13049 // C++ [expr.spaceship]p6
13050 // If at least one of the operands is of pointer type, [...] bring them
13051 // to their composite pointer type.
13052 // C++ [expr.rel]p2:
13053 // If both operands are pointers, [...] bring them to their composite
13054 // pointer type.
13055 // For <=>, the only valid non-pointer types are arrays and functions, and
13056 // we already decayed those, so this is really the same as the relational
13057 // comparison rule.
13058 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
13059 (IsOrdered ? 2 : 1) &&
13060 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
13061 RHSType->isObjCObjectPointerType()))) {
13062 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13063 return QualType();
13064 return computeResultTy();
13065 }
13066 } else if (LHSType->isPointerType() &&
13067 RHSType->isPointerType()) { // C99 6.5.8p2
13068 // All of the following pointer-related warnings are GCC extensions, except
13069 // when handling null pointer constants.
13070 QualType LCanPointeeTy =
13072 QualType RCanPointeeTy =
13074
13075 // C99 6.5.9p2 and C99 6.5.8p2
13076 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
13077 RCanPointeeTy.getUnqualifiedType())) {
13078 if (IsRelational) {
13079 // Pointers both need to point to complete or incomplete types
13080 if ((LCanPointeeTy->isIncompleteType() !=
13081 RCanPointeeTy->isIncompleteType()) &&
13082 !getLangOpts().C11) {
13083 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
13084 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
13085 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
13086 << RCanPointeeTy->isIncompleteType();
13087 }
13088 }
13089 } else if (!IsRelational &&
13090 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
13091 // Valid unless comparison between non-null pointer and function pointer
13092 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
13093 && !LHSIsNull && !RHSIsNull)
13094 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
13095 /*isError*/false);
13096 } else {
13097 // Invalid
13098 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
13099 }
13100 if (LCanPointeeTy != RCanPointeeTy) {
13101 // Treat NULL constant as a special case in OpenCL.
13102 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
13103 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
13104 getASTContext())) {
13105 Diag(Loc,
13106 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
13107 << LHSType << RHSType << 0 /* comparison */
13108 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
13109 }
13110 }
13111 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
13112 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
13113 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
13114 : CK_BitCast;
13115
13116 const FunctionType *LFn = LCanPointeeTy->getAs<FunctionType>();
13117 const FunctionType *RFn = RCanPointeeTy->getAs<FunctionType>();
13118 bool LHSHasCFIUncheckedCallee = LFn && LFn->getCFIUncheckedCalleeAttr();
13119 bool RHSHasCFIUncheckedCallee = RFn && RFn->getCFIUncheckedCalleeAttr();
13120 bool ChangingCFIUncheckedCallee =
13121 LHSHasCFIUncheckedCallee != RHSHasCFIUncheckedCallee;
13122
13123 if (LHSIsNull && !RHSIsNull)
13124 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
13125 else if (!ChangingCFIUncheckedCallee)
13126 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
13127 }
13128 return computeResultTy();
13129 }
13130
13131
13132 // C++ [expr.eq]p4:
13133 // Two operands of type std::nullptr_t or one operand of type
13134 // std::nullptr_t and the other a null pointer constant compare
13135 // equal.
13136 // C23 6.5.9p5:
13137 // If both operands have type nullptr_t or one operand has type nullptr_t
13138 // and the other is a null pointer constant, they compare equal if the
13139 // former is a null pointer.
13140 if (!IsOrdered && LHSIsNull && RHSIsNull) {
13141 if (LHSType->isNullPtrType()) {
13142 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13143 return computeResultTy();
13144 }
13145 if (RHSType->isNullPtrType()) {
13146 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13147 return computeResultTy();
13148 }
13149 }
13150
13151 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
13152 // C23 6.5.9p6:
13153 // Otherwise, at least one operand is a pointer. If one is a pointer and
13154 // the other is a null pointer constant or has type nullptr_t, they
13155 // compare equal
13156 if (LHSIsNull && RHSType->isPointerType()) {
13157 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13158 return computeResultTy();
13159 }
13160 if (RHSIsNull && LHSType->isPointerType()) {
13161 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13162 return computeResultTy();
13163 }
13164 }
13165
13166 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13167 // These aren't covered by the composite pointer type rules.
13168 if (!IsOrdered && RHSType->isNullPtrType() &&
13169 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
13170 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13171 return computeResultTy();
13172 }
13173 if (!IsOrdered && LHSType->isNullPtrType() &&
13174 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
13175 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13176 return computeResultTy();
13177 }
13178
13179 if (getLangOpts().CPlusPlus) {
13180 if (IsRelational &&
13181 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
13182 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
13183 // HACK: Relational comparison of nullptr_t against a pointer type is
13184 // invalid per DR583, but we allow it within std::less<> and friends,
13185 // since otherwise common uses of it break.
13186 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13187 // friends to have std::nullptr_t overload candidates.
13188 DeclContext *DC = CurContext;
13189 if (isa<FunctionDecl>(DC))
13190 DC = DC->getParent();
13191 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
13192 if (CTSD->isInStdNamespace() &&
13193 llvm::StringSwitch<bool>(CTSD->getName())
13194 .Cases({"less", "less_equal", "greater", "greater_equal"}, true)
13195 .Default(false)) {
13196 if (RHSType->isNullPtrType())
13197 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13198 else
13199 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13200 return computeResultTy();
13201 }
13202 }
13203 }
13204
13205 // C++ [expr.eq]p2:
13206 // If at least one operand is a pointer to member, [...] bring them to
13207 // their composite pointer type.
13208 if (!IsOrdered &&
13209 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
13210 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
13211 return QualType();
13212 else
13213 return computeResultTy();
13214 }
13215 }
13216
13217 // Handle block pointer types.
13218 if (!IsOrdered && LHSType->isBlockPointerType() &&
13219 RHSType->isBlockPointerType()) {
13220 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
13221 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
13222
13223 if (!LHSIsNull && !RHSIsNull &&
13224 !Context.typesAreCompatible(lpointee, rpointee)) {
13225 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13226 << LHSType << RHSType << LHS.get()->getSourceRange()
13227 << RHS.get()->getSourceRange();
13228 }
13229 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13230 return computeResultTy();
13231 }
13232
13233 // Allow block pointers to be compared with null pointer constants.
13234 if (!IsOrdered
13235 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
13236 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
13237 if (!LHSIsNull && !RHSIsNull) {
13238 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
13240 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
13241 ->getPointeeType()->isVoidType())))
13242 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
13243 << LHSType << RHSType << LHS.get()->getSourceRange()
13244 << RHS.get()->getSourceRange();
13245 }
13246 if (LHSIsNull && !RHSIsNull)
13247 LHS = ImpCastExprToType(LHS.get(), RHSType,
13248 RHSType->isPointerType() ? CK_BitCast
13249 : CK_AnyPointerToBlockPointerCast);
13250 else
13251 RHS = ImpCastExprToType(RHS.get(), LHSType,
13252 LHSType->isPointerType() ? CK_BitCast
13253 : CK_AnyPointerToBlockPointerCast);
13254 return computeResultTy();
13255 }
13256
13257 if (LHSType->isObjCObjectPointerType() ||
13258 RHSType->isObjCObjectPointerType()) {
13259 const PointerType *LPT = LHSType->getAs<PointerType>();
13260 const PointerType *RPT = RHSType->getAs<PointerType>();
13261 if (LPT || RPT) {
13262 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
13263 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
13264
13265 if (!LPtrToVoid && !RPtrToVoid &&
13266 !Context.typesAreCompatible(LHSType, RHSType)) {
13267 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13268 /*isError*/false);
13269 }
13270 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13271 // the RHS, but we have test coverage for this behavior.
13272 // FIXME: Consider using convertPointersToCompositeType in C++.
13273 if (LHSIsNull && !RHSIsNull) {
13274 Expr *E = LHS.get();
13275 if (getLangOpts().ObjCAutoRefCount)
13276 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
13278 LHS = ImpCastExprToType(E, RHSType,
13279 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13280 }
13281 else {
13282 Expr *E = RHS.get();
13283 if (getLangOpts().ObjCAutoRefCount)
13284 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
13286 /*Diagnose=*/true,
13287 /*DiagnoseCFAudited=*/false, Opc);
13288 RHS = ImpCastExprToType(E, LHSType,
13289 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
13290 }
13291 return computeResultTy();
13292 }
13293 if (LHSType->isObjCObjectPointerType() &&
13294 RHSType->isObjCObjectPointerType()) {
13295 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
13296 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
13297 /*isError*/false);
13299 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
13300
13301 if (LHSIsNull && !RHSIsNull)
13302 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
13303 else
13304 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
13305 return computeResultTy();
13306 }
13307
13308 if (!IsOrdered && LHSType->isBlockPointerType() &&
13310 LHS = ImpCastExprToType(LHS.get(), RHSType,
13311 CK_BlockPointerToObjCPointerCast);
13312 return computeResultTy();
13313 } else if (!IsOrdered &&
13315 RHSType->isBlockPointerType()) {
13316 RHS = ImpCastExprToType(RHS.get(), LHSType,
13317 CK_BlockPointerToObjCPointerCast);
13318 return computeResultTy();
13319 }
13320 }
13321 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
13322 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
13323 unsigned DiagID = 0;
13324 bool isError = false;
13325 if (LangOpts.DebuggerSupport) {
13326 // Under a debugger, allow the comparison of pointers to integers,
13327 // since users tend to want to compare addresses.
13328 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
13329 (RHSIsNull && RHSType->isIntegerType())) {
13330 if (IsOrdered) {
13331 isError = getLangOpts().CPlusPlus;
13332 DiagID =
13333 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13334 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
13335 }
13336 } else if (getLangOpts().CPlusPlus) {
13337 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
13338 isError = true;
13339 } else if (IsOrdered)
13340 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
13341 else
13342 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
13343
13344 if (DiagID) {
13345 Diag(Loc, DiagID)
13346 << LHSType << RHSType << LHS.get()->getSourceRange()
13347 << RHS.get()->getSourceRange();
13348 if (isError)
13349 return QualType();
13350 }
13351
13352 if (LHSType->isIntegerType())
13353 LHS = ImpCastExprToType(LHS.get(), RHSType,
13354 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13355 else
13356 RHS = ImpCastExprToType(RHS.get(), LHSType,
13357 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
13358 return computeResultTy();
13359 }
13360
13361 // Handle block pointers.
13362 if (!IsOrdered && RHSIsNull
13363 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
13364 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13365 return computeResultTy();
13366 }
13367 if (!IsOrdered && LHSIsNull
13368 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
13369 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13370 return computeResultTy();
13371 }
13372
13373 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13374 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
13375 return computeResultTy();
13376 }
13377
13378 if (LHSType->isQueueT() && RHSType->isQueueT()) {
13379 return computeResultTy();
13380 }
13381
13382 if (LHSIsNull && RHSType->isQueueT()) {
13383 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
13384 return computeResultTy();
13385 }
13386
13387 if (LHSType->isQueueT() && RHSIsNull) {
13388 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13389 return computeResultTy();
13390 }
13391 }
13392
13393 return InvalidOperands(Loc, LHS, RHS);
13394}
13395
13397 const VectorType *VTy = V->castAs<VectorType>();
13398 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13399
13400 if (isa<ExtVectorType>(VTy)) {
13401 if (VTy->isExtVectorBoolType())
13402 return Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
13403 if (TypeSize == Context.getTypeSize(Context.CharTy))
13404 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
13405 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13406 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
13407 if (TypeSize == Context.getTypeSize(Context.IntTy))
13408 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
13409 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13410 return Context.getExtVectorType(Context.Int128Ty, VTy->getNumElements());
13411 if (TypeSize == Context.getTypeSize(Context.LongTy))
13412 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
13413 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13414 "Unhandled vector element size in vector compare");
13415 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
13416 }
13417
13418 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13419 return Context.getVectorType(Context.Int128Ty, VTy->getNumElements(),
13421 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13422 return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
13424 if (TypeSize == Context.getTypeSize(Context.LongTy))
13425 return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
13427 if (TypeSize == Context.getTypeSize(Context.IntTy))
13428 return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
13430 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13431 return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
13433 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13434 "Unhandled vector element size in vector compare");
13435 return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
13437}
13438
13440 const BuiltinType *VTy = V->castAs<BuiltinType>();
13441 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13442
13443 const QualType ETy = V->getSveEltType(Context);
13444 const auto TypeSize = Context.getTypeSize(ETy);
13445
13446 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13447 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13448 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13449}
13450
13452 SourceLocation Loc,
13453 BinaryOperatorKind Opc) {
13454 if (Opc == BO_Cmp) {
13455 Diag(Loc, diag::err_three_way_vector_comparison);
13456 return QualType();
13457 }
13458
13459 // Check to make sure we're operating on vectors of the same type and width,
13460 // Allowing one side to be a scalar of element type.
13461 QualType vType =
13462 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13463 /*AllowBothBool*/ true,
13464 /*AllowBoolConversions*/ getLangOpts().ZVector,
13465 /*AllowBooleanOperation*/ true,
13466 /*ReportInvalid*/ true);
13467 if (vType.isNull())
13468 return vType;
13469
13470 QualType LHSType = LHS.get()->getType();
13471
13472 // Determine the return type of a vector compare. By default clang will return
13473 // a scalar for all vector compares except vector bool and vector pixel.
13474 // With the gcc compiler we will always return a vector type and with the xl
13475 // compiler we will always return a scalar type. This switch allows choosing
13476 // which behavior is prefered.
13477 if (getLangOpts().AltiVec) {
13478 switch (getLangOpts().getAltivecSrcCompat()) {
13480 // If AltiVec, the comparison results in a numeric type, i.e.
13481 // bool for C++, int for C
13482 if (vType->castAs<VectorType>()->getVectorKind() ==
13484 return Context.getLogicalOperationType();
13485 else
13486 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13487 break;
13489 // For GCC we always return the vector type.
13490 break;
13492 return Context.getLogicalOperationType();
13493 break;
13494 }
13495 }
13496
13497 // For non-floating point types, check for self-comparisons of the form
13498 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13499 // often indicate logic errors in the program.
13500 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13501
13502 // Check for comparisons of floating point operands using != and ==.
13503 if (LHSType->hasFloatingRepresentation()) {
13504 assert(RHS.get()->getType()->hasFloatingRepresentation());
13505 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13506 }
13507
13508 // Return a signed type for the vector.
13509 return GetSignedVectorType(vType);
13510}
13511
13513 ExprResult &RHS,
13514 SourceLocation Loc,
13515 BinaryOperatorKind Opc) {
13516 if (Opc == BO_Cmp) {
13517 Diag(Loc, diag::err_three_way_vector_comparison);
13518 return QualType();
13519 }
13520
13521 // Check to make sure we're operating on vectors of the same type and width,
13522 // Allowing one side to be a scalar of element type.
13524 LHS, RHS, Loc, /*isCompAssign*/ false, ArithConvKind::Comparison);
13525
13526 if (vType.isNull())
13527 return vType;
13528
13529 QualType LHSType = LHS.get()->getType();
13530
13531 // For non-floating point types, check for self-comparisons of the form
13532 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13533 // often indicate logic errors in the program.
13534 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13535
13536 // Check for comparisons of floating point operands using != and ==.
13537 if (LHSType->hasFloatingRepresentation()) {
13538 assert(RHS.get()->getType()->hasFloatingRepresentation());
13539 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13540 }
13541
13542 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13543 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13544
13545 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13546 RHSBuiltinTy->isSVEBool())
13547 return LHSType;
13548
13549 // Return a signed type for the vector.
13550 return GetSignedSizelessVectorType(vType);
13551}
13552
13553static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13554 const ExprResult &XorRHS,
13555 const SourceLocation Loc) {
13556 // Do not diagnose macros.
13557 if (Loc.isMacroID())
13558 return;
13559
13560 // Do not diagnose if both LHS and RHS are macros.
13561 if (XorLHS.get()->getExprLoc().isMacroID() &&
13562 XorRHS.get()->getExprLoc().isMacroID())
13563 return;
13564
13565 bool Negative = false;
13566 bool ExplicitPlus = false;
13567 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13568 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13569
13570 if (!LHSInt)
13571 return;
13572 if (!RHSInt) {
13573 // Check negative literals.
13574 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13575 UnaryOperatorKind Opc = UO->getOpcode();
13576 if (Opc != UO_Minus && Opc != UO_Plus)
13577 return;
13578 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13579 if (!RHSInt)
13580 return;
13581 Negative = (Opc == UO_Minus);
13582 ExplicitPlus = !Negative;
13583 } else {
13584 return;
13585 }
13586 }
13587
13588 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13589 llvm::APInt RightSideValue = RHSInt->getValue();
13590 if (LeftSideValue != 2 && LeftSideValue != 10)
13591 return;
13592
13593 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13594 return;
13595
13597 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13598 llvm::StringRef ExprStr =
13600
13601 CharSourceRange XorRange =
13603 llvm::StringRef XorStr =
13605 // Do not diagnose if xor keyword/macro is used.
13606 if (XorStr == "xor")
13607 return;
13608
13609 std::string LHSStr = std::string(Lexer::getSourceText(
13610 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13611 S.getSourceManager(), S.getLangOpts()));
13612 std::string RHSStr = std::string(Lexer::getSourceText(
13613 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13614 S.getSourceManager(), S.getLangOpts()));
13615
13616 if (Negative) {
13617 RightSideValue = -RightSideValue;
13618 RHSStr = "-" + RHSStr;
13619 } else if (ExplicitPlus) {
13620 RHSStr = "+" + RHSStr;
13621 }
13622
13623 StringRef LHSStrRef = LHSStr;
13624 StringRef RHSStrRef = RHSStr;
13625 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13626 // literals.
13627 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13628 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13629 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13630 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13631 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13632 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13633 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13634 return;
13635
13636 bool SuggestXor =
13637 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13638 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13639 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13640 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13641 std::string SuggestedExpr = "1 << " + RHSStr;
13642 bool Overflow = false;
13643 llvm::APInt One = (LeftSideValue - 1);
13644 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13645 if (Overflow) {
13646 if (RightSideIntValue < 64)
13647 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13648 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13649 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13650 else if (RightSideIntValue == 64)
13651 S.Diag(Loc, diag::warn_xor_used_as_pow)
13652 << ExprStr << toString(XorValue, 10, true);
13653 else
13654 return;
13655 } else {
13656 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13657 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13658 << toString(PowValue, 10, true)
13660 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13661 }
13662
13663 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13664 << ("0x2 ^ " + RHSStr) << SuggestXor;
13665 } else if (LeftSideValue == 10) {
13666 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13667 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13668 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13669 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13670 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13671 << ("0xA ^ " + RHSStr) << SuggestXor;
13672 }
13673}
13674
13676 SourceLocation Loc,
13677 BinaryOperatorKind Opc) {
13678 // Ensure that either both operands are of the same vector type, or
13679 // one operand is of a vector type and the other is of its element type.
13680 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13681 /*AllowBothBool*/ true,
13682 /*AllowBoolConversions*/ false,
13683 /*AllowBooleanOperation*/ false,
13684 /*ReportInvalid*/ false);
13685 if (vType.isNull())
13686 return InvalidOperands(Loc, LHS, RHS);
13687 if (getLangOpts().OpenCL &&
13688 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13690 return InvalidOperands(Loc, LHS, RHS);
13691 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13692 // usage of the logical operators && and || with vectors in C. This
13693 // check could be notionally dropped.
13694 if (!getLangOpts().CPlusPlus &&
13695 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13696 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13697 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13698 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13699 // `select` functions.
13700 if (getLangOpts().HLSL &&
13701 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13702 (void)InvalidOperands(Loc, LHS, RHS);
13703 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13704 return QualType();
13705 }
13706
13707 return GetSignedVectorType(LHS.get()->getType());
13708}
13709
13711 SourceLocation Loc,
13712 BinaryOperatorKind Opc) {
13713
13714 if (!getLangOpts().HLSL) {
13715 assert(false && "Logical operands are not supported in C\\C++");
13716 return QualType();
13717 }
13718
13719 if (getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13720 (void)InvalidOperands(Loc, LHS, RHS);
13721 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13722 return QualType();
13723 }
13724 SemaRef.Diag(LHS.get()->getBeginLoc(), diag::err_hlsl_langstd_unimplemented)
13725 << getLangOpts().getHLSLVersion();
13726 return QualType();
13727}
13728
13730 SourceLocation Loc,
13731 bool IsCompAssign) {
13732 if (!IsCompAssign) {
13734 if (LHS.isInvalid())
13735 return QualType();
13736 }
13738 if (RHS.isInvalid())
13739 return QualType();
13740
13741 // For conversion purposes, we ignore any qualifiers.
13742 // For example, "const float" and "float" are equivalent.
13743 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13744 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13745
13746 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13747 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13748 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13749
13750 if (Context.hasSameType(LHSType, RHSType))
13751 return Context.getCommonSugaredType(LHSType, RHSType);
13752
13753 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13754 // case we have to return InvalidOperands.
13755 ExprResult OriginalLHS = LHS;
13756 ExprResult OriginalRHS = RHS;
13757 if (LHSMatType && !RHSMatType) {
13758 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13759 if (!RHS.isInvalid())
13760 return LHSType;
13761
13762 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13763 }
13764
13765 if (!LHSMatType && RHSMatType) {
13766 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13767 if (!LHS.isInvalid())
13768 return RHSType;
13769 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13770 }
13771
13772 return InvalidOperands(Loc, LHS, RHS);
13773}
13774
13776 SourceLocation Loc,
13777 bool IsCompAssign) {
13778 if (!IsCompAssign) {
13780 if (LHS.isInvalid())
13781 return QualType();
13782 }
13784 if (RHS.isInvalid())
13785 return QualType();
13786
13787 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13788 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13789 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13790
13791 if (LHSMatType && RHSMatType) {
13792 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13793 return InvalidOperands(Loc, LHS, RHS);
13794
13795 if (Context.hasSameType(LHSMatType, RHSMatType))
13796 return Context.getCommonSugaredType(
13797 LHS.get()->getType().getUnqualifiedType(),
13798 RHS.get()->getType().getUnqualifiedType());
13799
13800 QualType LHSELTy = LHSMatType->getElementType(),
13801 RHSELTy = RHSMatType->getElementType();
13802 if (!Context.hasSameType(LHSELTy, RHSELTy))
13803 return InvalidOperands(Loc, LHS, RHS);
13804
13805 return Context.getConstantMatrixType(
13806 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13807 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13808 }
13809 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13810}
13811
13813 switch (Opc) {
13814 default:
13815 return false;
13816 case BO_And:
13817 case BO_AndAssign:
13818 case BO_Or:
13819 case BO_OrAssign:
13820 case BO_Xor:
13821 case BO_XorAssign:
13822 return true;
13823 }
13824}
13825
13827 SourceLocation Loc,
13828 BinaryOperatorKind Opc) {
13829 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13830
13831 bool IsCompAssign =
13832 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13833
13834 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13835
13836 if (LHS.get()->getType()->isVectorType() ||
13837 RHS.get()->getType()->isVectorType()) {
13838 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13840 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13841 /*AllowBothBool*/ true,
13842 /*AllowBoolConversions*/ getLangOpts().ZVector,
13843 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13844 /*ReportInvalid*/ true);
13845 return InvalidOperands(Loc, LHS, RHS);
13846 }
13847
13848 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13849 RHS.get()->getType()->isSveVLSBuiltinType()) {
13850 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13852 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13854 return InvalidOperands(Loc, LHS, RHS);
13855 }
13856
13857 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13858 RHS.get()->getType()->isSveVLSBuiltinType()) {
13859 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13861 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13863 return InvalidOperands(Loc, LHS, RHS);
13864 }
13865
13866 if (Opc == BO_And)
13867 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13868
13869 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13871 return InvalidOperands(Loc, LHS, RHS);
13872
13873 ExprResult LHSResult = LHS, RHSResult = RHS;
13875 LHSResult, RHSResult, Loc,
13877 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13878 return QualType();
13879 LHS = LHSResult.get();
13880 RHS = RHSResult.get();
13881
13882 if (Opc == BO_Xor)
13883 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13884
13885 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13886 return compType;
13887 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
13888 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
13889 return ResultTy;
13890}
13891
13892// C99 6.5.[13,14]
13894 SourceLocation Loc,
13895 BinaryOperatorKind Opc) {
13896 // Check vector operands differently.
13897 if (LHS.get()->getType()->isVectorType() ||
13898 RHS.get()->getType()->isVectorType())
13899 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13900
13901 if (LHS.get()->getType()->isConstantMatrixType() ||
13902 RHS.get()->getType()->isConstantMatrixType())
13903 return CheckMatrixLogicalOperands(LHS, RHS, Loc, Opc);
13904
13905 bool EnumConstantInBoolContext = false;
13906 for (const ExprResult &HS : {LHS, RHS}) {
13907 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13908 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13909 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13910 EnumConstantInBoolContext = true;
13911 }
13912 }
13913
13914 if (EnumConstantInBoolContext)
13915 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13916
13917 // WebAssembly tables can't be used with logical operators.
13918 QualType LHSTy = LHS.get()->getType();
13919 QualType RHSTy = RHS.get()->getType();
13920 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13921 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13922 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13923 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13924 return InvalidOperands(Loc, LHS, RHS);
13925 }
13926
13927 // Diagnose cases where the user write a logical and/or but probably meant a
13928 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13929 // is a constant.
13930 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13931 !LHS.get()->getType()->isBooleanType() &&
13932 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13933 // Don't warn in macros or template instantiations.
13934 !Loc.isMacroID() && !inTemplateInstantiation()) {
13935 // If the RHS can be constant folded, and if it constant folds to something
13936 // that isn't 0 or 1 (which indicate a potential logical operation that
13937 // happened to fold to true/false) then warn.
13938 // Parens on the RHS are ignored.
13939 Expr::EvalResult EVResult;
13940 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13941 llvm::APSInt Result = EVResult.Val.getInt();
13942 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13943 !RHS.get()->getExprLoc().isMacroID()) ||
13944 (Result != 0 && Result != 1)) {
13945 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13946 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13947 // Suggest replacing the logical operator with the bitwise version
13948 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13949 << (Opc == BO_LAnd ? "&" : "|")
13952 Opc == BO_LAnd ? "&" : "|");
13953 if (Opc == BO_LAnd)
13954 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13955 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13958 RHS.get()->getEndLoc()));
13959 }
13960 }
13961 }
13962
13963 if (!Context.getLangOpts().CPlusPlus) {
13964 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13965 // not operate on the built-in scalar and vector float types.
13966 if (Context.getLangOpts().OpenCL &&
13967 Context.getLangOpts().OpenCLVersion < 120) {
13968 if (LHS.get()->getType()->isFloatingType() ||
13969 RHS.get()->getType()->isFloatingType())
13970 return InvalidOperands(Loc, LHS, RHS);
13971 }
13972
13973 LHS = UsualUnaryConversions(LHS.get());
13974 if (LHS.isInvalid())
13975 return QualType();
13976
13977 RHS = UsualUnaryConversions(RHS.get());
13978 if (RHS.isInvalid())
13979 return QualType();
13980
13981 if (LHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
13983 if (RHS.get()->getType() == Context.AMDGPUFeaturePredicateTy)
13985
13986 if (!LHS.get()->getType()->isScalarType() ||
13987 !RHS.get()->getType()->isScalarType())
13988 return InvalidOperands(Loc, LHS, RHS);
13989
13990 return Context.IntTy;
13991 }
13992
13993 // The following is safe because we only use this method for
13994 // non-overloadable operands.
13995
13996 // C++ [expr.log.and]p1
13997 // C++ [expr.log.or]p1
13998 // The operands are both contextually converted to type bool.
14000 if (LHSRes.isInvalid()) {
14001 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14002 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
14003 return ResultTy;
14004 }
14005 LHS = LHSRes;
14006
14008 if (RHSRes.isInvalid()) {
14009 QualType ResultTy = InvalidOperands(Loc, LHS, RHS);
14010 diagnoseScopedEnums(*this, Loc, LHS, RHS, Opc);
14011 return ResultTy;
14012 }
14013 RHS = RHSRes;
14014
14015 // C++ [expr.log.and]p2
14016 // C++ [expr.log.or]p2
14017 // The result is a bool.
14018 return Context.BoolTy;
14019}
14020
14021static bool IsReadonlyMessage(Expr *E, Sema &S) {
14022 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14023 if (!ME) return false;
14024 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
14025 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
14027 if (!Base) return false;
14028 return Base->getMethodDecl() != nullptr;
14029}
14030
14031/// Is the given expression (which must be 'const') a reference to a
14032/// variable which was originally non-const, but which has become
14033/// 'const' due to being captured within a block?
14036 assert(E->isLValue() && E->getType().isConstQualified());
14037 E = E->IgnoreParens();
14038
14039 // Must be a reference to a declaration from an enclosing scope.
14040 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14041 if (!DRE) return NCCK_None;
14043
14044 ValueDecl *Value = DRE->getDecl();
14045
14046 // The declaration must be a value which is not declared 'const'.
14048 return NCCK_None;
14049
14050 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
14051 if (Binding) {
14052 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
14053 assert(!isa<BlockDecl>(Binding->getDeclContext()));
14054 return NCCK_Lambda;
14055 }
14056
14057 VarDecl *Var = dyn_cast<VarDecl>(Value);
14058 if (!Var)
14059 return NCCK_None;
14060 if (Var->getType()->isReferenceType())
14061 return NCCK_None;
14062
14063 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
14064
14065 // Decide whether the first capture was for a block or a lambda.
14066 DeclContext *DC = S.CurContext, *Prev = nullptr;
14067 // Decide whether the first capture was for a block or a lambda.
14068 while (DC) {
14069 // For init-capture, it is possible that the variable belongs to the
14070 // template pattern of the current context.
14071 if (auto *FD = dyn_cast<FunctionDecl>(DC))
14072 if (Var->isInitCapture() &&
14073 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
14074 break;
14075 if (DC == Var->getDeclContext())
14076 break;
14077 Prev = DC;
14078 DC = DC->getParent();
14079 }
14080 // Unless we have an init-capture, we've gone one step too far.
14081 if (!Var->isInitCapture())
14082 DC = Prev;
14083 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
14084}
14085
14086static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
14087 Ty = Ty.getNonReferenceType();
14088 if (IsDereference && Ty->isPointerType())
14089 Ty = Ty->getPointeeType();
14090 return !Ty.isConstQualified();
14091}
14092
14093// Update err_typecheck_assign_const and note_typecheck_assign_const
14094// when this enum is changed.
14095enum {
14100 ConstUnknown, // Keep as last element
14101};
14102
14103/// Emit the "read-only variable not assignable" error and print notes to give
14104/// more information about why the variable is not assignable, such as pointing
14105/// to the declaration of a const variable, showing that a method is const, or
14106/// that the function is returning a const reference.
14107static void DiagnoseConstAssignment(Sema &S, const Expr *E,
14108 SourceLocation Loc) {
14109 SourceRange ExprRange = E->getSourceRange();
14110
14111 // Only emit one error on the first const found. All other consts will emit
14112 // a note to the error.
14113 bool DiagnosticEmitted = false;
14114
14115 // Track if the current expression is the result of a dereference, and if the
14116 // next checked expression is the result of a dereference.
14117 bool IsDereference = false;
14118 bool NextIsDereference = false;
14119
14120 // Loop to process MemberExpr chains.
14121 while (true) {
14122 IsDereference = NextIsDereference;
14123
14125 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14126 NextIsDereference = ME->isArrow();
14127 const ValueDecl *VD = ME->getMemberDecl();
14128 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
14129 // Mutable fields can be modified even if the class is const.
14130 if (Field->isMutable()) {
14131 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
14132 break;
14133 }
14134
14135 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
14136 if (!DiagnosticEmitted) {
14137 S.Diag(Loc, diag::err_typecheck_assign_const)
14138 << ExprRange << ConstMember << false /*static*/ << Field
14139 << Field->getType();
14140 DiagnosticEmitted = true;
14141 }
14142 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14143 << ConstMember << false /*static*/ << Field << Field->getType()
14144 << Field->getSourceRange();
14145 }
14146 E = ME->getBase();
14147 continue;
14148 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
14149 if (VDecl->getType().isConstQualified()) {
14150 if (!DiagnosticEmitted) {
14151 S.Diag(Loc, diag::err_typecheck_assign_const)
14152 << ExprRange << ConstMember << true /*static*/ << VDecl
14153 << VDecl->getType();
14154 DiagnosticEmitted = true;
14155 }
14156 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14157 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
14158 << VDecl->getSourceRange();
14159 }
14160 // Static fields do not inherit constness from parents.
14161 break;
14162 }
14163 break; // End MemberExpr
14164 } else if (const ArraySubscriptExpr *ASE =
14165 dyn_cast<ArraySubscriptExpr>(E)) {
14166 E = ASE->getBase()->IgnoreParenImpCasts();
14167 continue;
14168 } else if (const ExtVectorElementExpr *EVE =
14169 dyn_cast<ExtVectorElementExpr>(E)) {
14170 E = EVE->getBase()->IgnoreParenImpCasts();
14171 continue;
14172 }
14173 break;
14174 }
14175
14176 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
14177 // Function calls
14178 const FunctionDecl *FD = CE->getDirectCallee();
14179 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
14180 if (!DiagnosticEmitted) {
14181 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
14182 << ConstFunction << FD;
14183 DiagnosticEmitted = true;
14184 }
14186 diag::note_typecheck_assign_const)
14187 << ConstFunction << FD << FD->getReturnType()
14188 << FD->getReturnTypeSourceRange();
14189 }
14190 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14191 // Point to variable declaration.
14192 if (const ValueDecl *VD = DRE->getDecl()) {
14193 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
14194 if (!DiagnosticEmitted) {
14195 S.Diag(Loc, diag::err_typecheck_assign_const)
14196 << ExprRange << ConstVariable << VD << VD->getType();
14197 DiagnosticEmitted = true;
14198 }
14199 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
14200 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
14201 }
14202 }
14203 } else if (isa<CXXThisExpr>(E)) {
14204 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
14205 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
14206 if (MD->isConst()) {
14207 if (!DiagnosticEmitted) {
14208 S.Diag(Loc, diag::err_typecheck_assign_const_method)
14209 << ExprRange << MD;
14210 DiagnosticEmitted = true;
14211 }
14212 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const_method)
14213 << MD << MD->getSourceRange();
14214 }
14215 }
14216 }
14217 }
14218
14219 if (DiagnosticEmitted)
14220 return;
14221
14222 // Can't determine a more specific message, so display the generic error.
14223 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
14224}
14225
14231
14233 const RecordType *Ty,
14234 SourceLocation Loc, SourceRange Range,
14235 OriginalExprKind OEK,
14236 bool &DiagnosticEmitted) {
14237 std::vector<const RecordType *> RecordTypeList;
14238 RecordTypeList.push_back(Ty);
14239 unsigned NextToCheckIndex = 0;
14240 // We walk the record hierarchy breadth-first to ensure that we print
14241 // diagnostics in field nesting order.
14242 while (RecordTypeList.size() > NextToCheckIndex) {
14243 bool IsNested = NextToCheckIndex > 0;
14244 for (const FieldDecl *Field : RecordTypeList[NextToCheckIndex]
14245 ->getDecl()
14246 ->getDefinitionOrSelf()
14247 ->fields()) {
14248 // First, check every field for constness.
14249 QualType FieldTy = Field->getType();
14250 if (FieldTy.isConstQualified()) {
14251 if (!DiagnosticEmitted) {
14252 S.Diag(Loc, diag::err_typecheck_assign_const)
14253 << Range << NestedConstMember << OEK << VD
14254 << IsNested << Field;
14255 DiagnosticEmitted = true;
14256 }
14257 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
14258 << NestedConstMember << IsNested << Field
14259 << FieldTy << Field->getSourceRange();
14260 }
14261
14262 // Then we append it to the list to check next in order.
14263 FieldTy = FieldTy.getCanonicalType();
14264 if (const auto *FieldRecTy = FieldTy->getAsCanonical<RecordType>()) {
14265 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
14266 RecordTypeList.push_back(FieldRecTy);
14267 }
14268 }
14269 ++NextToCheckIndex;
14270 }
14271}
14272
14273/// Emit an error for the case where a record we are trying to assign to has a
14274/// const-qualified field somewhere in its hierarchy.
14275static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
14276 SourceLocation Loc) {
14277 QualType Ty = E->getType();
14278 assert(Ty->isRecordType() && "lvalue was not record?");
14279 SourceRange Range = E->getSourceRange();
14280 const auto *RTy = Ty->getAsCanonical<RecordType>();
14281 bool DiagEmitted = false;
14282
14283 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
14284 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
14285 Range, OEK_Member, DiagEmitted);
14286 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
14287 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
14288 Range, OEK_Variable, DiagEmitted);
14289 else
14290 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
14291 Range, OEK_LValue, DiagEmitted);
14292 if (!DiagEmitted)
14293 DiagnoseConstAssignment(S, E, Loc);
14294}
14295
14296/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14297/// emit an error and return true. If so, return false.
14299 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
14300
14302
14303 SourceLocation OrigLoc = Loc;
14305 &Loc);
14306 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
14308 if (IsLV == Expr::MLV_Valid)
14309 return false;
14310
14311 unsigned DiagID = 0;
14312 bool NeedType = false;
14313 switch (IsLV) { // C99 6.5.16p2
14315 // Use a specialized diagnostic when we're assigning to an object
14316 // from an enclosing function or block.
14318 if (NCCK == NCCK_Block)
14319 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
14320 else
14321 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
14322 break;
14323 }
14324
14325 // In ARC, use some specialized diagnostics for occasions where we
14326 // infer 'const'. These are always pseudo-strong variables.
14327 if (S.getLangOpts().ObjCAutoRefCount) {
14328 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
14329 if (declRef && isa<VarDecl>(declRef->getDecl())) {
14330 VarDecl *var = cast<VarDecl>(declRef->getDecl());
14331
14332 // Use the normal diagnostic if it's pseudo-__strong but the
14333 // user actually wrote 'const'.
14334 if (var->isARCPseudoStrong() &&
14335 (!var->getTypeSourceInfo() ||
14336 !var->getTypeSourceInfo()->getType().isConstQualified())) {
14337 // There are three pseudo-strong cases:
14338 // - self
14339 ObjCMethodDecl *method = S.getCurMethodDecl();
14340 if (method && var == method->getSelfDecl()) {
14341 DiagID = method->isClassMethod()
14342 ? diag::err_typecheck_arc_assign_self_class_method
14343 : diag::err_typecheck_arc_assign_self;
14344
14345 // - Objective-C externally_retained attribute.
14346 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
14347 isa<ParmVarDecl>(var)) {
14348 DiagID = diag::err_typecheck_arc_assign_externally_retained;
14349
14350 // - fast enumeration variables
14351 } else {
14352 DiagID = diag::err_typecheck_arr_assign_enumeration;
14353 }
14354
14355 SourceRange Assign;
14356 if (Loc != OrigLoc)
14357 Assign = SourceRange(OrigLoc, OrigLoc);
14358 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14359 // We need to preserve the AST regardless, so migration tool
14360 // can do its job.
14361 return false;
14362 }
14363 }
14364 }
14365
14366 // If none of the special cases above are triggered, then this is a
14367 // simple const assignment.
14368 if (DiagID == 0) {
14369 DiagnoseConstAssignment(S, E, Loc);
14370 return true;
14371 }
14372
14373 break;
14375 DiagnoseConstAssignment(S, E, Loc);
14376 return true;
14379 return true;
14382 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
14383 NeedType = true;
14384 break;
14386 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
14387 NeedType = true;
14388 break;
14390 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
14391 break;
14392 case Expr::MLV_Valid:
14393 llvm_unreachable("did not take early return for MLV_Valid");
14397 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
14398 break;
14401 return S.RequireCompleteType(Loc, E->getType(),
14402 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
14404 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
14405 break;
14407 DiagID = diag::err_typecheck_duplicate_matrix_components_not_mlvalue;
14408 break;
14410 llvm_unreachable("readonly properties should be processed differently");
14412 DiagID = diag::err_readonly_message_assignment;
14413 break;
14415 DiagID = diag::err_no_subobject_property_setting;
14416 break;
14417 }
14418
14419 SourceRange Assign;
14420 if (Loc != OrigLoc)
14421 Assign = SourceRange(OrigLoc, OrigLoc);
14422 if (NeedType)
14423 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
14424 else
14425 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
14426 return true;
14427}
14428
14429static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
14430 SourceLocation Loc,
14431 Sema &Sema) {
14433 return;
14435 return;
14436 if (Loc.isInvalid() || Loc.isMacroID())
14437 return;
14438 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
14439 return;
14440
14441 // C / C++ fields
14442 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14443 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14444 if (ML && MR) {
14445 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14446 return;
14447 const ValueDecl *LHSDecl =
14449 const ValueDecl *RHSDecl =
14451 if (LHSDecl != RHSDecl)
14452 return;
14453 if (LHSDecl->getType().isVolatileQualified())
14454 return;
14455 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14456 if (RefTy->getPointeeType().isVolatileQualified())
14457 return;
14458
14459 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14460 }
14461
14462 // Objective-C instance variables
14463 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14464 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14465 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14466 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14467 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14468 if (RL && RR && RL->getDecl() == RR->getDecl())
14469 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14470 }
14471}
14472
14473// C99 6.5.16.1
14475 SourceLocation Loc,
14476 QualType CompoundType,
14477 BinaryOperatorKind Opc) {
14478 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14479
14480 // Verify that LHS is a modifiable lvalue, and emit error if not.
14481 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14482 return QualType();
14483
14484 QualType LHSType = LHSExpr->getType();
14485 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14486 CompoundType;
14487
14488 if (RHS.isUsable()) {
14489 // Even if this check fails don't return early to allow the best
14490 // possible error recovery and to allow any subsequent diagnostics to
14491 // work.
14492 const ValueDecl *Assignee = nullptr;
14493 bool ShowFullyQualifiedAssigneeName = false;
14494 // In simple cases describe what is being assigned to
14495 if (auto *DR = dyn_cast<DeclRefExpr>(LHSExpr->IgnoreParenCasts())) {
14496 Assignee = DR->getDecl();
14497 } else if (auto *ME = dyn_cast<MemberExpr>(LHSExpr->IgnoreParenCasts())) {
14498 Assignee = ME->getMemberDecl();
14499 ShowFullyQualifiedAssigneeName = true;
14500 }
14501
14503 LHSType, RHS.get(), AssignmentAction::Assigning, Loc, Assignee,
14504 ShowFullyQualifiedAssigneeName);
14505 }
14506
14507 // OpenCL v1.2 s6.1.1.1 p2:
14508 // The half data type can only be used to declare a pointer to a buffer that
14509 // contains half values
14510 if (getLangOpts().OpenCL &&
14511 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14512 LHSType->isHalfType()) {
14513 Diag(Loc, diag::err_opencl_half_load_store) << 1
14514 << LHSType.getUnqualifiedType();
14515 return QualType();
14516 }
14517
14518 // WebAssembly tables can't be used on RHS of an assignment expression.
14519 if (RHSType->isWebAssemblyTableType()) {
14520 Diag(Loc, diag::err_wasm_table_art) << 0;
14521 return QualType();
14522 }
14523
14524 AssignConvertType ConvTy;
14525 if (CompoundType.isNull()) {
14526 Expr *RHSCheck = RHS.get();
14527
14528 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14529
14530 QualType LHSTy(LHSType);
14531 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14532 if (RHS.isInvalid())
14533 return QualType();
14534 // Special case of NSObject attributes on c-style pointer types.
14536 ((Context.isObjCNSObjectType(LHSType) &&
14537 RHSType->isObjCObjectPointerType()) ||
14538 (Context.isObjCNSObjectType(RHSType) &&
14539 LHSType->isObjCObjectPointerType())))
14541
14542 if (IsAssignConvertCompatible(ConvTy) && LHSType->isObjCObjectType())
14543 Diag(Loc, diag::err_objc_object_assignment) << LHSType;
14544
14545 // If the RHS is a unary plus or minus, check to see if they = and + are
14546 // right next to each other. If so, the user may have typo'd "x =+ 4"
14547 // instead of "x += 4".
14548 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14549 RHSCheck = ICE->getSubExpr();
14550 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14551 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14552 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14553 // Only if the two operators are exactly adjacent.
14554 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14555 // And there is a space or other character before the subexpr of the
14556 // unary +/-. We don't want to warn on "x=-1".
14557 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14558 UO->getSubExpr()->getBeginLoc().isFileID()) {
14559 Diag(Loc, diag::warn_not_compound_assign)
14560 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14561 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14562 }
14563 }
14564
14565 if (IsAssignConvertCompatible(ConvTy)) {
14566 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14567 // Warn about retain cycles where a block captures the LHS, but
14568 // not if the LHS is a simple variable into which the block is
14569 // being stored...unless that variable can be captured by reference!
14570 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14571 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14572 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14573 ObjC().checkRetainCycles(LHSExpr, RHS.get());
14574 }
14575
14576 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14578 // It is safe to assign a weak reference into a strong variable.
14579 // Although this code can still have problems:
14580 // id x = self.weakProp;
14581 // id y = self.weakProp;
14582 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14583 // paths through the function. This should be revisited if
14584 // -Wrepeated-use-of-weak is made flow-sensitive.
14585 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14586 // variable, which will be valid for the current autorelease scope.
14587 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14588 RHS.get()->getBeginLoc()))
14590
14591 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14592 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14593 }
14594 }
14595 } else {
14596 // Compound assignment "x += y"
14597 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14598 }
14599
14600 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
14602 return QualType();
14603
14604 CheckForNullPointerDereference(*this, LHSExpr);
14605
14606 AssignedEntity AE{LHSExpr};
14607 checkAssignmentLifetime(*this, AE, RHS.get());
14608
14609 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14610 if (CompoundType.isNull()) {
14611 // C++2a [expr.ass]p5:
14612 // A simple-assignment whose left operand is of a volatile-qualified
14613 // type is deprecated unless the assignment is either a discarded-value
14614 // expression or an unevaluated operand
14615 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14616 }
14617 }
14618
14619 // C11 6.5.16p3: The type of an assignment expression is the type of the
14620 // left operand would have after lvalue conversion.
14621 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14622 // qualified type, the value has the unqualified version of the type of the
14623 // lvalue; additionally, if the lvalue has atomic type, the value has the
14624 // non-atomic version of the type of the lvalue.
14625 // C++ 5.17p1: the type of the assignment expression is that of its left
14626 // operand.
14627 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14628}
14629
14630// Scenarios to ignore if expression E is:
14631// 1. an explicit cast expression into void
14632// 2. a function call expression that returns void
14633static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14634 E = E->IgnoreParens();
14635
14636 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14637 if (CE->getCastKind() == CK_ToVoid) {
14638 return true;
14639 }
14640
14641 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14642 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14643 CE->getSubExpr()->getType()->isDependentType()) {
14644 return true;
14645 }
14646 }
14647
14648 if (const auto *CE = dyn_cast<CallExpr>(E))
14649 return CE->getCallReturnType(Context)->isVoidType();
14650 return false;
14651}
14652
14654 // No warnings in macros
14655 if (Loc.isMacroID())
14656 return;
14657
14658 // Don't warn in template instantiations.
14660 return;
14661
14662 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14663 // instead, skip more than needed, then call back into here with the
14664 // CommaVisitor in SemaStmt.cpp.
14665 // The listed locations are the initialization and increment portions
14666 // of a for loop. The additional checks are on the condition of
14667 // if statements, do/while loops, and for loops.
14668 if (getCurScope()->isControlScope())
14669 return;
14670
14671 // If there are multiple comma operators used together, get the RHS of the
14672 // of the comma operator as the LHS.
14673 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14674 if (BO->getOpcode() != BO_Comma)
14675 break;
14676 LHS = BO->getRHS();
14677 }
14678
14679 // Only allow some expressions on LHS to not warn.
14680 if (IgnoreCommaOperand(LHS, Context))
14681 return;
14682
14683 Diag(Loc, diag::warn_comma_operator);
14684 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14685 << LHS->getSourceRange()
14687 LangOpts.CPlusPlus ? "static_cast<void>("
14688 : "(void)(")
14689 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14690 ")");
14691}
14692
14693// C99 6.5.17
14695 SourceLocation Loc) {
14696 LHS = S.CheckPlaceholderExpr(LHS.get());
14697 RHS = S.CheckPlaceholderExpr(RHS.get());
14698 if (LHS.isInvalid() || RHS.isInvalid())
14699 return QualType();
14700
14701 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14702 // operands, but not unary promotions.
14703 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14704
14705 // So we treat the LHS as a ignored value, and in C++ we allow the
14706 // containing site to determine what should be done with the RHS.
14707 LHS = S.IgnoredValueConversions(LHS.get());
14708 if (LHS.isInvalid())
14709 return QualType();
14710
14711 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14712
14713 if (!S.getLangOpts().CPlusPlus) {
14715 if (RHS.isInvalid())
14716 return QualType();
14717 if (!RHS.get()->getType()->isVoidType())
14718 S.RequireCompleteType(Loc, RHS.get()->getType(),
14719 diag::err_incomplete_type);
14720 }
14721
14722 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14723 S.DiagnoseCommaOperator(LHS.get(), Loc);
14724
14725 return RHS.get()->getType();
14726}
14727
14728/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14729/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14732 ExprObjectKind &OK,
14733 SourceLocation OpLoc, bool IsInc,
14734 bool IsPrefix) {
14735 QualType ResType = Op->getType();
14736 // Atomic types can be used for increment / decrement where the non-atomic
14737 // versions can, so ignore the _Atomic() specifier for the purpose of
14738 // checking.
14739 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14740 ResType = ResAtomicType->getValueType();
14741
14742 assert(!ResType.isNull() && "no type for increment/decrement expression");
14743
14744 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14745 // Decrement of bool is not allowed.
14746 if (!IsInc) {
14747 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14748 return QualType();
14749 }
14750 // Increment of bool sets it to true, but is deprecated.
14751 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14752 : diag::warn_increment_bool)
14753 << Op->getSourceRange();
14754 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14755 // Error on enum increments and decrements in C++ mode
14756 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14757 return QualType();
14758 } else if (ResType->isRealType()) {
14759 // OK!
14760 } else if (ResType->isPointerType()) {
14761 // C99 6.5.2.4p2, 6.5.6p2
14762 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14763 return QualType();
14764 } else if (ResType->isOverflowBehaviorType()) {
14765 // OK!
14766 } else if (ResType->isObjCObjectPointerType()) {
14767 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14768 // Otherwise, we just need a complete type.
14769 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14770 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14771 return QualType();
14772 } else if (ResType->isAnyComplexType()) {
14773 // C99 does not support ++/-- on complex types, we allow as an extension.
14774 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14775 : diag::ext_c2y_increment_complex)
14776 << IsInc << Op->getSourceRange();
14777 } else if (ResType->isPlaceholderType()) {
14779 if (PR.isInvalid()) return QualType();
14780 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14781 IsInc, IsPrefix);
14782 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14783 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14784 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14785 (ResType->castAs<VectorType>()->getVectorKind() !=
14787 // The z vector extensions allow ++ and -- for non-bool vectors.
14788 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14789 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14790 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14791 } else {
14792 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14793 << ResType << int(IsInc) << Op->getSourceRange();
14794 return QualType();
14795 }
14796 // At this point, we know we have a real, complex or pointer type.
14797 // Now make sure the operand is a modifiable lvalue.
14798 if (CheckForModifiableLvalue(Op, OpLoc, S))
14799 return QualType();
14800 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14801 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14802 // An operand with volatile-qualified type is deprecated
14803 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14804 << IsInc << ResType;
14805 }
14806 // In C++, a prefix increment is the same type as the operand. Otherwise
14807 // (in C or with postfix), the increment is the unqualified type of the
14808 // operand.
14809 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14810 VK = VK_LValue;
14811 OK = Op->getObjectKind();
14812 return ResType;
14813 } else {
14814 VK = VK_PRValue;
14815 return ResType.getUnqualifiedType();
14816 }
14817}
14818
14819/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14820/// This routine allows us to typecheck complex/recursive expressions
14821/// where the declaration is needed for type checking. We only need to
14822/// handle cases when the expression references a function designator
14823/// or is an lvalue. Here are some examples:
14824/// - &(x) => x
14825/// - &*****f => f for f a function designator.
14826/// - &s.xx => s
14827/// - &s.zz[1].yy -> s, if zz is an array
14828/// - *(x + 1) -> x, if x is an array
14829/// - &"123"[2] -> 0
14830/// - & __real__ x -> x
14831///
14832/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14833/// members.
14835 switch (E->getStmtClass()) {
14836 case Stmt::DeclRefExprClass:
14837 return cast<DeclRefExpr>(E)->getDecl();
14838 case Stmt::MemberExprClass:
14839 // If this is an arrow operator, the address is an offset from
14840 // the base's value, so the object the base refers to is
14841 // irrelevant.
14842 if (cast<MemberExpr>(E)->isArrow())
14843 return nullptr;
14844 // Otherwise, the expression refers to a part of the base
14845 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14846 case Stmt::ArraySubscriptExprClass: {
14847 // FIXME: This code shouldn't be necessary! We should catch the implicit
14848 // promotion of register arrays earlier.
14849 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14850 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14851 if (ICE->getSubExpr()->getType()->isArrayType())
14852 return getPrimaryDecl(ICE->getSubExpr());
14853 }
14854 return nullptr;
14855 }
14856 case Stmt::UnaryOperatorClass: {
14858
14859 switch(UO->getOpcode()) {
14860 case UO_Real:
14861 case UO_Imag:
14862 case UO_Extension:
14863 return getPrimaryDecl(UO->getSubExpr());
14864 default:
14865 return nullptr;
14866 }
14867 }
14868 case Stmt::ParenExprClass:
14869 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14870 case Stmt::ImplicitCastExprClass:
14871 // If the result of an implicit cast is an l-value, we care about
14872 // the sub-expression; otherwise, the result here doesn't matter.
14873 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14874 case Stmt::CXXUuidofExprClass:
14875 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14876 default:
14877 return nullptr;
14878 }
14879}
14880
14881namespace {
14882enum {
14883 AO_Bit_Field = 0,
14884 AO_Vector_Element = 1,
14885 AO_Property_Expansion = 2,
14886 AO_Register_Variable = 3,
14887 AO_Matrix_Element = 4,
14888 AO_No_Error = 5
14889};
14890}
14891/// Diagnose invalid operand for address of operations.
14892///
14893/// \param Type The type of operand which cannot have its address taken.
14895 Expr *E, unsigned Type) {
14896 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14897}
14898
14900 const Expr *Op,
14901 const CXXMethodDecl *MD) {
14902 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14903
14904 if (Op != DRE)
14905 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14906 << Op->getSourceRange();
14907
14908 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14909 if (isa<CXXDestructorDecl>(MD))
14910 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14911 << DRE->getSourceRange();
14912
14913 if (DRE->getQualifier())
14914 return false;
14915
14916 if (MD->getParent()->getName().empty())
14917 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14918 << DRE->getSourceRange();
14919
14920 SmallString<32> Str;
14921 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14922 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14923 << DRE->getSourceRange()
14924 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14925}
14926
14928 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14929 if (PTy->getKind() == BuiltinType::Overload) {
14930 Expr *E = OrigOp.get()->IgnoreParens();
14931 if (!isa<OverloadExpr>(E)) {
14932 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14933 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14934 << OrigOp.get()->getSourceRange();
14935 return QualType();
14936 }
14937
14941 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14942 << OrigOp.get()->getSourceRange();
14943 return QualType();
14944 }
14945
14946 return Context.OverloadTy;
14947 }
14948
14949 if (PTy->getKind() == BuiltinType::UnknownAny)
14950 return Context.UnknownAnyTy;
14951
14952 if (PTy->getKind() == BuiltinType::BoundMember) {
14953 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14954 << OrigOp.get()->getSourceRange();
14955 return QualType();
14956 }
14957
14958 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14959 if (OrigOp.isInvalid()) return QualType();
14960 }
14961
14962 if (OrigOp.get()->isTypeDependent())
14963 return Context.DependentTy;
14964
14965 assert(!OrigOp.get()->hasPlaceholderType());
14966
14967 // Make sure to ignore parentheses in subsequent checks
14968 Expr *op = OrigOp.get()->IgnoreParens();
14969
14970 // In OpenCL captures for blocks called as lambda functions
14971 // are located in the private address space. Blocks used in
14972 // enqueue_kernel can be located in a different address space
14973 // depending on a vendor implementation. Thus preventing
14974 // taking an address of the capture to avoid invalid AS casts.
14975 if (LangOpts.OpenCL) {
14976 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14977 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14978 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14979 return QualType();
14980 }
14981 }
14982
14983 if (getLangOpts().C99) {
14984 // Implement C99-only parts of addressof rules.
14985 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14986 if (uOp->getOpcode() == UO_Deref)
14987 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14988 // (assuming the deref expression is valid).
14989 return uOp->getSubExpr()->getType();
14990 }
14991 // Technically, there should be a check for array subscript
14992 // expressions here, but the result of one is always an lvalue anyway.
14993 }
14994 ValueDecl *dcl = getPrimaryDecl(op);
14995
14996 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14997 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14998 op->getBeginLoc()))
14999 return QualType();
15000
15002 unsigned AddressOfError = AO_No_Error;
15003
15004 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
15005 bool IsError = isSFINAEContext();
15006 Diag(OpLoc, IsError ? diag::err_typecheck_addrof_temporary
15007 : diag::ext_typecheck_addrof_temporary)
15008 << op->getType() << op->getSourceRange();
15009 if (IsError)
15010 return QualType();
15011 // Materialize the temporary as an lvalue so that we can take its address.
15012 OrigOp = op =
15013 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
15014 } else if (isa<ObjCSelectorExpr>(op)) {
15015 return Context.getPointerType(op->getType());
15016 } else if (lval == Expr::LV_MemberFunction) {
15017 // If it's an instance method, make a member pointer.
15018 // The expression must have exactly the form &A::foo.
15019
15020 // If the underlying expression isn't a decl ref, give up.
15021 if (!isa<DeclRefExpr>(op)) {
15022 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
15023 << OrigOp.get()->getSourceRange();
15024 return QualType();
15025 }
15026 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
15028
15029 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15030 QualType MPTy = Context.getMemberPointerType(
15031 op->getType(), DRE->getQualifier(), MD->getParent());
15032
15033 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
15034 !isUnevaluatedContext() && !MPTy->isDependentType()) {
15035 // When pointer authentication is enabled, argument and return types of
15036 // vitual member functions must be complete. This is because vitrual
15037 // member function pointers are implemented using virtual dispatch
15038 // thunks and the thunks cannot be emitted if the argument or return
15039 // types are incomplete.
15040 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
15041 SourceLocation DeclRefLoc,
15042 SourceLocation RetArgTypeLoc) {
15043 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
15044 Diag(DeclRefLoc,
15045 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
15046 Diag(RetArgTypeLoc,
15047 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
15048 << T;
15049 return true;
15050 }
15051 return false;
15052 };
15053 QualType RetTy = MD->getReturnType();
15054 bool IsIncomplete =
15055 !RetTy->isVoidType() &&
15056 ReturnOrParamTypeIsIncomplete(
15057 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
15058 for (auto *PVD : MD->parameters())
15059 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
15060 PVD->getBeginLoc());
15061 if (IsIncomplete)
15062 return QualType();
15063 }
15064
15065 // Under the MS ABI, lock down the inheritance model now.
15066 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15067 (void)isCompleteType(OpLoc, MPTy);
15068 return MPTy;
15069 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
15070 // C99 6.5.3.2p1
15071 // The operand must be either an l-value or a function designator
15072 if (!op->getType()->isFunctionType()) {
15073 // Use a special diagnostic for loads from property references.
15074 if (isa<PseudoObjectExpr>(op)) {
15075 AddressOfError = AO_Property_Expansion;
15076 } else {
15077 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
15078 << op->getType() << op->getSourceRange();
15079 return QualType();
15080 }
15081 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
15082 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
15083 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
15084 }
15085
15086 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
15087 // The operand cannot be a bit-field
15088 AddressOfError = AO_Bit_Field;
15089 } else if (op->getObjectKind() == OK_VectorComponent) {
15090 // The operand cannot be an element of a vector
15091 AddressOfError = AO_Vector_Element;
15092 } else if (op->getObjectKind() == OK_MatrixComponent) {
15093 // The operand cannot be an element of a matrix.
15094 AddressOfError = AO_Matrix_Element;
15095 } else if (dcl) { // C99 6.5.3.2p1
15096 // We have an lvalue with a decl. Make sure the decl is not declared
15097 // with the register storage-class specifier.
15098 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
15099 // in C++ it is not error to take address of a register
15100 // variable (c++03 7.1.1P3)
15101 if (vd->getStorageClass() == SC_Register &&
15103 AddressOfError = AO_Register_Variable;
15104 }
15105 } else if (isa<MSPropertyDecl>(dcl)) {
15106 AddressOfError = AO_Property_Expansion;
15107 } else if (isa<FunctionTemplateDecl>(dcl)) {
15108 return Context.OverloadTy;
15109 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
15110 // Okay: we can take the address of a field.
15111 // Could be a pointer to member, though, if there is an explicit
15112 // scope qualifier for the class.
15113
15114 // [C++26] [expr.prim.id.general]
15115 // If an id-expression E denotes a non-static non-type member
15116 // of some class C [...] and if E is a qualified-id, E is
15117 // not the un-parenthesized operand of the unary & operator [...]
15118 // the id-expression is transformed into a class member access expression.
15119 if (auto *DRE = dyn_cast<DeclRefExpr>(op);
15120 DRE && DRE->getQualifier() && !isa<ParenExpr>(OrigOp.get())) {
15121 DeclContext *Ctx = dcl->getDeclContext();
15122 if (Ctx && Ctx->isRecord()) {
15123 if (dcl->getType()->isReferenceType()) {
15124 Diag(OpLoc,
15125 diag::err_cannot_form_pointer_to_member_of_reference_type)
15126 << dcl->getDeclName() << dcl->getType();
15127 return QualType();
15128 }
15129
15130 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
15131 Ctx = Ctx->getParent();
15132
15133 QualType MPTy = Context.getMemberPointerType(
15134 op->getType(), DRE->getQualifier(), cast<CXXRecordDecl>(Ctx));
15135 // Under the MS ABI, lock down the inheritance model now.
15136 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
15137 (void)isCompleteType(OpLoc, MPTy);
15138 return MPTy;
15139 }
15140 }
15144 llvm_unreachable("Unknown/unexpected decl type");
15145 }
15146
15147 if (AddressOfError != AO_No_Error) {
15148 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
15149 return QualType();
15150 }
15151
15152 if (lval == Expr::LV_IncompleteVoidType) {
15153 // Taking the address of a void variable is technically illegal, but we
15154 // allow it in cases which are otherwise valid.
15155 // Example: "extern void x; void* y = &x;".
15156 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
15157 }
15158
15159 // If the operand has type "type", the result has type "pointer to type".
15160 if (op->getType()->isObjCObjectType())
15161 return Context.getObjCObjectPointerType(op->getType());
15162
15163 // Cannot take the address of WebAssembly references or tables.
15164 if (Context.getTargetInfo().getTriple().isWasm()) {
15165 QualType OpTy = op->getType();
15166 if (OpTy.isWebAssemblyReferenceType()) {
15167 Diag(OpLoc, diag::err_wasm_ca_reference)
15168 << 1 << OrigOp.get()->getSourceRange();
15169 return QualType();
15170 }
15171 if (OpTy->isWebAssemblyTableType()) {
15172 Diag(OpLoc, diag::err_wasm_table_pr)
15173 << 1 << OrigOp.get()->getSourceRange();
15174 return QualType();
15175 }
15176 }
15177
15178 CheckAddressOfPackedMember(op);
15179
15180 return Context.getPointerType(op->getType());
15181}
15182
15183static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
15184 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
15185 if (!DRE)
15186 return;
15187 const Decl *D = DRE->getDecl();
15188 if (!D)
15189 return;
15190 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
15191 if (!Param)
15192 return;
15193 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
15194 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
15195 return;
15196 if (FunctionScopeInfo *FD = S.getCurFunction())
15197 FD->ModifiedNonNullParams.insert(Param);
15198}
15199
15200/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15202 SourceLocation OpLoc,
15203 bool IsAfterAmp = false) {
15204 ExprResult ConvResult = S.UsualUnaryConversions(Op);
15205 if (ConvResult.isInvalid())
15206 return QualType();
15207 Op = ConvResult.get();
15208 QualType OpTy = Op->getType();
15210
15212 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
15213 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
15214 Op->getSourceRange());
15215 }
15216
15217 if (const PointerType *PT = OpTy->getAs<PointerType>())
15218 {
15219 Result = PT->getPointeeType();
15220 }
15221 else if (const ObjCObjectPointerType *OPT =
15223 Result = OPT->getPointeeType();
15224 else {
15226 if (PR.isInvalid()) return QualType();
15227 if (PR.get() != Op)
15228 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
15229 }
15230
15231 if (Result.isNull()) {
15232 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
15233 << OpTy << Op->getSourceRange();
15234 return QualType();
15235 }
15236
15237 if (Result->isVoidType()) {
15238 // C++ [expr.unary.op]p1:
15239 // [...] the expression to which [the unary * operator] is applied shall
15240 // be a pointer to an object type, or a pointer to a function type
15241 LangOptions LO = S.getLangOpts();
15242 if (LO.CPlusPlus)
15243 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
15244 << OpTy << Op->getSourceRange();
15245 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
15246 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
15247 << OpTy << Op->getSourceRange();
15248 }
15249
15250 // Dereferences are usually l-values...
15251 VK = VK_LValue;
15252
15253 // ...except that certain expressions are never l-values in C.
15254 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
15255 VK = VK_PRValue;
15256
15257 return Result;
15258}
15259
15260BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
15262 switch (Kind) {
15263 default: llvm_unreachable("Unknown binop!");
15264 case tok::periodstar: Opc = BO_PtrMemD; break;
15265 case tok::arrowstar: Opc = BO_PtrMemI; break;
15266 case tok::star: Opc = BO_Mul; break;
15267 case tok::slash: Opc = BO_Div; break;
15268 case tok::percent: Opc = BO_Rem; break;
15269 case tok::plus: Opc = BO_Add; break;
15270 case tok::minus: Opc = BO_Sub; break;
15271 case tok::lessless: Opc = BO_Shl; break;
15272 case tok::greatergreater: Opc = BO_Shr; break;
15273 case tok::lessequal: Opc = BO_LE; break;
15274 case tok::less: Opc = BO_LT; break;
15275 case tok::greaterequal: Opc = BO_GE; break;
15276 case tok::greater: Opc = BO_GT; break;
15277 case tok::exclaimequal: Opc = BO_NE; break;
15278 case tok::equalequal: Opc = BO_EQ; break;
15279 case tok::spaceship: Opc = BO_Cmp; break;
15280 case tok::amp: Opc = BO_And; break;
15281 case tok::caret: Opc = BO_Xor; break;
15282 case tok::pipe: Opc = BO_Or; break;
15283 case tok::ampamp: Opc = BO_LAnd; break;
15284 case tok::pipepipe: Opc = BO_LOr; break;
15285 case tok::equal: Opc = BO_Assign; break;
15286 case tok::starequal: Opc = BO_MulAssign; break;
15287 case tok::slashequal: Opc = BO_DivAssign; break;
15288 case tok::percentequal: Opc = BO_RemAssign; break;
15289 case tok::plusequal: Opc = BO_AddAssign; break;
15290 case tok::minusequal: Opc = BO_SubAssign; break;
15291 case tok::lesslessequal: Opc = BO_ShlAssign; break;
15292 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
15293 case tok::ampequal: Opc = BO_AndAssign; break;
15294 case tok::caretequal: Opc = BO_XorAssign; break;
15295 case tok::pipeequal: Opc = BO_OrAssign; break;
15296 case tok::comma: Opc = BO_Comma; break;
15297 }
15298 return Opc;
15299}
15300
15302 tok::TokenKind Kind) {
15304 switch (Kind) {
15305 default: llvm_unreachable("Unknown unary op!");
15306 case tok::plusplus: Opc = UO_PreInc; break;
15307 case tok::minusminus: Opc = UO_PreDec; break;
15308 case tok::amp: Opc = UO_AddrOf; break;
15309 case tok::star: Opc = UO_Deref; break;
15310 case tok::plus: Opc = UO_Plus; break;
15311 case tok::minus: Opc = UO_Minus; break;
15312 case tok::tilde: Opc = UO_Not; break;
15313 case tok::exclaim: Opc = UO_LNot; break;
15314 case tok::kw___real: Opc = UO_Real; break;
15315 case tok::kw___imag: Opc = UO_Imag; break;
15316 case tok::kw___extension__: Opc = UO_Extension; break;
15317 }
15318 return Opc;
15319}
15320
15321const FieldDecl *
15323 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15324 // common for setters.
15325 // struct A {
15326 // int X;
15327 // -void setX(int X) { X = X; }
15328 // +void setX(int X) { this->X = X; }
15329 // };
15330
15331 // Only consider parameters for self assignment fixes.
15332 if (!isa<ParmVarDecl>(SelfAssigned))
15333 return nullptr;
15334 const auto *Method =
15335 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
15336 if (!Method)
15337 return nullptr;
15338
15339 const CXXRecordDecl *Parent = Method->getParent();
15340 // In theory this is fixable if the lambda explicitly captures this, but
15341 // that's added complexity that's rarely going to be used.
15342 if (Parent->isLambda())
15343 return nullptr;
15344
15345 // FIXME: Use an actual Lookup operation instead of just traversing fields
15346 // in order to get base class fields.
15347 auto Field =
15348 llvm::find_if(Parent->fields(),
15349 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
15350 return F->getDeclName() == Name;
15351 });
15352 return (Field != Parent->field_end()) ? *Field : nullptr;
15353}
15354
15355/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15356/// This warning suppressed in the event of macro expansions.
15357static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
15358 SourceLocation OpLoc, bool IsBuiltin) {
15360 return;
15361 if (S.isUnevaluatedContext())
15362 return;
15363 if (OpLoc.isInvalid() || OpLoc.isMacroID())
15364 return;
15365 LHSExpr = LHSExpr->IgnoreParenImpCasts();
15366 RHSExpr = RHSExpr->IgnoreParenImpCasts();
15367 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15368 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15369 if (!LHSDeclRef || !RHSDeclRef ||
15370 LHSDeclRef->getLocation().isMacroID() ||
15371 RHSDeclRef->getLocation().isMacroID())
15372 return;
15373 const ValueDecl *LHSDecl =
15374 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
15375 const ValueDecl *RHSDecl =
15376 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
15377 if (LHSDecl != RHSDecl)
15378 return;
15379 if (LHSDecl->getType().isVolatileQualified())
15380 return;
15381 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
15382 if (RefTy->getPointeeType().isVolatileQualified())
15383 return;
15384
15385 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
15386 : diag::warn_self_assignment_overloaded)
15387 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
15388 << RHSExpr->getSourceRange();
15389 if (const FieldDecl *SelfAssignField =
15391 Diag << 1 << SelfAssignField
15392 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
15393 else
15394 Diag << 0;
15395}
15396
15397/// Check if a bitwise-& is performed on an Objective-C pointer. This
15398/// is usually indicative of introspection within the Objective-C pointer.
15400 SourceLocation OpLoc) {
15401 if (!S.getLangOpts().ObjC)
15402 return;
15403
15404 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
15405 const Expr *LHS = L.get();
15406 const Expr *RHS = R.get();
15407
15409 ObjCPointerExpr = LHS;
15410 OtherExpr = RHS;
15411 }
15412 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15413 ObjCPointerExpr = RHS;
15414 OtherExpr = LHS;
15415 }
15416
15417 // This warning is deliberately made very specific to reduce false
15418 // positives with logic that uses '&' for hashing. This logic mainly
15419 // looks for code trying to introspect into tagged pointers, which
15420 // code should generally never do.
15421 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
15422 unsigned Diag = diag::warn_objc_pointer_masking;
15423 // Determine if we are introspecting the result of performSelectorXXX.
15424 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
15425 // Special case messages to -performSelector and friends, which
15426 // can return non-pointer values boxed in a pointer value.
15427 // Some clients may wish to silence warnings in this subcase.
15428 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
15429 Selector S = ME->getSelector();
15430 StringRef SelArg0 = S.getNameForSlot(0);
15431 if (SelArg0.starts_with("performSelector"))
15432 Diag = diag::warn_objc_pointer_masking_performSelector;
15433 }
15434
15435 S.Diag(OpLoc, Diag)
15436 << ObjCPointerExpr->getSourceRange();
15437 }
15438}
15439
15440// This helper function promotes a binary operator's operands (which are of a
15441// half vector type) to a vector of floats and then truncates the result to
15442// a vector of either half or short.
15444 BinaryOperatorKind Opc, QualType ResultTy,
15446 bool IsCompAssign, SourceLocation OpLoc,
15447 FPOptionsOverride FPFeatures) {
15448 auto &Context = S.getASTContext();
15449 assert((isVector(ResultTy, Context.HalfTy) ||
15450 isVector(ResultTy, Context.ShortTy)) &&
15451 "Result must be a vector of half or short");
15452 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
15453 isVector(RHS.get()->getType(), Context.HalfTy) &&
15454 "both operands expected to be a half vector");
15455
15456 RHS = convertVector(RHS.get(), Context.FloatTy, S);
15457 QualType BinOpResTy = RHS.get()->getType();
15458
15459 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15460 // change BinOpResTy to a vector of ints.
15461 if (isVector(ResultTy, Context.ShortTy))
15462 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
15463
15464 if (IsCompAssign)
15465 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15466 ResultTy, VK, OK, OpLoc, FPFeatures,
15467 BinOpResTy, BinOpResTy);
15468
15469 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15470 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15471 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15472 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15473}
15474
15475/// Returns true if conversion between vectors of halfs and vectors of floats
15476/// is needed.
15477static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15478 Expr *E0, Expr *E1 = nullptr) {
15479 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15481 return false;
15482
15483 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15484 QualType Ty = E->IgnoreImplicit()->getType();
15485
15486 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15487 // to vectors of floats. Although the element type of the vectors is __fp16,
15488 // the vectors shouldn't be treated as storage-only types. See the
15489 // discussion here: https://reviews.llvm.org/rG825235c140e7
15490 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15491 if (VT->getVectorKind() == VectorKind::Neon)
15492 return false;
15493 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15494 }
15495 return false;
15496 };
15497
15498 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15499}
15500
15502 BinaryOperatorKind Opc, Expr *LHSExpr,
15503 Expr *RHSExpr, bool ForFoldExpression) {
15504 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15505 // The syntax only allows initializer lists on the RHS of assignment,
15506 // so we don't need to worry about accepting invalid code for
15507 // non-assignment operators.
15508 // C++11 5.17p9:
15509 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15510 // of x = {} is x = T().
15512 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15513 InitializedEntity Entity =
15515 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15516 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15517 if (Init.isInvalid())
15518 return Init;
15519 RHSExpr = Init.get();
15520 }
15521
15522 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15523 QualType ResultTy; // Result type of the binary operator.
15524 // The following two variables are used for compound assignment operators
15525 QualType CompLHSTy; // Type of LHS after promotions for computation
15526 QualType CompResultTy; // Type of computation result
15529 bool ConvertHalfVec = false;
15530
15531 if (!LHS.isUsable() || !RHS.isUsable())
15532 return ExprError();
15533
15534 if (getLangOpts().OpenCL) {
15535 QualType LHSTy = LHSExpr->getType();
15536 QualType RHSTy = RHSExpr->getType();
15537 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15538 // the ATOMIC_VAR_INIT macro.
15539 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15540 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15541 if (BO_Assign == Opc)
15542 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15543 else
15544 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15545 return ExprError();
15546 }
15547
15548 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15549 // only with a builtin functions and therefore should be disallowed here.
15550 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15551 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15552 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15553 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15554 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15555 return ExprError();
15556 }
15557 }
15558
15559 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15560 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15561
15562 switch (Opc) {
15563 case BO_Assign:
15564 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15565 if (getLangOpts().CPlusPlus &&
15566 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15567 VK = LHS.get()->getValueKind();
15568 OK = LHS.get()->getObjectKind();
15569 }
15570 if (!ResultTy.isNull()) {
15571 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15572 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15573
15574 // Avoid copying a block to the heap if the block is assigned to a local
15575 // auto variable that is declared in the same scope as the block. This
15576 // optimization is unsafe if the local variable is declared in an outer
15577 // scope. For example:
15578 //
15579 // BlockTy b;
15580 // {
15581 // b = ^{...};
15582 // }
15583 // // It is unsafe to invoke the block here if it wasn't copied to the
15584 // // heap.
15585 // b();
15586
15587 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15588 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15589 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15590 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15591 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15592
15594 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15596 }
15597 RecordModifiableNonNullParam(*this, LHS.get());
15598 break;
15599 case BO_PtrMemD:
15600 case BO_PtrMemI:
15601 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15602 Opc == BO_PtrMemI);
15603 break;
15604 case BO_Mul:
15605 case BO_Div:
15606 ConvertHalfVec = true;
15607 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15608 break;
15609 case BO_Rem:
15610 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15611 break;
15612 case BO_Add:
15613 ConvertHalfVec = true;
15614 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15615 break;
15616 case BO_Sub:
15617 ConvertHalfVec = true;
15618 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc);
15619 break;
15620 case BO_Shl:
15621 case BO_Shr:
15622 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15623 break;
15624 case BO_LE:
15625 case BO_LT:
15626 case BO_GE:
15627 case BO_GT:
15628 ConvertHalfVec = true;
15629 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15630
15631 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
15632 !ForFoldExpression && BI && BI->isComparisonOp())
15633 Diag(OpLoc, diag::warn_consecutive_comparison)
15634 << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);
15635
15636 break;
15637 case BO_EQ:
15638 case BO_NE:
15639 ConvertHalfVec = true;
15640 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15641 break;
15642 case BO_Cmp:
15643 ConvertHalfVec = true;
15644 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15645 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15646 break;
15647 case BO_And:
15648 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15649 [[fallthrough]];
15650 case BO_Xor:
15651 case BO_Or:
15652 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15653 break;
15654 case BO_LAnd:
15655 case BO_LOr:
15656 ConvertHalfVec = true;
15657 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15658 break;
15659 case BO_MulAssign:
15660 case BO_DivAssign:
15661 ConvertHalfVec = true;
15662 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, Opc);
15663 CompLHSTy = CompResultTy;
15664 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15665 ResultTy =
15666 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15667 break;
15668 case BO_RemAssign:
15669 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15670 CompLHSTy = CompResultTy;
15671 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15672 ResultTy =
15673 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15674 break;
15675 case BO_AddAssign:
15676 ConvertHalfVec = true;
15677 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15678 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15679 ResultTy =
15680 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15681 break;
15682 case BO_SubAssign:
15683 ConvertHalfVec = true;
15684 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15685 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15686 ResultTy =
15687 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15688 break;
15689 case BO_ShlAssign:
15690 case BO_ShrAssign:
15691 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15692 CompLHSTy = CompResultTy;
15693 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15694 ResultTy =
15695 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15696 break;
15697 case BO_AndAssign:
15698 case BO_OrAssign: // fallthrough
15699 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15700 [[fallthrough]];
15701 case BO_XorAssign:
15702 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15703 CompLHSTy = CompResultTy;
15704 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15705 ResultTy =
15706 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15707 break;
15708 case BO_Comma:
15709 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15710 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15711 VK = RHS.get()->getValueKind();
15712 OK = RHS.get()->getObjectKind();
15713 }
15714 break;
15715 }
15716 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15717 return ExprError();
15718
15719 // Some of the binary operations require promoting operands of half vector to
15720 // float vectors and truncating the result back to half vector. For now, we do
15721 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15722 // arm64).
15723 assert(
15724 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15725 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15726 "both sides are half vectors or neither sides are");
15727 ConvertHalfVec =
15728 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15729
15730 // Check for array bounds violations for both sides of the BinaryOperator
15731 CheckArrayAccess(LHS.get());
15732 CheckArrayAccess(RHS.get());
15733
15734 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15735 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15736 &Context.Idents.get("object_setClass"),
15738 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15739 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15740 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15742 "object_setClass(")
15743 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15744 ",")
15745 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15746 }
15747 else
15748 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15749 }
15750 else if (const ObjCIvarRefExpr *OIRE =
15751 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15752 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15753
15754 // Opc is not a compound assignment if CompResultTy is null.
15755 if (CompResultTy.isNull()) {
15756 if (ConvertHalfVec)
15757 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15758 OpLoc, CurFPFeatureOverrides());
15759 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15760 VK, OK, OpLoc, CurFPFeatureOverrides());
15761 }
15762
15763 // Handle compound assignments.
15764 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15766 VK = VK_LValue;
15767 OK = LHS.get()->getObjectKind();
15768 }
15769
15770 // The LHS is not converted to the result type for fixed-point compound
15771 // assignment as the common type is computed on demand. Reset the CompLHSTy
15772 // to the LHS type we would have gotten after unary conversions.
15773 if (CompResultTy->isFixedPointType())
15774 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15775
15776 if (ConvertHalfVec)
15777 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15778 OpLoc, CurFPFeatureOverrides());
15779
15781 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15782 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15783}
15784
15785/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15786/// operators are mixed in a way that suggests that the programmer forgot that
15787/// comparison operators have higher precedence. The most typical example of
15788/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15790 SourceLocation OpLoc, Expr *LHSExpr,
15791 Expr *RHSExpr) {
15792 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15793 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15794
15795 // Check that one of the sides is a comparison operator and the other isn't.
15796 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15797 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15798 if (isLeftComp == isRightComp)
15799 return;
15800
15801 // Bitwise operations are sometimes used as eager logical ops.
15802 // Don't diagnose this.
15803 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15804 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15805 if (isLeftBitwise || isRightBitwise)
15806 return;
15807
15808 SourceRange DiagRange = isLeftComp
15809 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15810 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15811 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15812 SourceRange ParensRange =
15813 isLeftComp
15814 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15815 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15816
15817 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15818 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15819 SuggestParentheses(Self, OpLoc,
15820 Self.PDiag(diag::note_precedence_silence) << OpStr,
15821 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15822 SuggestParentheses(Self, OpLoc,
15823 Self.PDiag(diag::note_precedence_bitwise_first)
15825 ParensRange);
15826}
15827
15828/// It accepts a '&&' expr that is inside a '||' one.
15829/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15830/// in parentheses.
15831static void
15833 BinaryOperator *Bop) {
15834 assert(Bop->getOpcode() == BO_LAnd);
15835 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15836 << Bop->getSourceRange() << OpLoc;
15838 Self.PDiag(diag::note_precedence_silence)
15839 << Bop->getOpcodeStr(),
15840 Bop->getSourceRange());
15841}
15842
15843/// Look for '&&' in the left hand of a '||' expr.
15845 Expr *LHSExpr, Expr *RHSExpr) {
15846 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15847 if (Bop->getOpcode() == BO_LAnd) {
15848 // If it's "string_literal && a || b" don't warn since the precedence
15849 // doesn't matter.
15850 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15851 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15852 } else if (Bop->getOpcode() == BO_LOr) {
15853 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15854 // If it's "a || b && string_literal || c" we didn't warn earlier for
15855 // "a || b && string_literal", but warn now.
15856 if (RBop->getOpcode() == BO_LAnd &&
15857 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15858 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15859 }
15860 }
15861 }
15862}
15863
15864/// Look for '&&' in the right hand of a '||' expr.
15866 Expr *LHSExpr, Expr *RHSExpr) {
15867 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15868 if (Bop->getOpcode() == BO_LAnd) {
15869 // If it's "a || b && string_literal" don't warn since the precedence
15870 // doesn't matter.
15871 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15872 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15873 }
15874 }
15875}
15876
15877/// Look for bitwise op in the left or right hand of a bitwise op with
15878/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15879/// the '&' expression in parentheses.
15881 SourceLocation OpLoc, Expr *SubExpr) {
15882 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15883 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15884 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15885 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15886 << Bop->getSourceRange() << OpLoc;
15887 SuggestParentheses(S, Bop->getOperatorLoc(),
15888 S.PDiag(diag::note_precedence_silence)
15889 << Bop->getOpcodeStr(),
15890 Bop->getSourceRange());
15891 }
15892 }
15893}
15894
15896 Expr *SubExpr, StringRef Shift) {
15897 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15898 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15899 StringRef Op = Bop->getOpcodeStr();
15900 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15901 << Bop->getSourceRange() << OpLoc << Shift << Op;
15902 SuggestParentheses(S, Bop->getOperatorLoc(),
15903 S.PDiag(diag::note_precedence_silence) << Op,
15904 Bop->getSourceRange());
15905 }
15906 }
15907}
15908
15910 Expr *LHSExpr, Expr *RHSExpr) {
15911 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15912 if (!OCE)
15913 return;
15914
15915 FunctionDecl *FD = OCE->getDirectCallee();
15916 if (!FD || !FD->isOverloadedOperator())
15917 return;
15918
15920 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15921 return;
15922
15923 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15924 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15925 << (Kind == OO_LessLess);
15927 S.PDiag(diag::note_precedence_silence)
15928 << (Kind == OO_LessLess ? "<<" : ">>"),
15929 OCE->getSourceRange());
15931 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15932 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15933}
15934
15935/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15936/// precedence.
15938 SourceLocation OpLoc, Expr *LHSExpr,
15939 Expr *RHSExpr){
15940 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15942 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15943
15944 // Diagnose "arg1 & arg2 | arg3"
15945 if ((Opc == BO_Or || Opc == BO_Xor) &&
15946 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15947 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15948 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15949 }
15950
15951 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15952 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15953 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15954 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15955 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15956 }
15957
15958 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15959 || Opc == BO_Shr) {
15960 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15961 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15962 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15963 }
15964
15965 // Warn on overloaded shift operators and comparisons, such as:
15966 // cout << 5 == 4;
15968 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15969}
15970
15972 tok::TokenKind Kind,
15973 Expr *LHSExpr, Expr *RHSExpr) {
15974 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15975 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15976 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15977
15978 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15979 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15980
15984
15985 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
15986 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
15987
15988 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15989}
15990
15992 UnresolvedSetImpl &Functions) {
15994 if (OverOp != OO_None && OverOp != OO_Equal)
15995 LookupOverloadedOperatorName(OverOp, S, Functions);
15996
15997 // In C++20 onwards, we may have a second operator to look up.
15998 if (getLangOpts().CPlusPlus20) {
16000 LookupOverloadedOperatorName(ExtraOp, S, Functions);
16001 }
16002}
16003
16004/// Build an overloaded binary operator expression in the given scope.
16007 Expr *LHS, Expr *RHS) {
16008 switch (Opc) {
16009 case BO_Assign:
16010 // In the non-overloaded case, we warn about self-assignment (x = x) for
16011 // both simple assignment and certain compound assignments where algebra
16012 // tells us the operation yields a constant result. When the operator is
16013 // overloaded, we can't do the latter because we don't want to assume that
16014 // those algebraic identities still apply; for example, a path-building
16015 // library might use operator/= to append paths. But it's still reasonable
16016 // to assume that simple assignment is just moving/copying values around
16017 // and so self-assignment is likely a bug.
16018 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
16019 [[fallthrough]];
16020 case BO_DivAssign:
16021 case BO_RemAssign:
16022 case BO_SubAssign:
16023 case BO_AndAssign:
16024 case BO_OrAssign:
16025 case BO_XorAssign:
16026 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
16027 break;
16028 default:
16029 break;
16030 }
16031
16032 // Find all of the overloaded operators visible from this point.
16033 UnresolvedSet<16> Functions;
16034 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
16035
16036 // Build the (potentially-overloaded, potentially-dependent)
16037 // binary operation.
16038 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
16039}
16040
16042 BinaryOperatorKind Opc, Expr *LHSExpr,
16043 Expr *RHSExpr, bool ForFoldExpression) {
16044 if (!LHSExpr || !RHSExpr)
16045 return ExprError();
16046
16047 // We want to end up calling one of SemaPseudoObject::checkAssignment
16048 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16049 // both expressions are overloadable or either is type-dependent),
16050 // or CreateBuiltinBinOp (in any other case). We also want to get
16051 // any placeholder types out of the way.
16052
16053 // Handle pseudo-objects in the LHS.
16054 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
16055 // Assignments with a pseudo-object l-value need special analysis.
16056 if (pty->getKind() == BuiltinType::PseudoObject &&
16058 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
16059
16060 // Don't resolve overloads if the other type is overloadable.
16061 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
16062 // We can't actually test that if we still have a placeholder,
16063 // though. Fortunately, none of the exceptions we see in that
16064 // code below are valid when the LHS is an overload set. Note
16065 // that an overload set can be dependently-typed, but it never
16066 // instantiates to having an overloadable type.
16067 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16068 if (resolvedRHS.isInvalid()) return ExprError();
16069 RHSExpr = resolvedRHS.get();
16070
16071 if (RHSExpr->isTypeDependent() ||
16072 RHSExpr->getType()->isOverloadableType())
16073 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16074 }
16075
16076 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16077 // template, diagnose the missing 'template' keyword instead of diagnosing
16078 // an invalid use of a bound member function.
16079 //
16080 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16081 // to C++1z [over.over]/1.4, but we already checked for that case above.
16082 if (Opc == BO_LT && inTemplateInstantiation() &&
16083 (pty->getKind() == BuiltinType::BoundMember ||
16084 pty->getKind() == BuiltinType::Overload)) {
16085 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
16086 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
16087 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
16088 return isa<FunctionTemplateDecl>(ND);
16089 })) {
16090 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
16091 : OE->getNameLoc(),
16092 diag::err_template_kw_missing)
16093 << OE->getName().getAsIdentifierInfo();
16094 return ExprError();
16095 }
16096 }
16097
16098 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
16099 if (LHS.isInvalid()) return ExprError();
16100 LHSExpr = LHS.get();
16101 }
16102
16103 // Handle pseudo-objects in the RHS.
16104 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
16105 // An overload in the RHS can potentially be resolved by the type
16106 // being assigned to.
16107 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
16108 if (getLangOpts().CPlusPlus &&
16109 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
16110 LHSExpr->getType()->isOverloadableType()))
16111 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16112
16113 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr,
16114 ForFoldExpression);
16115 }
16116
16117 // Don't resolve overloads if the other type is overloadable.
16118 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
16119 LHSExpr->getType()->isOverloadableType())
16120 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16121
16122 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
16123 if (!resolvedRHS.isUsable()) return ExprError();
16124 RHSExpr = resolvedRHS.get();
16125 }
16126
16127 if (getLangOpts().HLSL && (LHSExpr->getType()->isHLSLResourceRecord() ||
16128 LHSExpr->getType()->isHLSLResourceRecordArray())) {
16129 if (!HLSL().CheckResourceBinOp(Opc, LHSExpr, RHSExpr, OpLoc))
16130 return ExprError();
16131 }
16132
16133 if (getLangOpts().CPlusPlus) {
16134 bool CanOverloadBinOp =
16135 !getLangOpts().HLSL ||
16136 HLSL().canHaveOverloadedBinOp(LHSExpr->getType(), Opc) ||
16137 HLSL().canHaveOverloadedBinOp(RHSExpr->getType(), Opc);
16138 bool TypeDependent =
16139 LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent();
16140 bool Overloadable = LHSExpr->getType()->isOverloadableType() ||
16141 RHSExpr->getType()->isOverloadableType();
16142 if (CanOverloadBinOp && (TypeDependent || Overloadable))
16143 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
16144 }
16145
16146 if (getLangOpts().RecoveryAST &&
16147 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
16148 assert(!getLangOpts().CPlusPlus);
16149 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
16150 "Should only occur in error-recovery path.");
16152 // C [6.15.16] p3:
16153 // An assignment expression has the value of the left operand after the
16154 // assignment, but is not an lvalue.
16156 Context, LHSExpr, RHSExpr, Opc,
16158 OpLoc, CurFPFeatureOverrides());
16159 QualType ResultType;
16160 switch (Opc) {
16161 case BO_Assign:
16162 ResultType = LHSExpr->getType().getUnqualifiedType();
16163 break;
16164 case BO_LT:
16165 case BO_GT:
16166 case BO_LE:
16167 case BO_GE:
16168 case BO_EQ:
16169 case BO_NE:
16170 case BO_LAnd:
16171 case BO_LOr:
16172 // These operators have a fixed result type regardless of operands.
16173 ResultType = Context.IntTy;
16174 break;
16175 case BO_Comma:
16176 ResultType = RHSExpr->getType();
16177 break;
16178 default:
16179 ResultType = Context.DependentTy;
16180 break;
16181 }
16182 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
16183 VK_PRValue, OK_Ordinary, OpLoc,
16185 }
16186
16187 // Build a built-in binary operation.
16188 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr, ForFoldExpression);
16189}
16190
16192 if (T.isNull() || T->isDependentType())
16193 return false;
16194
16195 if (!Ctx.isPromotableIntegerType(T))
16196 return true;
16197
16198 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
16199}
16200
16202 UnaryOperatorKind Opc, Expr *InputExpr,
16203 bool IsAfterAmp) {
16204 ExprResult Input = InputExpr;
16207 QualType resultType;
16208 bool CanOverflow = false;
16209
16210 bool ConvertHalfVec = false;
16211 if (getLangOpts().OpenCL) {
16212 QualType Ty = InputExpr->getType();
16213 // The only legal unary operation for atomics is '&'.
16214 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
16215 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16216 // only with a builtin functions and therefore should be disallowed here.
16217 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
16218 || Ty->isBlockPointerType())) {
16219 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16220 << InputExpr->getType()
16221 << Input.get()->getSourceRange());
16222 }
16223 }
16224
16225 if (getLangOpts().HLSL && OpLoc.isValid()) {
16226 if (Opc == UO_AddrOf)
16227 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
16228 if (Opc == UO_Deref)
16229 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
16230 }
16231
16232 if (InputExpr->isTypeDependent() &&
16233 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
16234 resultType = Context.DependentTy;
16235 } else {
16236 switch (Opc) {
16237 case UO_PreInc:
16238 case UO_PreDec:
16239 case UO_PostInc:
16240 case UO_PostDec:
16241 resultType =
16242 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
16243 Opc == UO_PreInc || Opc == UO_PostInc,
16244 Opc == UO_PreInc || Opc == UO_PreDec);
16245 CanOverflow = isOverflowingIntegerType(Context, resultType);
16246 break;
16247 case UO_AddrOf:
16248 resultType = CheckAddressOfOperand(Input, OpLoc);
16249 CheckAddressOfNoDeref(InputExpr);
16250 RecordModifiableNonNullParam(*this, InputExpr);
16251 break;
16252 case UO_Deref: {
16254 if (Input.isInvalid())
16255 return ExprError();
16256 resultType =
16257 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
16258 break;
16259 }
16260 case UO_Plus:
16261 case UO_Minus:
16262 CanOverflow = Opc == UO_Minus &&
16264 Input = UsualUnaryConversions(Input.get());
16265 if (Input.isInvalid())
16266 return ExprError();
16267 // Unary plus and minus require promoting an operand of half vector to a
16268 // float vector and truncating the result back to a half vector. For now,
16269 // we do this only when HalfArgsAndReturns is set (that is, when the
16270 // target is arm or arm64).
16271 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
16272
16273 // If the operand is a half vector, promote it to a float vector.
16274 if (ConvertHalfVec)
16275 Input = convertVector(Input.get(), Context.FloatTy, *this);
16276 resultType = Input.get()->getType();
16277 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
16278 break;
16279 else if (resultType->isVectorType() &&
16280 // The z vector extensions don't allow + or - with bool vectors.
16281 (!Context.getLangOpts().ZVector ||
16282 resultType->castAs<VectorType>()->getVectorKind() !=
16284 break;
16285 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
16286 break;
16287 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
16288 Opc == UO_Plus && resultType->isPointerType())
16289 break;
16290
16291 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16292 << resultType << Input.get()->getSourceRange());
16293
16294 case UO_Not: // bitwise complement
16295 Input = UsualUnaryConversions(Input.get());
16296 if (Input.isInvalid())
16297 return ExprError();
16298 resultType = Input.get()->getType();
16299 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16300 if (resultType->isComplexType() || resultType->isComplexIntegerType())
16301 // C99 does not support '~' for complex conjugation.
16302 Diag(OpLoc, diag::ext_integer_complement_complex)
16303 << resultType << Input.get()->getSourceRange();
16304 else if (resultType->hasIntegerRepresentation())
16305 break;
16306 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
16307 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16308 // on vector float types.
16309 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16310 if (!T->isIntegerType())
16311 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16312 << resultType << Input.get()->getSourceRange());
16313 } else {
16314 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16315 << resultType << Input.get()->getSourceRange());
16316 }
16317 break;
16318
16319 case UO_LNot: // logical negation
16320 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16322 if (Input.isInvalid())
16323 return ExprError();
16324 resultType = Input.get()->getType();
16325
16326 // Though we still have to promote half FP to float...
16327 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
16328 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
16329 .get();
16330 resultType = Context.FloatTy;
16331 }
16332
16333 // WebAsembly tables can't be used in unary expressions.
16334 if (resultType->isPointerType() &&
16336 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16337 << resultType << Input.get()->getSourceRange());
16338 }
16339
16340 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
16341 // C99 6.5.3.3p1: ok, fallthrough;
16342 if (Context.getLangOpts().CPlusPlus) {
16343 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16344 // operand contextually converted to bool.
16345 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
16346 ScalarTypeToBooleanCastKind(resultType));
16347 } else if (Context.getLangOpts().OpenCL &&
16348 Context.getLangOpts().OpenCLVersion < 120) {
16349 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16350 // operate on scalar float types.
16351 if (!resultType->isIntegerType() && !resultType->isPointerType())
16352 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16353 << resultType << Input.get()->getSourceRange());
16354 }
16355 } else if (Context.getLangOpts().HLSL && resultType->isVectorType() &&
16356 !resultType->hasBooleanRepresentation()) {
16357 // HLSL unary logical 'not' behaves like C++, which states that the
16358 // operand is converted to bool and the result is bool, however HLSL
16359 // extends this property to vectors.
16360 const VectorType *VTy = resultType->castAs<VectorType>();
16361 resultType =
16362 Context.getExtVectorType(Context.BoolTy, VTy->getNumElements());
16363
16364 Input = ImpCastExprToType(
16365 Input.get(), resultType,
16367 .get();
16368 break;
16369 } else if (resultType->isExtVectorType()) {
16370 if (Context.getLangOpts().OpenCL &&
16371 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16372 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16373 // operate on vector float types.
16374 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
16375 if (!T->isIntegerType())
16376 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16377 << resultType << Input.get()->getSourceRange());
16378 }
16379 // Vector logical not returns the signed variant of the operand type.
16380 resultType = GetSignedVectorType(resultType);
16381 break;
16382 } else if (Context.getLangOpts().CPlusPlus &&
16383 resultType->isVectorType()) {
16384 const VectorType *VTy = resultType->castAs<VectorType>();
16385 if (VTy->getVectorKind() != VectorKind::Generic)
16386 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16387 << resultType << Input.get()->getSourceRange());
16388
16389 // Vector logical not returns the signed variant of the operand type.
16390 resultType = GetSignedVectorType(resultType);
16391 break;
16392 } else if (resultType == Context.AMDGPUFeaturePredicateTy) {
16393 resultType = Context.getLogicalOperationType();
16394 Input = AMDGPU().ExpandAMDGPUPredicateBuiltIn(InputExpr);
16395 break;
16396 } else {
16397 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
16398 << resultType << Input.get()->getSourceRange());
16399 }
16400
16401 // LNot always has type int. C99 6.5.3.3p5.
16402 // In C++, it's bool. C++ 5.3.1p8
16403 resultType = Context.getLogicalOperationType();
16404 break;
16405 case UO_Real:
16406 case UO_Imag:
16407 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
16408 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
16409 // ordinary complex l-values to ordinary l-values and all other values to
16410 // r-values.
16411 if (Input.isInvalid())
16412 return ExprError();
16413 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
16414 if (Input.get()->isGLValue() &&
16415 Input.get()->getObjectKind() == OK_Ordinary)
16416 VK = Input.get()->getValueKind();
16417 } else if (!getLangOpts().CPlusPlus) {
16418 // In C, a volatile scalar is read by __imag. In C++, it is not.
16419 Input = DefaultLvalueConversion(Input.get());
16420 }
16421 break;
16422 case UO_Extension:
16423 resultType = Input.get()->getType();
16424 VK = Input.get()->getValueKind();
16425 OK = Input.get()->getObjectKind();
16426 break;
16427 case UO_Coawait:
16428 // It's unnecessary to represent the pass-through operator co_await in the
16429 // AST; just return the input expression instead.
16430 assert(!Input.get()->getType()->isDependentType() &&
16431 "the co_await expression must be non-dependant before "
16432 "building operator co_await");
16433 return Input;
16434 }
16435 }
16436 if (resultType.isNull() || Input.isInvalid())
16437 return ExprError();
16438
16439 // Check for array bounds violations in the operand of the UnaryOperator,
16440 // except for the '*' and '&' operators that have to be handled specially
16441 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16442 // that are explicitly defined as valid by the standard).
16443 if (Opc != UO_AddrOf && Opc != UO_Deref)
16444 CheckArrayAccess(Input.get());
16445
16446 auto *UO =
16447 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
16448 OpLoc, CanOverflow, CurFPFeatureOverrides());
16449
16450 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
16451 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
16453 ExprEvalContexts.back().PossibleDerefs.insert(UO);
16454
16455 // Convert the result back to a half vector.
16456 if (ConvertHalfVec)
16457 return convertVector(UO, Context.HalfTy, *this);
16458 return UO;
16459}
16460
16462 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
16463 if (!DRE->getQualifier())
16464 return false;
16465
16466 ValueDecl *VD = DRE->getDecl();
16467 if (!VD->isCXXClassMember())
16468 return false;
16469
16471 return true;
16472 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16473 return Method->isImplicitObjectMemberFunction();
16474
16475 return false;
16476 }
16477
16478 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16479 if (!ULE->getQualifier())
16480 return false;
16481
16482 for (NamedDecl *D : ULE->decls()) {
16483 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16484 if (Method->isImplicitObjectMemberFunction())
16485 return true;
16486 } else {
16487 // Overload set does not contain methods.
16488 break;
16489 }
16490 }
16491
16492 return false;
16493 }
16494
16495 return false;
16496}
16497
16499 UnaryOperatorKind Opc, Expr *Input,
16500 bool IsAfterAmp) {
16501 // First things first: handle placeholders so that the
16502 // overloaded-operator check considers the right type.
16503 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16504 // Increment and decrement of pseudo-object references.
16505 if (pty->getKind() == BuiltinType::PseudoObject &&
16507 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
16508
16509 // extension is always a builtin operator.
16510 if (Opc == UO_Extension)
16511 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16512
16513 // & gets special logic for several kinds of placeholder.
16514 // The builtin code knows what to do.
16515 if (Opc == UO_AddrOf &&
16516 (pty->getKind() == BuiltinType::Overload ||
16517 pty->getKind() == BuiltinType::UnknownAny ||
16518 pty->getKind() == BuiltinType::BoundMember))
16519 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16520
16521 // Anything else needs to be handled now.
16523 if (Result.isInvalid()) return ExprError();
16524 Input = Result.get();
16525 }
16526
16527 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16529 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16530 // Find all of the overloaded operators visible from this point.
16531 UnresolvedSet<16> Functions;
16533 if (S && OverOp != OO_None)
16534 LookupOverloadedOperatorName(OverOp, S, Functions);
16535
16536 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16537 }
16538
16539 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16540}
16541
16543 Expr *Input, bool IsAfterAmp) {
16544 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16545 IsAfterAmp);
16546}
16547
16549 LabelDecl *TheDecl) {
16550 TheDecl->markUsed(Context);
16551 // Create the AST node. The address of a label always has type 'void*'.
16552 auto *Res = new (Context) AddrLabelExpr(
16553 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16554
16555 if (getCurFunction())
16556 getCurFunction()->AddrLabels.push_back(Res);
16557
16558 return Res;
16559}
16560
16563 // Make sure we diagnose jumping into a statement expression.
16565}
16566
16568 // Note that function is also called by TreeTransform when leaving a
16569 // StmtExpr scope without rebuilding anything.
16570
16573}
16574
16576 SourceLocation RPLoc) {
16577 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16578}
16579
16581 SourceLocation RPLoc, unsigned TemplateDepth) {
16582 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16583 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16584
16587 assert(!Cleanup.exprNeedsCleanups() &&
16588 "cleanups within StmtExpr not correctly bound!");
16590
16591 // FIXME: there are a variety of strange constraints to enforce here, for
16592 // example, it is not possible to goto into a stmt expression apparently.
16593 // More semantic analysis is needed.
16594
16595 // If there are sub-stmts in the compound stmt, take the type of the last one
16596 // as the type of the stmtexpr.
16597 QualType Ty = Context.VoidTy;
16598 bool StmtExprMayBindToTemp = false;
16599 if (!Compound->body_empty()) {
16600 if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
16601 if (const Expr *Value = LastStmt->getExprStmt()) {
16602 StmtExprMayBindToTemp = true;
16603 Ty = Value->getType();
16604 }
16605 }
16606 }
16607
16608 // FIXME: Check that expression type is complete/non-abstract; statement
16609 // expressions are not lvalues.
16610 Expr *ResStmtExpr =
16611 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16612 if (StmtExprMayBindToTemp)
16613 return MaybeBindToTemporary(ResStmtExpr);
16614 return ResStmtExpr;
16615}
16616
16618 if (ER.isInvalid())
16619 return ExprError();
16620
16621 // Do function/array conversion on the last expression, but not
16622 // lvalue-to-rvalue. However, initialize an unqualified type.
16624 if (ER.isInvalid())
16625 return ExprError();
16626 Expr *E = ER.get();
16627
16628 if (E->isTypeDependent())
16629 return E;
16630
16631 // In ARC, if the final expression ends in a consume, splice
16632 // the consume out and bind it later. In the alternate case
16633 // (when dealing with a retainable type), the result
16634 // initialization will create a produce. In both cases the
16635 // result will be +1, and we'll need to balance that out with
16636 // a bind.
16637 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16638 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16639 return Cast->getSubExpr();
16640
16641 // FIXME: Provide a better location for the initialization.
16645 SourceLocation(), E);
16646}
16647
16649 TypeSourceInfo *TInfo,
16650 ArrayRef<OffsetOfComponent> Components,
16651 SourceLocation RParenLoc) {
16652 QualType ArgTy = TInfo->getType();
16653 bool Dependent = ArgTy->isDependentType();
16654 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16655
16656 // We must have at least one component that refers to the type, and the first
16657 // one is known to be a field designator. Verify that the ArgTy represents
16658 // a struct/union/class.
16659 if (!Dependent && !ArgTy->isRecordType())
16660 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16661 << ArgTy << TypeRange);
16662
16663 // Type must be complete per C99 7.17p3 because a declaring a variable
16664 // with an incomplete type would be ill-formed.
16665 if (!Dependent
16666 && RequireCompleteType(BuiltinLoc, ArgTy,
16667 diag::err_offsetof_incomplete_type, TypeRange))
16668 return ExprError();
16669
16670 bool DidWarnAboutNonPOD = false;
16671 QualType CurrentType = ArgTy;
16674 for (const OffsetOfComponent &OC : Components) {
16675 if (OC.isBrackets) {
16676 // Offset of an array sub-field. TODO: Should we allow vector elements?
16677 if (!CurrentType->isDependentType()) {
16678 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16679 if(!AT)
16680 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16681 << CurrentType);
16682 CurrentType = AT->getElementType();
16683 } else
16684 CurrentType = Context.DependentTy;
16685
16686 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16687 if (IdxRval.isInvalid())
16688 return ExprError();
16689 Expr *Idx = IdxRval.get();
16690
16691 // The expression must be an integral expression.
16692 // FIXME: An integral constant expression?
16693 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16694 !Idx->getType()->isIntegerType())
16695 return ExprError(
16696 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16697 << Idx->getSourceRange());
16698
16699 // Record this array index.
16700 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16701 Exprs.push_back(Idx);
16702 continue;
16703 }
16704
16705 // Offset of a field.
16706 if (CurrentType->isDependentType()) {
16707 // We have the offset of a field, but we can't look into the dependent
16708 // type. Just record the identifier of the field.
16709 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16710 CurrentType = Context.DependentTy;
16711 continue;
16712 }
16713
16714 // We need to have a complete type to look into.
16715 if (RequireCompleteType(OC.LocStart, CurrentType,
16716 diag::err_offsetof_incomplete_type))
16717 return ExprError();
16718
16719 // Look for the designated field.
16720 auto *RD = CurrentType->getAsRecordDecl();
16721 if (!RD)
16722 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16723 << CurrentType);
16724
16725 // C++ [lib.support.types]p5:
16726 // The macro offsetof accepts a restricted set of type arguments in this
16727 // International Standard. type shall be a POD structure or a POD union
16728 // (clause 9).
16729 // C++11 [support.types]p4:
16730 // If type is not a standard-layout class (Clause 9), the results are
16731 // undefined.
16732 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16733 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16734 unsigned DiagID =
16735 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16736 : diag::ext_offsetof_non_pod_type;
16737
16738 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16739 Diag(BuiltinLoc, DiagID)
16740 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16741 DidWarnAboutNonPOD = true;
16742 }
16743 }
16744
16745 // Look for the field.
16746 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16747 LookupQualifiedName(R, RD);
16748 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16749 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16750 if (!MemberDecl) {
16751 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16752 MemberDecl = IndirectMemberDecl->getAnonField();
16753 }
16754
16755 if (!MemberDecl) {
16756 // Lookup could be ambiguous when looking up a placeholder variable
16757 // __builtin_offsetof(S, _).
16758 // In that case we would already have emitted a diagnostic
16759 if (!R.isAmbiguous())
16760 Diag(BuiltinLoc, diag::err_no_member)
16761 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16762 return ExprError();
16763 }
16764
16765 // C99 7.17p3:
16766 // (If the specified member is a bit-field, the behavior is undefined.)
16767 //
16768 // We diagnose this as an error.
16769 if (MemberDecl->isBitField()) {
16770 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16771 << MemberDecl->getDeclName()
16772 << SourceRange(BuiltinLoc, RParenLoc);
16773 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16774 return ExprError();
16775 }
16776
16777 RecordDecl *Parent = MemberDecl->getParent();
16778 if (IndirectMemberDecl)
16779 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16780
16781 // If the member was found in a base class, introduce OffsetOfNodes for
16782 // the base class indirections.
16783 CXXBasePaths Paths;
16784 if (IsDerivedFrom(OC.LocStart, CurrentType,
16785 Context.getCanonicalTagType(Parent), Paths)) {
16786 if (Paths.getDetectedVirtual()) {
16787 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16788 << MemberDecl->getDeclName()
16789 << SourceRange(BuiltinLoc, RParenLoc);
16790 return ExprError();
16791 }
16792
16793 CXXBasePath &Path = Paths.front();
16794 for (const CXXBasePathElement &B : Path)
16795 Comps.push_back(OffsetOfNode(B.Base));
16796 }
16797
16798 if (IndirectMemberDecl) {
16799 for (auto *FI : IndirectMemberDecl->chain()) {
16800 assert(isa<FieldDecl>(FI));
16801 Comps.push_back(OffsetOfNode(OC.LocStart,
16802 cast<FieldDecl>(FI), OC.LocEnd));
16803 }
16804 } else
16805 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16806
16807 CurrentType = MemberDecl->getType().getNonReferenceType();
16808 }
16809
16810 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16811 Comps, Exprs, RParenLoc);
16812}
16813
16815 SourceLocation BuiltinLoc,
16817 ParsedType ParsedArgTy,
16818 ArrayRef<OffsetOfComponent> Components,
16819 SourceLocation RParenLoc) {
16820
16821 TypeSourceInfo *ArgTInfo;
16822 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16823 if (ArgTy.isNull())
16824 return ExprError();
16825
16826 if (!ArgTInfo)
16827 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16828
16829 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16830}
16831
16832
16834 Expr *CondExpr,
16835 Expr *LHSExpr, Expr *RHSExpr,
16836 SourceLocation RPLoc) {
16837 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16838
16841 QualType resType;
16842 bool CondIsTrue = false;
16843 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16844 resType = Context.DependentTy;
16845 } else {
16846 // The conditional expression is required to be a constant expression.
16847 llvm::APSInt condEval(32);
16849 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16850 if (CondICE.isInvalid())
16851 return ExprError();
16852 CondExpr = CondICE.get();
16853 CondIsTrue = condEval.getZExtValue();
16854
16855 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16856 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16857
16858 resType = ActiveExpr->getType();
16859 VK = ActiveExpr->getValueKind();
16860 OK = ActiveExpr->getObjectKind();
16861 }
16862
16863 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16864 resType, VK, OK, RPLoc, CondIsTrue);
16865}
16866
16867//===----------------------------------------------------------------------===//
16868// Clang Extensions.
16869//===----------------------------------------------------------------------===//
16870
16871void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16873
16874 if (LangOpts.CPlusPlus) {
16876 Decl *ManglingContextDecl;
16877 std::tie(MCtx, ManglingContextDecl) =
16878 getCurrentMangleNumberContext(Block->getDeclContext());
16879 if (MCtx) {
16880 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16881 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16882 }
16883 }
16884
16885 PushBlockScope(CurScope, Block);
16886 CurContext->addDecl(Block);
16887 if (CurScope)
16888 PushDeclContext(CurScope, Block);
16889 else
16890 CurContext = Block;
16891
16893
16894 // Enter a new evaluation context to insulate the block from any
16895 // cleanups from the enclosing full-expression.
16898}
16899
16901 Scope *CurScope) {
16902 assert(ParamInfo.getIdentifier() == nullptr &&
16903 "block-id should have no identifier!");
16904 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16905 BlockScopeInfo *CurBlock = getCurBlock();
16906
16907 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16908 QualType T = Sig->getType();
16910
16911 // GetTypeForDeclarator always produces a function type for a block
16912 // literal signature. Furthermore, it is always a FunctionProtoType
16913 // unless the function was written with a typedef.
16914 assert(T->isFunctionType() &&
16915 "GetTypeForDeclarator made a non-function block signature");
16916
16917 // Look for an explicit signature in that function type.
16918 FunctionProtoTypeLoc ExplicitSignature;
16919
16920 if ((ExplicitSignature = Sig->getTypeLoc()
16922
16923 // Check whether that explicit signature was synthesized by
16924 // GetTypeForDeclarator. If so, don't save that as part of the
16925 // written signature.
16926 if (ExplicitSignature.getLocalRangeBegin() ==
16927 ExplicitSignature.getLocalRangeEnd()) {
16928 // This would be much cheaper if we stored TypeLocs instead of
16929 // TypeSourceInfos.
16930 TypeLoc Result = ExplicitSignature.getReturnLoc();
16931 unsigned Size = Result.getFullDataSize();
16932 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16933 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16934
16935 ExplicitSignature = FunctionProtoTypeLoc();
16936 }
16937 }
16938
16939 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16940 CurBlock->FunctionType = T;
16941
16942 const auto *Fn = T->castAs<FunctionType>();
16943 QualType RetTy = Fn->getReturnType();
16944 bool isVariadic =
16945 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16946
16947 CurBlock->TheDecl->setIsVariadic(isVariadic);
16948
16949 // Context.DependentTy is used as a placeholder for a missing block
16950 // return type. TODO: what should we do with declarators like:
16951 // ^ * { ... }
16952 // If the answer is "apply template argument deduction"....
16953 if (RetTy != Context.DependentTy) {
16954 CurBlock->ReturnType = RetTy;
16955 CurBlock->TheDecl->setBlockMissingReturnType(false);
16956 CurBlock->HasImplicitReturnType = false;
16957 }
16958
16959 // Push block parameters from the declarator if we had them.
16961 if (ExplicitSignature) {
16962 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16963 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16964 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16965 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16966 // Diagnose this as an extension in C17 and earlier.
16967 if (!getLangOpts().C23)
16968 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16969 }
16970 Params.push_back(Param);
16971 }
16972
16973 // Fake up parameter variables if we have a typedef, like
16974 // ^ fntype { ... }
16975 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16976 for (const auto &I : Fn->param_types()) {
16978 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16979 Params.push_back(Param);
16980 }
16981 }
16982
16983 // Set the parameters on the block decl.
16984 if (!Params.empty()) {
16985 CurBlock->TheDecl->setParams(Params);
16987 /*CheckParameterNames=*/false);
16988 }
16989
16990 // Finally we can process decl attributes.
16991 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16992
16993 // Put the parameter variables in scope.
16994 for (auto *AI : CurBlock->TheDecl->parameters()) {
16995 AI->setOwningFunction(CurBlock->TheDecl);
16996
16997 // If this has an identifier, add it to the scope stack.
16998 if (AI->getIdentifier()) {
16999 CheckShadow(CurBlock->TheScope, AI);
17000
17001 PushOnScopeChains(AI, CurBlock->TheScope);
17002 }
17003
17004 if (AI->isInvalidDecl())
17005 CurBlock->TheDecl->setInvalidDecl();
17006 }
17007}
17008
17009void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
17010 // Leave the expression-evaluation context.
17013
17014 // Pop off CurBlock, handle nested blocks.
17017}
17018
17020 Stmt *Body, Scope *CurScope) {
17021 // If blocks are disabled, emit an error.
17022 if (!LangOpts.Blocks)
17023 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
17024
17025 // Leave the expression-evaluation context.
17028 assert(!Cleanup.exprNeedsCleanups() &&
17029 "cleanups within block not correctly bound!");
17031
17033 BlockDecl *BD = BSI->TheDecl;
17034
17036
17037 if (BSI->HasImplicitReturnType)
17039
17040 QualType RetTy = Context.VoidTy;
17041 if (!BSI->ReturnType.isNull())
17042 RetTy = BSI->ReturnType;
17043
17044 bool NoReturn = BD->hasAttr<NoReturnAttr>();
17045 QualType BlockTy;
17046
17047 // If the user wrote a function type in some form, try to use that.
17048 if (!BSI->FunctionType.isNull()) {
17049 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
17050
17051 FunctionType::ExtInfo Ext = FTy->getExtInfo();
17052 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
17053
17054 // Turn protoless block types into nullary block types.
17055 if (isa<FunctionNoProtoType>(FTy)) {
17057 EPI.ExtInfo = Ext;
17058 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17059
17060 // Otherwise, if we don't need to change anything about the function type,
17061 // preserve its sugar structure.
17062 } else if (FTy->getReturnType() == RetTy &&
17063 (!NoReturn || FTy->getNoReturnAttr())) {
17064 BlockTy = BSI->FunctionType;
17065
17066 // Otherwise, make the minimal modifications to the function type.
17067 } else {
17070 EPI.TypeQuals = Qualifiers();
17071 EPI.ExtInfo = Ext;
17072 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
17073 }
17074
17075 // If we don't have a function type, just build one from nothing.
17076 } else {
17078 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
17079 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
17080 }
17081
17083 BlockTy = Context.getBlockPointerType(BlockTy);
17084
17085 // If needed, diagnose invalid gotos and switches in the block.
17086 if (getCurFunction()->NeedsScopeChecking() &&
17087 !PP.isCodeCompletionEnabled())
17089
17090 BD->setBody(cast<CompoundStmt>(Body));
17091
17092 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
17094
17095 // Try to apply the named return value optimization. We have to check again
17096 // if we can do this, though, because blocks keep return statements around
17097 // to deduce an implicit return type.
17098 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
17099 !BD->isDependentContext())
17100 computeNRVO(Body, BSI);
17101
17107
17109
17110 // Set the captured variables on the block.
17112 for (Capture &Cap : BSI->Captures) {
17113 if (Cap.isInvalid() || Cap.isThisCapture())
17114 continue;
17115 // Cap.getVariable() is always a VarDecl because
17116 // blocks cannot capture structured bindings or other ValueDecl kinds.
17117 auto *Var = cast<VarDecl>(Cap.getVariable());
17118 Expr *CopyExpr = nullptr;
17119 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
17120 if (auto *Record = Cap.getCaptureType()->getAsCXXRecordDecl()) {
17121 // The capture logic needs the destructor, so make sure we mark it.
17122 // Usually this is unnecessary because most local variables have
17123 // their destructors marked at declaration time, but parameters are
17124 // an exception because it's technically only the call site that
17125 // actually requires the destructor.
17126 if (isa<ParmVarDecl>(Var))
17128
17129 // Enter a separate potentially-evaluated context while building block
17130 // initializers to isolate their cleanups from those of the block
17131 // itself.
17132 // FIXME: Is this appropriate even when the block itself occurs in an
17133 // unevaluated operand?
17136
17137 SourceLocation Loc = Cap.getLocation();
17138
17140 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
17141
17142 // According to the blocks spec, the capture of a variable from
17143 // the stack requires a const copy constructor. This is not true
17144 // of the copy/move done to move a __block variable to the heap.
17145 if (!Result.isInvalid() &&
17146 !Result.get()->getType().isConstQualified()) {
17148 Result.get()->getType().withConst(),
17149 CK_NoOp, VK_LValue);
17150 }
17151
17152 if (!Result.isInvalid()) {
17154 InitializedEntity::InitializeBlock(Var->getLocation(),
17155 Cap.getCaptureType()),
17156 Loc, Result.get());
17157 }
17158
17159 // Build a full-expression copy expression if initialization
17160 // succeeded and used a non-trivial constructor. Recover from
17161 // errors by pretending that the copy isn't necessary.
17162 if (!Result.isInvalid() &&
17163 !cast<CXXConstructExpr>(Result.get())->getConstructor()
17164 ->isTrivial()) {
17166 CopyExpr = Result.get();
17167 }
17168 }
17169 }
17170
17171 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
17172 CopyExpr);
17173 Captures.push_back(NewCap);
17174 }
17175 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
17176
17177 // Pop the block scope now but keep it alive to the end of this function.
17179 AnalysisWarnings.getPolicyInEffectAt(Body->getEndLoc());
17180 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
17181
17182 BlockExpr *Result = new (Context)
17183 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
17184
17185 // If the block isn't obviously global, i.e. it captures anything at
17186 // all, then we need to do a few things in the surrounding context:
17187 if (Result->getBlockDecl()->hasCaptures()) {
17188 // First, this expression has a new cleanup object.
17189 ExprCleanupObjects.push_back(Result->getBlockDecl());
17190 Cleanup.setExprNeedsCleanups(true);
17191
17192 // It also gets a branch-protected scope if any of the captured
17193 // variables needs destruction.
17194 for (const auto &CI : Result->getBlockDecl()->captures()) {
17195 const VarDecl *var = CI.getVariable();
17196 if (var->getType().isDestructedType() != QualType::DK_none) {
17198 break;
17199 }
17200 }
17201 }
17202
17203 if (getCurFunction())
17204 getCurFunction()->addBlock(BD);
17205
17206 // This can happen if the block's return type is deduced, but
17207 // the return expression is invalid.
17208 if (BD->isInvalidDecl())
17209 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
17210 {Result}, Result->getType());
17211 return Result;
17212}
17213
17215 SourceLocation RPLoc) {
17216 TypeSourceInfo *TInfo;
17217 GetTypeFromParser(Ty, &TInfo);
17218 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
17219}
17220
17222 Expr *E, TypeSourceInfo *TInfo,
17223 SourceLocation RPLoc) {
17224 Expr *OrigExpr = E;
17225 bool IsMS = false;
17226
17227 // CUDA device global function does not support varargs.
17228 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
17229 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
17232 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
17233 }
17234 }
17235
17236 // NVPTX does not support va_arg expression.
17237 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
17238 Context.getTargetInfo().getTriple().isNVPTX())
17239 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
17240
17241 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17242 // as Microsoft ABI on an actual Microsoft platform, where
17243 // __builtin_ms_va_list and __builtin_va_list are the same.)
17244 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
17245 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
17246 QualType MSVaListType = Context.getBuiltinMSVaListType();
17247 if (Context.hasSameType(MSVaListType, E->getType())) {
17248 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
17249 return ExprError();
17250 IsMS = true;
17251 }
17252 }
17253
17254 // Get the va_list type
17255 QualType VaListType = Context.getBuiltinVaListType();
17256 if (!IsMS) {
17257 if (VaListType->isArrayType()) {
17258 // Deal with implicit array decay; for example, on x86-64,
17259 // va_list is an array, but it's supposed to decay to
17260 // a pointer for va_arg.
17261 VaListType = Context.getArrayDecayedType(VaListType);
17262 // Make sure the input expression also decays appropriately.
17264 if (Result.isInvalid())
17265 return ExprError();
17266 E = Result.get();
17267 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
17268 // If va_list is a record type and we are compiling in C++ mode,
17269 // check the argument using reference binding.
17271 Context, Context.getLValueReferenceType(VaListType), false);
17273 if (Init.isInvalid())
17274 return ExprError();
17275 E = Init.getAs<Expr>();
17276 } else {
17277 // Otherwise, the va_list argument must be an l-value because
17278 // it is modified by va_arg.
17279 if (!E->isTypeDependent() &&
17280 CheckForModifiableLvalue(E, BuiltinLoc, *this))
17281 return ExprError();
17282 }
17283 }
17284
17285 if (!IsMS && !E->isTypeDependent() &&
17286 !Context.hasSameType(VaListType, E->getType()))
17287 return ExprError(
17288 Diag(E->getBeginLoc(),
17289 diag::err_first_argument_to_va_arg_not_of_type_va_list)
17290 << OrigExpr->getType() << E->getSourceRange());
17291
17292 if (!TInfo->getType()->isDependentType()) {
17293 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
17294 diag::err_second_parameter_to_va_arg_incomplete,
17295 TInfo->getTypeLoc()))
17296 return ExprError();
17297
17299 TInfo->getType(),
17300 diag::err_second_parameter_to_va_arg_abstract,
17301 TInfo->getTypeLoc()))
17302 return ExprError();
17303
17304 if (!TInfo->getType().isPODType(Context)) {
17305 Diag(TInfo->getTypeLoc().getBeginLoc(),
17306 TInfo->getType()->isObjCLifetimeType()
17307 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17308 : diag::warn_second_parameter_to_va_arg_not_pod)
17309 << TInfo->getType()
17310 << TInfo->getTypeLoc().getSourceRange();
17311 }
17312
17313 if (TInfo->getType()->isArrayType()) {
17315 PDiag(diag::warn_second_parameter_to_va_arg_array)
17316 << TInfo->getType()
17317 << TInfo->getTypeLoc().getSourceRange());
17318 }
17319
17320 // Check for va_arg where arguments of the given type will be promoted
17321 // (i.e. this va_arg is guaranteed to have undefined behavior).
17322 QualType PromoteType;
17323 if (Context.isPromotableIntegerType(TInfo->getType())) {
17324 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
17325 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17326 // and C23 7.16.1.1p2 says, in part:
17327 // If type is not compatible with the type of the actual next argument
17328 // (as promoted according to the default argument promotions), the
17329 // behavior is undefined, except for the following cases:
17330 // - both types are pointers to qualified or unqualified versions of
17331 // compatible types;
17332 // - one type is compatible with a signed integer type, the other
17333 // type is compatible with the corresponding unsigned integer type,
17334 // and the value is representable in both types;
17335 // - one type is pointer to qualified or unqualified void and the
17336 // other is a pointer to a qualified or unqualified character type;
17337 // - or, the type of the next argument is nullptr_t and type is a
17338 // pointer type that has the same representation and alignment
17339 // requirements as a pointer to a character type.
17340 // Given that type compatibility is the primary requirement (ignoring
17341 // qualifications), you would think we could call typesAreCompatible()
17342 // directly to test this. However, in C++, that checks for *same type*,
17343 // which causes false positives when passing an enumeration type to
17344 // va_arg. Instead, get the underlying type of the enumeration and pass
17345 // that.
17346 QualType UnderlyingType = TInfo->getType();
17347 if (const auto *ED = UnderlyingType->getAsEnumDecl())
17348 UnderlyingType = ED->getIntegerType();
17349 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17350 /*CompareUnqualified*/ true))
17351 PromoteType = QualType();
17352
17353 // If the types are still not compatible, we need to test whether the
17354 // promoted type and the underlying type are the same except for
17355 // signedness. Ask the AST for the correctly corresponding type and see
17356 // if that's compatible.
17357 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
17358 PromoteType->isUnsignedIntegerType() !=
17359 UnderlyingType->isUnsignedIntegerType()) {
17360 UnderlyingType =
17361 UnderlyingType->isUnsignedIntegerType()
17362 ? Context.getCorrespondingSignedType(UnderlyingType)
17363 : Context.getCorrespondingUnsignedType(UnderlyingType);
17364 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
17365 /*CompareUnqualified*/ true))
17366 PromoteType = QualType();
17367 }
17368 }
17369 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
17370 PromoteType = Context.DoubleTy;
17371 if (!PromoteType.isNull())
17373 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
17374 << TInfo->getType()
17375 << PromoteType
17376 << TInfo->getTypeLoc().getSourceRange());
17377 }
17378
17380 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
17381}
17382
17384 // The type of __null will be int or long, depending on the size of
17385 // pointers on the target.
17386 QualType Ty;
17387 unsigned pw = Context.getTargetInfo().getPointerWidth(LangAS::Default);
17388 if (pw == Context.getTargetInfo().getIntWidth())
17389 Ty = Context.IntTy;
17390 else if (pw == Context.getTargetInfo().getLongWidth())
17391 Ty = Context.LongTy;
17392 else if (pw == Context.getTargetInfo().getLongLongWidth())
17393 Ty = Context.LongLongTy;
17394 else {
17395 llvm_unreachable("I don't know size of pointer!");
17396 }
17397
17398 return new (Context) GNUNullExpr(Ty, TokenLoc);
17399}
17400
17402 CXXRecordDecl *ImplDecl = nullptr;
17403
17404 // Fetch the std::source_location::__impl decl.
17405 if (NamespaceDecl *Std = S.getStdNamespace()) {
17406 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
17408 if (S.LookupQualifiedName(ResultSL, Std)) {
17409 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
17410 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
17412 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
17413 S.LookupQualifiedName(ResultImpl, SLDecl)) {
17414 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
17415 }
17416 }
17417 }
17418 }
17419
17420 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
17421 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
17422 return nullptr;
17423 }
17424
17425 // Verify that __impl is a trivial struct type, with no base classes, and with
17426 // only the four expected fields.
17427 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
17428 ImplDecl->getNumBases() != 0) {
17429 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17430 return nullptr;
17431 }
17432
17433 unsigned Count = 0;
17434 for (FieldDecl *F : ImplDecl->fields()) {
17435 StringRef Name = F->getName();
17436
17437 if (Name == "_M_file_name") {
17438 if (F->getType() !=
17440 break;
17441 Count++;
17442 } else if (Name == "_M_function_name") {
17443 if (F->getType() !=
17445 break;
17446 Count++;
17447 } else if (Name == "_M_line") {
17448 if (!F->getType()->isIntegerType())
17449 break;
17450 Count++;
17451 } else if (Name == "_M_column") {
17452 if (!F->getType()->isIntegerType())
17453 break;
17454 Count++;
17455 } else {
17456 Count = 100; // invalid
17457 break;
17458 }
17459 }
17460 if (Count != 4) {
17461 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
17462 return nullptr;
17463 }
17464
17465 return ImplDecl;
17466}
17467
17469 SourceLocation BuiltinLoc,
17470 SourceLocation RPLoc) {
17471 QualType ResultTy;
17472 switch (Kind) {
17477 QualType ArrTy = Context.getStringLiteralArrayType(Context.CharTy, 0);
17478 ResultTy =
17479 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17480 break;
17481 }
17484 ResultTy = Context.UnsignedIntTy;
17485 break;
17489 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17491 return ExprError();
17492 }
17493 ResultTy = Context.getPointerType(
17494 Context.getCanonicalTagType(StdSourceLocationImplDecl).withConst());
17495 break;
17496 }
17497
17498 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17499}
17500
17502 SourceLocation BuiltinLoc,
17503 SourceLocation RPLoc,
17504 DeclContext *ParentContext) {
17505 return new (Context)
17506 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17507}
17508
17510 StringLiteral *BinaryData, StringRef FileName) {
17512 Data->BinaryData = BinaryData;
17513 Data->FileName = FileName;
17514 return new (Context)
17515 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
17516 Data->getDataElementCount());
17517}
17518
17520 const Expr *SrcExpr) {
17521 if (!DstType->isFunctionPointerType() ||
17522 !SrcExpr->getType()->isFunctionType())
17523 return false;
17524
17525 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17526 if (!DRE)
17527 return false;
17528
17529 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17530 if (!FD)
17531 return false;
17532
17534 /*Complain=*/true,
17535 SrcExpr->getBeginLoc());
17536}
17537
17539 SourceLocation Loc,
17540 QualType DstType, QualType SrcType,
17541 Expr *SrcExpr, AssignmentAction Action,
17542 bool *Complained) {
17543 if (Complained)
17544 *Complained = false;
17545
17546 // Decode the result (notice that AST's are still created for extensions).
17547 bool CheckInferredResultType = false;
17548 bool isInvalid = false;
17549 unsigned DiagKind = 0;
17550 ConversionFixItGenerator ConvHints;
17551 bool MayHaveConvFixit = false;
17552 bool MayHaveFunctionDiff = false;
17553 const ObjCInterfaceDecl *IFace = nullptr;
17554 const ObjCProtocolDecl *PDecl = nullptr;
17555
17556 switch (ConvTy) {
17558 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17559 return false;
17561 // Still a valid conversion, but we may want to diagnose for C++
17562 // compatibility reasons.
17563 DiagKind = diag::warn_compatible_implicit_pointer_conv;
17564 break;
17566 if (getLangOpts().CPlusPlus) {
17567 DiagKind = diag::err_typecheck_convert_pointer_int;
17568 isInvalid = true;
17569 } else {
17570 DiagKind = diag::ext_typecheck_convert_pointer_int;
17571 }
17572 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17573 MayHaveConvFixit = true;
17574 break;
17576 if (getLangOpts().CPlusPlus) {
17577 DiagKind = diag::err_typecheck_convert_int_pointer;
17578 isInvalid = true;
17579 } else {
17580 DiagKind = diag::ext_typecheck_convert_int_pointer;
17581 }
17582 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17583 MayHaveConvFixit = true;
17584 break;
17586 DiagKind =
17587 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17588 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17589 MayHaveConvFixit = true;
17590 break;
17592 if (getLangOpts().CPlusPlus) {
17593 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17594 isInvalid = true;
17595 } else {
17596 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17597 }
17598 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17599 MayHaveConvFixit = true;
17600 break;
17603 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17604 } else if (getLangOpts().CPlusPlus) {
17605 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17606 isInvalid = true;
17607 } else {
17608 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17609 }
17610 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17611 SrcType->isObjCObjectPointerType();
17612 if (CheckInferredResultType) {
17613 SrcType = SrcType.getUnqualifiedType();
17614 DstType = DstType.getUnqualifiedType();
17615 } else {
17616 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17617 }
17618 MayHaveConvFixit = true;
17619 break;
17621 if (getLangOpts().CPlusPlus) {
17622 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17623 isInvalid = true;
17624 } else {
17625 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17626 }
17627 break;
17629 if (getLangOpts().CPlusPlus) {
17630 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17631 isInvalid = true;
17632 } else {
17633 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17634 }
17635 break;
17637 // Perform decay if necessary.
17638 if (SrcType->canDecayToPointerType())
17639 SrcType = Context.getDecayedType(SrcType);
17640
17641 isInvalid = true;
17642
17643 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17644 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17645 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17646 DiagKind = diag::err_typecheck_incompatible_address_space;
17647 break;
17648 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17649 DiagKind = diag::err_typecheck_incompatible_ownership;
17650 break;
17651 } else if (!lhq.getPointerAuth().isEquivalent(rhq.getPointerAuth())) {
17652 DiagKind = diag::err_typecheck_incompatible_ptrauth;
17653 break;
17654 }
17655
17656 llvm_unreachable("unknown error case for discarding qualifiers!");
17657 // fallthrough
17658 }
17660 if (SrcType->isArrayType())
17661 SrcType = Context.getArrayDecayedType(SrcType);
17662
17663 DiagKind = diag::ext_typecheck_convert_discards_overflow_behavior;
17664 break;
17666 // If the qualifiers lost were because we were applying the
17667 // (deprecated) C++ conversion from a string literal to a char*
17668 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17669 // Ideally, this check would be performed in
17670 // checkPointerTypesForAssignment. However, that would require a
17671 // bit of refactoring (so that the second argument is an
17672 // expression, rather than a type), which should be done as part
17673 // of a larger effort to fix checkPointerTypesForAssignment for
17674 // C++ semantics.
17675 if (getLangOpts().CPlusPlus &&
17677 return false;
17678 if (getLangOpts().CPlusPlus) {
17679 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17680 isInvalid = true;
17681 } else {
17682 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17683 }
17684
17685 break;
17687 if (getLangOpts().CPlusPlus) {
17688 isInvalid = true;
17689 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17690 } else {
17691 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17692 }
17693 break;
17695 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17696 isInvalid = true;
17697 break;
17699 DiagKind = diag::err_int_to_block_pointer;
17700 isInvalid = true;
17701 break;
17703 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17704 isInvalid = true;
17705 break;
17707 if (SrcType->isObjCQualifiedIdType()) {
17708 const ObjCObjectPointerType *srcOPT =
17709 SrcType->castAs<ObjCObjectPointerType>();
17710 for (auto *srcProto : srcOPT->quals()) {
17711 PDecl = srcProto;
17712 break;
17713 }
17714 if (const ObjCInterfaceType *IFaceT =
17716 IFace = IFaceT->getDecl();
17717 }
17718 else if (DstType->isObjCQualifiedIdType()) {
17719 const ObjCObjectPointerType *dstOPT =
17720 DstType->castAs<ObjCObjectPointerType>();
17721 for (auto *dstProto : dstOPT->quals()) {
17722 PDecl = dstProto;
17723 break;
17724 }
17725 if (const ObjCInterfaceType *IFaceT =
17727 IFace = IFaceT->getDecl();
17728 }
17729 if (getLangOpts().CPlusPlus) {
17730 DiagKind = diag::err_incompatible_qualified_id;
17731 isInvalid = true;
17732 } else {
17733 DiagKind = diag::warn_incompatible_qualified_id;
17734 }
17735 break;
17736 }
17738 if (getLangOpts().CPlusPlus) {
17739 DiagKind = diag::err_incompatible_vectors;
17740 isInvalid = true;
17741 } else {
17742 DiagKind = diag::warn_incompatible_vectors;
17743 }
17744 break;
17746 DiagKind = diag::err_arc_weak_unavailable_assign;
17747 isInvalid = true;
17748 break;
17750 return false;
17752 assert(!SrcType->isFunctionType() &&
17753 "Unexpected function type found in IncompatibleOBTKinds assignment");
17754 if (SrcType->canDecayToPointerType())
17755 SrcType = Context.getDecayedType(SrcType);
17756
17757 auto getOBTKindName = [](QualType Ty) -> StringRef {
17758 if (Ty->isPointerType())
17759 Ty = Ty->getPointeeType();
17760 if (const auto *OBT = Ty->getAs<OverflowBehaviorType>()) {
17761 return OBT->getBehaviorKind() ==
17762 OverflowBehaviorType::OverflowBehaviorKind::Trap
17763 ? "__ob_trap"
17764 : "__ob_wrap";
17765 }
17766 llvm_unreachable("OBT kind unhandled");
17767 };
17768
17769 Diag(Loc, diag::err_incompatible_obt_kinds_assignment)
17770 << DstType << SrcType << getOBTKindName(DstType)
17771 << getOBTKindName(SrcType);
17772 isInvalid = true;
17773 return true;
17774 }
17776 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17777 if (Complained)
17778 *Complained = true;
17779 return true;
17780 }
17781
17782 DiagKind = diag::err_typecheck_convert_incompatible;
17783 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17784 MayHaveConvFixit = true;
17785 isInvalid = true;
17786 MayHaveFunctionDiff = true;
17787 break;
17788 }
17789
17790 QualType FirstType, SecondType;
17791 switch (Action) {
17794 // The destination type comes first.
17795 FirstType = DstType;
17796 SecondType = SrcType;
17797 break;
17798
17805 // The source type comes first.
17806 FirstType = SrcType;
17807 SecondType = DstType;
17808 break;
17809 }
17810
17811 PartialDiagnostic FDiag = PDiag(DiagKind);
17812 AssignmentAction ActionForDiag = Action;
17814 ActionForDiag = AssignmentAction::Passing;
17815
17816 FDiag << FirstType << SecondType << ActionForDiag
17817 << SrcExpr->getSourceRange();
17818
17819 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17820 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17821 auto isPlainChar = [](const clang::Type *Type) {
17822 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17823 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17824 };
17825 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17826 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17827 }
17828
17829 // If we can fix the conversion, suggest the FixIts.
17830 if (!ConvHints.isNull()) {
17831 for (FixItHint &H : ConvHints.Hints)
17832 FDiag << H;
17833 }
17834
17835 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17836
17837 if (MayHaveFunctionDiff)
17838 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17839
17840 Diag(Loc, FDiag);
17841 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17842 DiagKind == diag::err_incompatible_qualified_id) &&
17843 PDecl && IFace && !IFace->hasDefinition())
17844 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17845 << IFace << PDecl;
17846
17847 if (SecondType == Context.OverloadTy)
17849 FirstType, /*TakingAddress=*/true);
17850
17851 if (CheckInferredResultType)
17853
17854 if (Action == AssignmentAction::Returning &&
17857
17858 if (Complained)
17859 *Complained = true;
17860 return isInvalid;
17861}
17862
17864 llvm::APSInt *Result,
17865 AllowFoldKind CanFold) {
17866 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17867 public:
17868 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17869 QualType T) override {
17870 return S.Diag(Loc, diag::err_ice_not_integral)
17871 << T << S.LangOpts.CPlusPlus;
17872 }
17873 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17874 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17875 }
17876 } Diagnoser;
17877
17878 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17879}
17880
17882 llvm::APSInt *Result,
17883 unsigned DiagID,
17884 AllowFoldKind CanFold) {
17885 class IDDiagnoser : public VerifyICEDiagnoser {
17886 unsigned DiagID;
17887
17888 public:
17889 IDDiagnoser(unsigned DiagID)
17890 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17891
17892 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17893 return S.Diag(Loc, DiagID);
17894 }
17895 } Diagnoser(DiagID);
17896
17897 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17898}
17899
17905
17908 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17909}
17910
17913 VerifyICEDiagnoser &Diagnoser,
17914 AllowFoldKind CanFold) {
17915 SourceLocation DiagLoc = E->getBeginLoc();
17916
17917 if (getLangOpts().CPlusPlus11) {
17918 // C++11 [expr.const]p5:
17919 // If an expression of literal class type is used in a context where an
17920 // integral constant expression is required, then that class type shall
17921 // have a single non-explicit conversion function to an integral or
17922 // unscoped enumeration type
17923 ExprResult Converted;
17924 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17925 VerifyICEDiagnoser &BaseDiagnoser;
17926 public:
17927 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17928 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17929 BaseDiagnoser.Suppress, true),
17930 BaseDiagnoser(BaseDiagnoser) {}
17931
17932 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17933 QualType T) override {
17934 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17935 }
17936
17937 SemaDiagnosticBuilder diagnoseIncomplete(
17938 Sema &S, SourceLocation Loc, QualType T) override {
17939 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17940 }
17941
17942 SemaDiagnosticBuilder diagnoseExplicitConv(
17943 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17944 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17945 }
17946
17947 SemaDiagnosticBuilder noteExplicitConv(
17948 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17949 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17950 << ConvTy->isEnumeralType() << ConvTy;
17951 }
17952
17953 SemaDiagnosticBuilder diagnoseAmbiguous(
17954 Sema &S, SourceLocation Loc, QualType T) override {
17955 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17956 }
17957
17958 SemaDiagnosticBuilder noteAmbiguous(
17959 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17960 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17961 << ConvTy->isEnumeralType() << ConvTy;
17962 }
17963
17964 SemaDiagnosticBuilder diagnoseConversion(
17965 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17966 llvm_unreachable("conversion functions are permitted");
17967 }
17968 } ConvertDiagnoser(Diagnoser);
17969
17970 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17971 ConvertDiagnoser);
17972 if (Converted.isInvalid())
17973 return Converted;
17974 E = Converted.get();
17975 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17976 // don't try to evaluate it later. We also don't want to return the
17977 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17978 // this function will attempt to use 'Value'.
17979 if (isa<RecoveryExpr>(E))
17980 return ExprError();
17982 return ExprError();
17983 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17984 // An ICE must be of integral or unscoped enumeration type.
17985 if (!Diagnoser.Suppress)
17986 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17987 << E->getSourceRange();
17988 return ExprError();
17989 }
17990
17991 ExprResult RValueExpr = DefaultLvalueConversion(E);
17992 if (RValueExpr.isInvalid())
17993 return ExprError();
17994
17995 E = RValueExpr.get();
17996
17997 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17998 // in the non-ICE case.
18001 if (Result)
18003 if (!isa<ConstantExpr>(E))
18006
18007 if (Notes.empty())
18008 return E;
18009
18010 // If our only note is the usual "invalid subexpression" note, just point
18011 // the caret at its location rather than producing an essentially
18012 // redundant note.
18013 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18014 diag::note_invalid_subexpr_in_const_expr) {
18015 DiagLoc = Notes[0].first;
18016 Notes.clear();
18017 }
18018
18019 if (getLangOpts().CPlusPlus) {
18020 if (!Diagnoser.Suppress) {
18021 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18022 for (const PartialDiagnosticAt &Note : Notes)
18023 Diag(Note.first, Note.second);
18024 }
18025 return ExprError();
18026 }
18027
18028 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18029 for (const PartialDiagnosticAt &Note : Notes)
18030 Diag(Note.first, Note.second);
18031
18032 return E;
18033 }
18034
18035 Expr::EvalResult EvalResult;
18037 EvalResult.Diag = &Notes;
18038
18039 // Try to evaluate the expression, and produce diagnostics explaining why it's
18040 // not a constant expression as a side-effect.
18041 bool Folded =
18042 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
18043 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
18044 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
18045
18046 if (!isa<ConstantExpr>(E))
18047 E = ConstantExpr::Create(Context, E, EvalResult.Val);
18048
18049 // In C++11, we can rely on diagnostics being produced for any expression
18050 // which is not a constant expression. If no diagnostics were produced, then
18051 // this is a constant expression.
18052 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
18053 if (Result)
18054 *Result = EvalResult.Val.getInt();
18055 return E;
18056 }
18057
18058 // If our only note is the usual "invalid subexpression" note, just point
18059 // the caret at its location rather than producing an essentially
18060 // redundant note.
18061 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
18062 diag::note_invalid_subexpr_in_const_expr) {
18063 DiagLoc = Notes[0].first;
18064 Notes.clear();
18065 }
18066
18067 if (!Folded || CanFold == AllowFoldKind::No) {
18068 if (!Diagnoser.Suppress) {
18069 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
18070 for (const PartialDiagnosticAt &Note : Notes)
18071 Diag(Note.first, Note.second);
18072 }
18073
18074 return ExprError();
18075 }
18076
18077 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
18078 for (const PartialDiagnosticAt &Note : Notes)
18079 Diag(Note.first, Note.second);
18080
18081 if (Result)
18082 *Result = EvalResult.Val.getInt();
18083 return E;
18084}
18085
18086namespace {
18087 // Handle the case where we conclude a expression which we speculatively
18088 // considered to be unevaluated is actually evaluated.
18089 class TransformToPE : public TreeTransform<TransformToPE> {
18090 typedef TreeTransform<TransformToPE> BaseTransform;
18091
18092 public:
18093 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
18094
18095 // Make sure we redo semantic analysis
18096 bool AlwaysRebuild() { return true; }
18097 bool ReplacingOriginal() { return true; }
18098
18099 // We need to special-case DeclRefExprs referring to FieldDecls which
18100 // are not part of a member pointer formation; normal TreeTransforming
18101 // doesn't catch this case because of the way we represent them in the AST.
18102 // FIXME: This is a bit ugly; is it really the best way to handle this
18103 // case?
18104 //
18105 // Error on DeclRefExprs referring to FieldDecls.
18106 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18107 if (isa<FieldDecl>(E->getDecl()) &&
18108 !SemaRef.isUnevaluatedContext())
18109 return SemaRef.Diag(E->getLocation(),
18110 diag::err_invalid_non_static_member_use)
18111 << E->getDecl() << E->getSourceRange();
18112
18113 return BaseTransform::TransformDeclRefExpr(E);
18114 }
18115
18116 // Exception: filter out member pointer formation
18117 ExprResult TransformUnaryOperator(UnaryOperator *E) {
18118 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
18119 return E;
18120
18121 return BaseTransform::TransformUnaryOperator(E);
18122 }
18123
18124 // The body of a lambda-expression is in a separate expression evaluation
18125 // context so never needs to be transformed.
18126 // FIXME: Ideally we wouldn't transform the closure type either, and would
18127 // just recreate the capture expressions and lambda expression.
18128 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
18129 return SkipLambdaBody(E, Body);
18130 }
18131 };
18132}
18133
18135 assert(isUnevaluatedContext() &&
18136 "Should only transform unevaluated expressions");
18137 ExprEvalContexts.back().Context =
18138 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
18140 return E;
18141 return TransformToPE(*this).TransformExpr(E);
18142}
18143
18145 assert(isUnevaluatedContext() &&
18146 "Should only transform unevaluated expressions");
18149 return TInfo;
18150 return TransformToPE(*this).TransformType(TInfo);
18151}
18152
18153void
18155 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
18157 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
18158 LambdaContextDecl, ExprContext);
18159
18160 // Discarded statements and immediate contexts nested in other
18161 // discarded statements or immediate context are themselves
18162 // a discarded statement or an immediate context, respectively.
18163 ExprEvalContexts.back().InDiscardedStatement =
18165
18166 // C++23 [expr.const]/p15
18167 // An expression or conversion is in an immediate function context if [...]
18168 // it is a subexpression of a manifestly constant-evaluated expression or
18169 // conversion.
18170 const auto &Prev = parentEvaluationContext();
18171 ExprEvalContexts.back().InImmediateFunctionContext =
18172 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
18173
18174 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
18175 Prev.InImmediateEscalatingFunctionContext;
18176
18177 Cleanup.reset();
18178 if (!MaybeODRUseExprs.empty())
18179 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
18180}
18181
18182void
18186 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
18187 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
18188}
18189
18191 ExpressionEvaluationContext NewContext, FunctionDecl *FD) {
18192 // [expr.const]/p14.1
18193 // An expression or conversion is in an immediate function context if it is
18194 // potentially evaluated and either: its innermost enclosing non-block scope
18195 // is a function parameter scope of an immediate function.
18197 FD && FD->isConsteval()
18199 : NewContext);
18203
18204 Current.InDiscardedStatement = false;
18205
18206 if (FD) {
18207
18208 // Each ExpressionEvaluationContextRecord also keeps track of whether the
18209 // context is nested in an immediate function context, so smaller contexts
18210 // that appear inside immediate functions (like variable initializers) are
18211 // considered to be inside an immediate function context even though by
18212 // themselves they are not immediate function contexts. But when a new
18213 // function is entered, we need to reset this tracking, since the entered
18214 // function might be not an immediate function.
18215
18217 getLangOpts().CPlusPlus20 && FD->isImmediateEscalating();
18218
18219 if (isLambdaMethod(FD))
18221 FD->isConsteval() ||
18222 (isLambdaMethod(FD) && (Parent.isConstantEvaluated() ||
18223 Parent.isImmediateFunctionContext()));
18224 else
18226 }
18227}
18228
18230 TypeSourceInfo *TSI) {
18231 return BuildCXXReflectExpr(CaretCaretLoc, TSI);
18232}
18233
18235 TypeSourceInfo *TSI) {
18236 return CXXReflectExpr::Create(Context, CaretCaretLoc, TSI);
18237}
18238
18239namespace {
18240
18241const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
18242 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
18243 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
18244 if (E->getOpcode() == UO_Deref)
18245 return CheckPossibleDeref(S, E->getSubExpr());
18246 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
18247 return CheckPossibleDeref(S, E->getBase());
18248 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
18249 return CheckPossibleDeref(S, E->getBase());
18250 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
18251 QualType Inner;
18252 QualType Ty = E->getType();
18253 if (const auto *Ptr = Ty->getAs<PointerType>())
18254 Inner = Ptr->getPointeeType();
18255 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
18256 Inner = Arr->getElementType();
18257 else
18258 return nullptr;
18259
18260 if (Inner->hasAttr(attr::NoDeref))
18261 return E;
18262 }
18263 return nullptr;
18264}
18265
18266} // namespace
18267
18269 for (const Expr *E : Rec.PossibleDerefs) {
18270 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
18271 if (DeclRef) {
18272 const ValueDecl *Decl = DeclRef->getDecl();
18273 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
18274 << Decl->getName() << E->getSourceRange();
18275 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
18276 } else {
18277 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
18278 << E->getSourceRange();
18279 }
18280 }
18281 Rec.PossibleDerefs.clear();
18282}
18283
18286 return;
18287
18288 // Note: ignoring parens here is not justified by the standard rules, but
18289 // ignoring parentheses seems like a more reasonable approach, and this only
18290 // drives a deprecation warning so doesn't affect conformance.
18291 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
18292 if (BO->getOpcode() == BO_Assign) {
18293 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
18294 llvm::erase(LHSs, BO->getLHS());
18295 }
18296 }
18297}
18298
18300 assert(getLangOpts().CPlusPlus20 &&
18301 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18302 "Cannot mark an immediate escalating expression outside of an "
18303 "immediate escalating context");
18304 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
18305 Call && Call->getCallee()) {
18306 if (auto *DeclRef =
18307 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18308 DeclRef->setIsImmediateEscalating(true);
18309 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
18310 Ctr->setIsImmediateEscalating(true);
18311 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
18312 DeclRef->setIsImmediateEscalating(true);
18313 } else {
18314 assert(false && "expected an immediately escalating expression");
18315 }
18317 FI->FoundImmediateEscalatingExpression = true;
18318}
18319
18321 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
18322 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18325 return E;
18326
18327 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18328 /// It's OK if this fails; we'll also remove this in
18329 /// HandleImmediateInvocations, but catching it here allows us to avoid
18330 /// walking the AST looking for it in simple cases.
18331 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
18332 if (auto *DeclRef =
18333 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
18334 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
18335
18336 // C++23 [expr.const]/p16
18337 // An expression or conversion is immediate-escalating if it is not initially
18338 // in an immediate function context and it is [...] an immediate invocation
18339 // that is not a constant expression and is not a subexpression of an
18340 // immediate invocation.
18341 APValue Cached;
18342 auto CheckConstantExpressionAndKeepResult = [&]() {
18343 Expr::EvalResult Eval;
18344 bool Res = E.get()->EvaluateAsConstantExpr(
18345 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
18346 if (Res && !Eval.DiagEmitted) {
18347 Cached = std::move(Eval.Val);
18348 return true;
18349 }
18350 return false;
18351 };
18352
18353 if (!E.get()->isValueDependent() &&
18354 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
18355 !CheckConstantExpressionAndKeepResult()) {
18357 return E;
18358 }
18359
18360 if (Cleanup.exprNeedsCleanups()) {
18361 // Since an immediate invocation is a full expression itself - it requires
18362 // an additional ExprWithCleanups node, but it can participate to a bigger
18363 // full expression which actually requires cleanups to be run after so
18364 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18365 // may discard cleanups for outer expression too early.
18366
18367 // Note that ExprWithCleanups created here must always have empty cleanup
18368 // objects:
18369 // - compound literals do not create cleanup objects in C++ and immediate
18370 // invocations are C++-only.
18371 // - blocks are not allowed inside constant expressions and compiler will
18372 // issue an error if they appear there.
18373 //
18374 // Hence, in correct code any cleanup objects created inside current
18375 // evaluation context must be outside the immediate invocation.
18377 Cleanup.cleanupsHaveSideEffects(), {});
18378 }
18379
18381 getASTContext(), E.get(),
18382 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
18383 getASTContext()),
18384 /*IsImmediateInvocation*/ true);
18385 if (Cached.hasValue())
18386 Res->MoveIntoResult(Cached, getASTContext());
18387 /// Value-dependent constant expressions should not be immediately
18388 /// evaluated until they are instantiated.
18389 if (!Res->isValueDependent())
18390 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
18391 return Res;
18392}
18393
18397 Expr::EvalResult Eval;
18398 Eval.Diag = &Notes;
18399 ConstantExpr *CE = Candidate.getPointer();
18400 bool Result = CE->EvaluateAsConstantExpr(
18401 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
18402 if (!Result || !Notes.empty()) {
18404 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
18405 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
18406 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
18407 FunctionDecl *FD = nullptr;
18408 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
18409 FD = cast<FunctionDecl>(Call->getCalleeDecl());
18410 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
18411 FD = Call->getConstructor();
18412 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
18413 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
18414
18415 assert(FD && FD->isImmediateFunction() &&
18416 "could not find an immediate function in this expression");
18417 if (FD->isInvalidDecl())
18418 return;
18419 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
18420 << FD << FD->isConsteval();
18421 if (auto Context =
18423 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18424 << Context->Decl;
18425 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18426 }
18427 if (!FD->isConsteval())
18429 for (auto &Note : Notes)
18430 SemaRef.Diag(Note.first, Note.second);
18431 return;
18432 }
18434}
18435
18439 struct ComplexRemove : TreeTransform<ComplexRemove> {
18441 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18444 CurrentII;
18445 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
18448 4>::reverse_iterator Current)
18449 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
18450 void RemoveImmediateInvocation(ConstantExpr* E) {
18451 auto It = std::find_if(CurrentII, IISet.rend(),
18453 return Elem.getPointer() == E;
18454 });
18455 // It is possible that some subexpression of the current immediate
18456 // invocation was handled from another expression evaluation context. Do
18457 // not handle the current immediate invocation if some of its
18458 // subexpressions failed before.
18459 if (It == IISet.rend()) {
18460 if (SemaRef.FailedImmediateInvocations.contains(E))
18461 CurrentII->setInt(1);
18462 } else {
18463 It->setInt(1); // Mark as deleted
18464 }
18465 }
18466 ExprResult TransformConstantExpr(ConstantExpr *E) {
18467 if (!E->isImmediateInvocation())
18468 return Base::TransformConstantExpr(E);
18469 RemoveImmediateInvocation(E);
18470 return Base::TransformExpr(E->getSubExpr());
18471 }
18472 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18473 /// we need to remove its DeclRefExpr from the DRSet.
18474 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
18475 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
18476 return Base::TransformCXXOperatorCallExpr(E);
18477 }
18478 /// Base::TransformUserDefinedLiteral doesn't preserve the
18479 /// UserDefinedLiteral node.
18480 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
18481 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18482 /// here.
18483 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
18484 if (!Init)
18485 return Init;
18486
18487 // We cannot use IgnoreImpCasts because we need to preserve
18488 // full expressions.
18489 while (true) {
18490 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
18491 Init = ICE->getSubExpr();
18492 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
18493 Init = ICE->getSubExpr();
18494 else
18495 break;
18496 }
18497 /// ConstantExprs are the first layer of implicit node to be removed so if
18498 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18499 if (auto *CE = dyn_cast<ConstantExpr>(Init);
18500 CE && CE->isImmediateInvocation())
18501 RemoveImmediateInvocation(CE);
18502 return Base::TransformInitializer(Init, NotCopyInit);
18503 }
18504 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
18505 DRSet.erase(E);
18506 return E;
18507 }
18508 ExprResult TransformLambdaExpr(LambdaExpr *E) {
18509 // Do not rebuild lambdas to avoid creating a new type.
18510 // Lambdas have already been processed inside their eval contexts.
18511 return E;
18512 }
18513
18514 // We do not have enough information to transform opaque expressions and
18515 // assume they do not contain immediate subexpressions.
18516 ExprResult TransformOpaqueValueExpr(OpaqueValueExpr *E) { return E; }
18517
18518 bool AlwaysRebuild() { return false; }
18519 bool ReplacingOriginal() { return true; }
18520 bool AllowSkippingCXXConstructExpr() {
18521 bool Res = AllowSkippingFirstCXXConstructExpr;
18522 AllowSkippingFirstCXXConstructExpr = true;
18523 return Res;
18524 }
18525 bool AllowSkippingFirstCXXConstructExpr = true;
18526 } Transformer(SemaRef, Rec.ReferenceToConsteval,
18528
18529 /// CXXConstructExpr with a single argument are getting skipped by
18530 /// TreeTransform in some situtation because they could be implicit. This
18531 /// can only occur for the top-level CXXConstructExpr because it is used
18532 /// nowhere in the expression being transformed therefore will not be rebuilt.
18533 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18534 /// skipping the first CXXConstructExpr.
18535 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
18536 Transformer.AllowSkippingFirstCXXConstructExpr = false;
18537
18538 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
18539 // The result may not be usable in case of previous compilation errors.
18540 // In this case evaluation of the expression may result in crash so just
18541 // don't do anything further with the result.
18542 if (Res.isUsable()) {
18544 It->getPointer()->setSubExpr(Res.get());
18545 }
18546}
18547
18548static void
18551 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18552 Rec.ReferenceToConsteval.size() == 0) ||
18554 return;
18555
18556 // An expression or conversion is 'manifestly constant-evaluated' if it is:
18557 // [...]
18558 // - the initializer of a variable that is usable in constant expressions or
18559 // has constant initialization.
18560 if (SemaRef.getLangOpts().CPlusPlus23 &&
18561 Rec.ExprContext ==
18563 auto *VD = dyn_cast<VarDecl>(Rec.ManglingContextDecl);
18564 if (VD && (VD->isUsableInConstantExpressions(SemaRef.Context) ||
18565 VD->hasConstantInitialization())) {
18566 // An expression or conversion is in an 'immediate function context' if it
18567 // is potentially evaluated and either:
18568 // [...]
18569 // - it is a subexpression of a manifestly constant-evaluated expression
18570 // or conversion.
18571 return;
18572 }
18573 }
18574
18575 /// When we have more than 1 ImmediateInvocationCandidates or previously
18576 /// failed immediate invocations, we need to check for nested
18577 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18578 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18579 /// invocation.
18580 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18582
18583 /// Prevent sema calls during the tree transform from adding pointers that
18584 /// are already in the sets.
18585 llvm::SaveAndRestore DisableIITracking(
18587
18588 /// Prevent diagnostic during tree transfrom as they are duplicates
18590
18591 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18592 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18593 if (!It->getInt())
18595 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18596 Rec.ReferenceToConsteval.size()) {
18597 struct SimpleRemove : DynamicRecursiveASTVisitor {
18598 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18599 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18600 bool VisitDeclRefExpr(DeclRefExpr *E) override {
18601 DRSet.erase(E);
18602 return DRSet.size();
18603 }
18604 } Visitor(Rec.ReferenceToConsteval);
18605 Visitor.TraverseStmt(
18606 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18607 }
18608 for (auto CE : Rec.ImmediateInvocationCandidates)
18609 if (!CE.getInt())
18611 for (auto *DR : Rec.ReferenceToConsteval) {
18612 // If the expression is immediate escalating, it is not an error;
18613 // The outer context itself becomes immediate and further errors,
18614 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18615 if (DR->isImmediateEscalating())
18616 continue;
18617 auto *FD = cast<FunctionDecl>(DR->getDecl());
18618 const NamedDecl *ND = FD;
18619 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18620 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18621 ND = MD->getParent();
18622
18623 // C++23 [expr.const]/p16
18624 // An expression or conversion is immediate-escalating if it is not
18625 // initially in an immediate function context and it is [...] a
18626 // potentially-evaluated id-expression that denotes an immediate function
18627 // that is not a subexpression of an immediate invocation.
18628 bool ImmediateEscalating = false;
18629 bool IsPotentiallyEvaluated =
18630 Rec.Context ==
18632 Rec.Context ==
18634 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18635 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18636
18638 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18639 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18640 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18641 if (!FD->getBuiltinID())
18642 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18643 if (auto Context =
18645 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18646 << Context->Decl;
18647 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18648 }
18649 if (FD->isImmediateEscalating() && !FD->isConsteval())
18651
18652 } else {
18654 }
18655 }
18656}
18657
18660 if (!Rec.Lambdas.empty()) {
18662 if (!getLangOpts().CPlusPlus20 &&
18663 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18664 Rec.isUnevaluated() ||
18666 unsigned D;
18667 if (Rec.isUnevaluated()) {
18668 // C++11 [expr.prim.lambda]p2:
18669 // A lambda-expression shall not appear in an unevaluated operand
18670 // (Clause 5).
18671 D = diag::err_lambda_unevaluated_operand;
18672 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18673 // C++1y [expr.const]p2:
18674 // A conditional-expression e is a core constant expression unless the
18675 // evaluation of e, following the rules of the abstract machine, would
18676 // evaluate [...] a lambda-expression.
18677 D = diag::err_lambda_in_constant_expression;
18678 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18679 // C++17 [expr.prim.lamda]p2:
18680 // A lambda-expression shall not appear [...] in a template-argument.
18681 D = diag::err_lambda_in_invalid_context;
18682 } else
18683 llvm_unreachable("Couldn't infer lambda error message.");
18684
18685 for (const auto *L : Rec.Lambdas)
18686 Diag(L->getBeginLoc(), D);
18687 }
18688 }
18689
18690 // Append the collected materialized temporaries into previous context before
18691 // exit if the previous also is a lifetime extending context.
18693 parentEvaluationContext().InLifetimeExtendingContext &&
18694 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18697 }
18698
18700 HandleImmediateInvocations(*this, Rec);
18701
18702 // Warn on any volatile-qualified simple-assignments that are not discarded-
18703 // value expressions nor unevaluated operands (those cases get removed from
18704 // this list by CheckUnusedVolatileAssignment).
18705 for (auto *BO : Rec.VolatileAssignmentLHSs)
18706 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18707 << BO->getType();
18708
18709 // When are coming out of an unevaluated context, clear out any
18710 // temporaries that we may have created as part of the evaluation of
18711 // the expression in that context: they aren't relevant because they
18712 // will never be constructed.
18713 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18715 ExprCleanupObjects.end());
18716 Cleanup = Rec.ParentCleanup;
18719 // Otherwise, merge the contexts together.
18720 } else {
18721 Cleanup.mergeFrom(Rec.ParentCleanup);
18722 MaybeODRUseExprs.insert_range(Rec.SavedMaybeODRUseExprs);
18723 }
18724
18726
18727 // Pop the current expression evaluation context off the stack.
18728 ExprEvalContexts.pop_back();
18729}
18730
18732 ExprCleanupObjects.erase(
18733 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18734 ExprCleanupObjects.end());
18735 Cleanup.reset();
18736 MaybeODRUseExprs.clear();
18737}
18738
18741 if (Result.isInvalid())
18742 return ExprError();
18743 E = Result.get();
18744 if (!E->getType()->isVariablyModifiedType())
18745 return E;
18747}
18748
18749/// Are we in a context that is potentially constant evaluated per C++20
18750/// [expr.const]p12?
18752 /// C++2a [expr.const]p12:
18753 // An expression or conversion is potentially constant evaluated if it is
18754 switch (SemaRef.ExprEvalContexts.back().Context) {
18757
18758 // -- a manifestly constant-evaluated expression,
18762 // -- a potentially-evaluated expression,
18764 // -- an immediate subexpression of a braced-init-list,
18765
18766 // -- [FIXME] an expression of the form & cast-expression that occurs
18767 // within a templated entity
18768 // -- a subexpression of one of the above that is not a subexpression of
18769 // a nested unevaluated operand.
18770 return true;
18771
18774 // Expressions in this context are never evaluated.
18775 return false;
18776 }
18777 llvm_unreachable("Invalid context");
18778}
18779
18780/// Return true if this function has a calling convention that requires mangling
18781/// in the size of the parameter pack.
18783 // These manglings are only applicable for targets whcih use Microsoft
18784 // mangling scheme for C.
18786 return false;
18787
18788 // If this is C++ and this isn't an extern "C" function, parameters do not
18789 // need to be complete. In this case, C++ mangling will apply, which doesn't
18790 // use the size of the parameters.
18791 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18792 return false;
18793
18794 // Stdcall, fastcall, and vectorcall need this special treatment.
18795 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18796 switch (CC) {
18797 case CC_X86StdCall:
18798 case CC_X86FastCall:
18799 case CC_X86VectorCall:
18800 return true;
18801 default:
18802 break;
18803 }
18804 return false;
18805}
18806
18807/// Require that all of the parameter types of function be complete. Normally,
18808/// parameter types are only required to be complete when a function is called
18809/// or defined, but to mangle functions with certain calling conventions, the
18810/// mangler needs to know the size of the parameter list. In this situation,
18811/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18812/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18813/// result in a linker error. Clang doesn't implement this behavior, and instead
18814/// attempts to error at compile time.
18816 SourceLocation Loc) {
18817 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18818 FunctionDecl *FD;
18819 ParmVarDecl *Param;
18820
18821 public:
18822 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18823 : FD(FD), Param(Param) {}
18824
18825 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18826 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18827 StringRef CCName;
18828 switch (CC) {
18829 case CC_X86StdCall:
18830 CCName = "stdcall";
18831 break;
18832 case CC_X86FastCall:
18833 CCName = "fastcall";
18834 break;
18835 case CC_X86VectorCall:
18836 CCName = "vectorcall";
18837 break;
18838 default:
18839 llvm_unreachable("CC does not need mangling");
18840 }
18841
18842 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18843 << Param->getDeclName() << FD->getDeclName() << CCName;
18844 }
18845 };
18846
18847 for (ParmVarDecl *Param : FD->parameters()) {
18848 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18849 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18850 }
18851}
18852
18853namespace {
18854enum class OdrUseContext {
18855 /// Declarations in this context are not odr-used.
18856 None,
18857 /// Declarations in this context are formally odr-used, but this is a
18858 /// dependent context.
18859 Dependent,
18860 /// Declarations in this context are odr-used but not actually used (yet).
18861 FormallyOdrUsed,
18862 /// Declarations in this context are used.
18863 Used
18864};
18865}
18866
18867/// Are we within a context in which references to resolved functions or to
18868/// variables result in odr-use?
18869static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18872
18873 if (Context.isUnevaluated())
18874 return OdrUseContext::None;
18875
18877 return OdrUseContext::Dependent;
18878
18879 if (Context.isDiscardedStatementContext())
18880 return OdrUseContext::FormallyOdrUsed;
18881
18882 else if (Context.Context ==
18884 return OdrUseContext::FormallyOdrUsed;
18885
18886 return OdrUseContext::Used;
18887}
18888
18890 if (!Func->isConstexpr())
18891 return false;
18892
18893 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18894 return true;
18895
18896 // Lambda conversion operators are never user provided.
18897 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(Func))
18898 return isLambdaConversionOperator(Conv);
18899
18900 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18901 return CCD && CCD->getInheritedConstructor();
18902}
18903
18905 bool MightBeOdrUse) {
18906 assert(Func && "No function?");
18907
18908 Func->setReferenced();
18909
18910 // Recursive functions aren't really used until they're used from some other
18911 // context.
18912 bool IsRecursiveCall = CurContext == Func;
18913
18914 // C++11 [basic.def.odr]p3:
18915 // A function whose name appears as a potentially-evaluated expression is
18916 // odr-used if it is the unique lookup result or the selected member of a
18917 // set of overloaded functions [...].
18918 //
18919 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18920 // can just check that here.
18921 OdrUseContext OdrUse =
18922 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18923 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18924 OdrUse = OdrUseContext::FormallyOdrUsed;
18925
18926 // Trivial default constructors and destructors are never actually used.
18927 // FIXME: What about other special members?
18928 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18929 OdrUse == OdrUseContext::Used) {
18930 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18931 if (Constructor->isDefaultConstructor())
18932 OdrUse = OdrUseContext::FormallyOdrUsed;
18934 OdrUse = OdrUseContext::FormallyOdrUsed;
18935 }
18936
18937 // C++20 [expr.const]p12:
18938 // A function [...] is needed for constant evaluation if it is [...] a
18939 // constexpr function that is named by an expression that is potentially
18940 // constant evaluated
18941 bool NeededForConstantEvaluation =
18944
18945 // Determine whether we require a function definition to exist, per
18946 // C++11 [temp.inst]p3:
18947 // Unless a function template specialization has been explicitly
18948 // instantiated or explicitly specialized, the function template
18949 // specialization is implicitly instantiated when the specialization is
18950 // referenced in a context that requires a function definition to exist.
18951 // C++20 [temp.inst]p7:
18952 // The existence of a definition of a [...] function is considered to
18953 // affect the semantics of the program if the [...] function is needed for
18954 // constant evaluation by an expression
18955 // C++20 [basic.def.odr]p10:
18956 // Every program shall contain exactly one definition of every non-inline
18957 // function or variable that is odr-used in that program outside of a
18958 // discarded statement
18959 // C++20 [special]p1:
18960 // The implementation will implicitly define [defaulted special members]
18961 // if they are odr-used or needed for constant evaluation.
18962 //
18963 // Note that we skip the implicit instantiation of templates that are only
18964 // used in unused default arguments or by recursive calls to themselves.
18965 // This is formally non-conforming, but seems reasonable in practice.
18966 bool NeedDefinition =
18967 !IsRecursiveCall &&
18968 (OdrUse == OdrUseContext::Used ||
18969 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18970
18971 // C++14 [temp.expl.spec]p6:
18972 // If a template [...] is explicitly specialized then that specialization
18973 // shall be declared before the first use of that specialization that would
18974 // cause an implicit instantiation to take place, in every translation unit
18975 // in which such a use occurs
18976 if (NeedDefinition &&
18977 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18978 Func->getMemberSpecializationInfo()))
18980
18981 if (getLangOpts().CUDA)
18982 CUDA().CheckCall(Loc, Func);
18983
18984 // If we need a definition, try to create one.
18985 if (NeedDefinition && !Func->getBody()) {
18988 dyn_cast<CXXConstructorDecl>(Func)) {
18990 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18991 if (Constructor->isDefaultConstructor()) {
18992 if (Constructor->isTrivial() &&
18993 !Constructor->hasAttr<DLLExportAttr>())
18994 return;
18996 } else if (Constructor->isCopyConstructor()) {
18998 } else if (Constructor->isMoveConstructor()) {
19000 }
19001 } else if (Constructor->getInheritedConstructor()) {
19003 }
19004 } else if (CXXDestructorDecl *Destructor =
19005 dyn_cast<CXXDestructorDecl>(Func)) {
19007 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
19008 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
19009 return;
19011 }
19012 if (Destructor->isVirtual() && getLangOpts().AppleKext)
19013 MarkVTableUsed(Loc, Destructor->getParent());
19014 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
19015 if (MethodDecl->isOverloadedOperator() &&
19016 MethodDecl->getOverloadedOperator() == OO_Equal) {
19017 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
19018 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
19019 if (MethodDecl->isCopyAssignmentOperator())
19020 DefineImplicitCopyAssignment(Loc, MethodDecl);
19021 else if (MethodDecl->isMoveAssignmentOperator())
19022 DefineImplicitMoveAssignment(Loc, MethodDecl);
19023 }
19024 } else if (isa<CXXConversionDecl>(MethodDecl) &&
19025 MethodDecl->getParent()->isLambda()) {
19026 CXXConversionDecl *Conversion =
19027 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
19028 if (Conversion->isLambdaToBlockPointerConversion())
19030 else
19032 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
19033 MarkVTableUsed(Loc, MethodDecl->getParent());
19034 }
19035
19036 if (Func->isDefaulted() && !Func->isDeleted()) {
19040 }
19041
19042 // Implicit instantiation of function templates and member functions of
19043 // class templates.
19044 if (Func->isImplicitlyInstantiable()) {
19046 Func->getTemplateSpecializationKindForInstantiation();
19047 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
19048 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19049 if (FirstInstantiation) {
19050 PointOfInstantiation = Loc;
19051 if (auto *MSI = Func->getMemberSpecializationInfo())
19052 MSI->setPointOfInstantiation(Loc);
19053 // FIXME: Notify listener.
19054 else
19055 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19056 } else if (TSK != TSK_ImplicitInstantiation) {
19057 // Use the point of use as the point of instantiation, instead of the
19058 // point of explicit instantiation (which we track as the actual point
19059 // of instantiation). This gives better backtraces in diagnostics.
19060 PointOfInstantiation = Loc;
19061 }
19062
19063 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
19064 Func->isConstexpr()) {
19065 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
19066 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
19067 CodeSynthesisContexts.size())
19069 std::make_pair(Func, PointOfInstantiation));
19070 else if (Func->isConstexpr())
19071 // Do not defer instantiations of constexpr functions, to avoid the
19072 // expression evaluator needing to call back into Sema if it sees a
19073 // call to such a function.
19074 InstantiateFunctionDefinition(PointOfInstantiation, Func);
19075 else {
19076 Func->setInstantiationIsPending(true);
19077 PendingInstantiations.push_back(
19078 std::make_pair(Func, PointOfInstantiation));
19079 if (llvm::isTimeTraceVerbose()) {
19080 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
19081 std::string Name;
19082 llvm::raw_string_ostream OS(Name);
19083 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
19084 /*Qualified=*/true);
19085 return Name;
19086 });
19087 }
19088 // Notify the consumer that a function was implicitly instantiated.
19089 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
19090 }
19091 }
19092 } else {
19093 // Walk redefinitions, as some of them may be instantiable.
19094 for (auto *i : Func->redecls()) {
19095 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
19096 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
19097 }
19098 }
19099 });
19100 }
19101
19102 // If a constructor was defined in the context of a default parameter
19103 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19104 // context), its initializers may not be referenced yet.
19105 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
19107 *this,
19108 Constructor->isImmediateFunction()
19111 Constructor);
19112 for (CXXCtorInitializer *Init : Constructor->inits()) {
19113 if (Init->isInClassMemberInitializer())
19114 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
19115 MarkDeclarationsReferencedInExpr(Init->getInit());
19116 });
19117 }
19118 }
19119
19120 // C++14 [except.spec]p17:
19121 // An exception-specification is considered to be needed when:
19122 // - the function is odr-used or, if it appears in an unevaluated operand,
19123 // would be odr-used if the expression were potentially-evaluated;
19124 //
19125 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19126 // function is a pure virtual function we're calling, and in that case the
19127 // function was selected by overload resolution and we need to resolve its
19128 // exception specification for a different reason.
19129 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
19131 ResolveExceptionSpec(Loc, FPT);
19132
19133 // A callee could be called by a host function then by a device function.
19134 // If we only try recording once, we will miss recording the use on device
19135 // side. Therefore keep trying until it is recorded.
19136 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
19137 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(Func))
19139
19140 // If this is the first "real" use, act on that.
19141 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
19142 // Keep track of used but undefined functions.
19143 if (!Func->isDefined() && !Func->isInAnotherModuleUnit()) {
19144 if (mightHaveNonExternalLinkage(Func))
19145 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19146 else if (Func->getMostRecentDecl()->isInlined() &&
19147 !LangOpts.GNUInline &&
19148 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
19149 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19151 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
19152 }
19153
19154 // Some x86 Windows calling conventions mangle the size of the parameter
19155 // pack into the name. Computing the size of the parameters requires the
19156 // parameter types to be complete. Check that now.
19159
19160 // In the MS C++ ABI, the compiler emits destructor variants where they are
19161 // used. If the destructor is used here but defined elsewhere, mark the
19162 // virtual base destructors referenced. If those virtual base destructors
19163 // are inline, this will ensure they are defined when emitting the complete
19164 // destructor variant. This checking may be redundant if the destructor is
19165 // provided later in this TU.
19166 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19167 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
19168 CXXRecordDecl *Parent = Dtor->getParent();
19169 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
19171 }
19172 }
19173
19174 Func->markUsed(Context);
19175 }
19176}
19177
19178/// Directly mark a variable odr-used. Given a choice, prefer to use
19179/// MarkVariableReferenced since it does additional checks and then
19180/// calls MarkVarDeclODRUsed.
19181/// If the variable must be captured:
19182/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19183/// - else capture it in the DeclContext that maps to the
19184/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19185static void
19187 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
19188 // Keep track of used but undefined variables.
19189 // FIXME: We shouldn't suppress this warning for static data members.
19190 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
19191 assert(Var && "expected a capturable variable");
19192
19194 (!Var->isExternallyVisible() || Var->isInline() ||
19196 !(Var->isStaticDataMember() && Var->hasInit())) {
19198 if (old.isInvalid())
19199 old = Loc;
19200 }
19201 QualType CaptureType, DeclRefType;
19202 if (SemaRef.LangOpts.OpenMP)
19205 /*EllipsisLoc*/ SourceLocation(),
19206 /*BuildAndDiagnose*/ true, CaptureType,
19207 DeclRefType, FunctionScopeIndexToStopAt);
19208
19209 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
19210 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
19211 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
19212 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
19213 if (VarTarget == SemaCUDA::CVT_Host &&
19214 (UserTarget == CUDAFunctionTarget::Device ||
19215 UserTarget == CUDAFunctionTarget::HostDevice ||
19216 UserTarget == CUDAFunctionTarget::Global)) {
19217 // Diagnose ODR-use of host global variables in device functions.
19218 // Reference of device global variables in host functions is allowed
19219 // through shadow variables therefore it is not diagnosed.
19220 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
19221 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
19222 << /*host*/ 2 << /*variable*/ 1 << Var << UserTarget;
19224 Var->getType().isConstQualified()
19225 ? diag::note_cuda_const_var_unpromoted
19226 : diag::note_cuda_host_var);
19227 }
19228 } else if ((VarTarget == SemaCUDA::CVT_Device ||
19229 // Also capture __device__ const variables, which are classified
19230 // as CVT_Both due to an implicit CUDAConstantAttr. We check for
19231 // an explicit CUDADeviceAttr to distinguish them from plain
19232 // const variables (no __device__), which also get CVT_Both but
19233 // only have an implicit CUDADeviceAttr.
19234 (VarTarget == SemaCUDA::CVT_Both &&
19235 Var->hasAttr<CUDADeviceAttr>() &&
19236 !Var->getAttr<CUDADeviceAttr>()->isImplicit())) &&
19237 !Var->hasAttr<CUDASharedAttr>() &&
19238 (UserTarget == CUDAFunctionTarget::Host ||
19239 UserTarget == CUDAFunctionTarget::HostDevice)) {
19240 // Record a CUDA/HIP device side variable if it is ODR-used
19241 // by host code. This is done conservatively, when the variable is
19242 // referenced in any of the following contexts:
19243 // - a non-function context
19244 // - a host function
19245 // - a host device function
19246 // This makes the ODR-use of the device side variable by host code to
19247 // be visible in the device compilation for the compiler to be able to
19248 // emit template variables instantiated by host code only and to
19249 // externalize the static device side variable ODR-used by host code.
19250 if (!Var->hasExternalStorage())
19252 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
19253 (!FD || (!FD->getDescribedFunctionTemplate() &&
19257 }
19258 }
19259
19260 V->markUsed(SemaRef.Context);
19261}
19262
19264 SourceLocation Loc,
19265 unsigned CapturingScopeIndex) {
19266 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
19267}
19268
19270 SourceLocation loc,
19271 ValueDecl *var) {
19272 DeclContext *VarDC = var->getDeclContext();
19273
19274 // If the parameter still belongs to the translation unit, then
19275 // we're actually just using one parameter in the declaration of
19276 // the next.
19277 if (isa<ParmVarDecl>(var) &&
19279 return;
19280
19281 // For C code, don't diagnose about capture if we're not actually in code
19282 // right now; it's impossible to write a non-constant expression outside of
19283 // function context, so we'll get other (more useful) diagnostics later.
19284 //
19285 // For C++, things get a bit more nasty... it would be nice to suppress this
19286 // diagnostic for certain cases like using a local variable in an array bound
19287 // for a member of a local class, but the correct predicate is not obvious.
19288 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
19289 return;
19290
19291 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
19292 unsigned ContextKind = 3; // unknown
19293 if (isa<CXXMethodDecl>(VarDC) &&
19294 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
19295 ContextKind = 2;
19296 } else if (isa<FunctionDecl>(VarDC)) {
19297 ContextKind = 0;
19298 } else if (isa<BlockDecl>(VarDC)) {
19299 ContextKind = 1;
19300 }
19301
19302 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
19303 << var << ValueKind << ContextKind << VarDC;
19304 S.Diag(var->getLocation(), diag::note_entity_declared_at)
19305 << var;
19306
19307 // FIXME: Add additional diagnostic info about class etc. which prevents
19308 // capture.
19309}
19310
19312 ValueDecl *Var,
19313 bool &SubCapturesAreNested,
19314 QualType &CaptureType,
19315 QualType &DeclRefType) {
19316 // Check whether we've already captured it.
19317 if (CSI->CaptureMap.count(Var)) {
19318 // If we found a capture, any subcaptures are nested.
19319 SubCapturesAreNested = true;
19320
19321 // Retrieve the capture type for this variable.
19322 CaptureType = CSI->getCapture(Var).getCaptureType();
19323
19324 // Compute the type of an expression that refers to this variable.
19325 DeclRefType = CaptureType.getNonReferenceType();
19326
19327 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19328 // are mutable in the sense that user can change their value - they are
19329 // private instances of the captured declarations.
19330 const Capture &Cap = CSI->getCapture(Var);
19331 // C++ [expr.prim.lambda]p10:
19332 // The type of such a data member is [...] an lvalue reference to the
19333 // referenced function type if the entity is a reference to a function.
19334 // [...]
19335 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
19336 !(isa<LambdaScopeInfo>(CSI) &&
19337 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
19339 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
19340 DeclRefType.addConst();
19341 return true;
19342 }
19343 return false;
19344}
19345
19346// Only block literals, captured statements, and lambda expressions can
19347// capture; other scopes don't work.
19349 ValueDecl *Var,
19350 SourceLocation Loc,
19351 const bool Diagnose,
19352 Sema &S) {
19355
19356 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
19357 if (Underlying) {
19358 if (Underlying->hasLocalStorage() && Diagnose)
19360 }
19361 return nullptr;
19362}
19363
19364// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19365// certain types of variables (unnamed, variably modified types etc.)
19366// so check for eligibility.
19368 SourceLocation Loc, const bool Diagnose,
19369 Sema &S) {
19370
19371 assert((isa<VarDecl, BindingDecl>(Var)) &&
19372 "Only variables and structured bindings can be captured");
19373
19374 bool IsBlock = isa<BlockScopeInfo>(CSI);
19375 bool IsLambda = isa<LambdaScopeInfo>(CSI);
19376
19377 // Lambdas are not allowed to capture unnamed variables
19378 // (e.g. anonymous unions).
19379 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19380 // assuming that's the intent.
19381 if (IsLambda && !Var->getDeclName()) {
19382 if (Diagnose) {
19383 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
19384 S.Diag(Var->getLocation(), diag::note_declared_at);
19385 }
19386 return false;
19387 }
19388
19389 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19390 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
19391 if (Diagnose) {
19392 S.Diag(Loc, diag::err_ref_vm_type);
19393 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19394 }
19395 return false;
19396 }
19397 // Prohibit structs with flexible array members too.
19398 // We cannot capture what is in the tail end of the struct.
19399 if (const auto *VTD = Var->getType()->getAsRecordDecl();
19400 VTD && VTD->hasFlexibleArrayMember()) {
19401 if (Diagnose) {
19402 if (IsBlock)
19403 S.Diag(Loc, diag::err_ref_flexarray_type);
19404 else
19405 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
19406 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19407 }
19408 return false;
19409 }
19410 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19411 // Lambdas and captured statements are not allowed to capture __block
19412 // variables; they don't support the expected semantics.
19413 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
19414 if (Diagnose) {
19415 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
19416 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19417 }
19418 return false;
19419 }
19420 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19421 if (S.getLangOpts().OpenCL && IsBlock &&
19422 Var->getType()->isBlockPointerType()) {
19423 if (Diagnose)
19424 S.Diag(Loc, diag::err_opencl_block_ref_block);
19425 return false;
19426 }
19427
19428 if (isa<BindingDecl>(Var)) {
19429 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
19430 if (Diagnose)
19432 return false;
19433 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
19434 S.Diag(Loc, S.LangOpts.CPlusPlus20
19435 ? diag::warn_cxx17_compat_capture_binding
19436 : diag::ext_capture_binding)
19437 << Var;
19438 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19439 }
19440 }
19441
19442 return true;
19443}
19444
19445// Returns true if the capture by block was successful.
19447 SourceLocation Loc, const bool BuildAndDiagnose,
19448 QualType &CaptureType, QualType &DeclRefType,
19449 const bool Nested, Sema &S, bool Invalid) {
19450 bool ByRef = false;
19451
19452 // Blocks are not allowed to capture arrays, excepting OpenCL.
19453 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19454 // (decayed to pointers).
19455 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
19456 if (BuildAndDiagnose) {
19457 S.Diag(Loc, diag::err_ref_array_type);
19458 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19459 Invalid = true;
19460 } else {
19461 return false;
19462 }
19463 }
19464
19465 // Forbid the block-capture of autoreleasing variables.
19466 if (!Invalid &&
19468 if (BuildAndDiagnose) {
19469 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
19470 << /*block*/ 0;
19471 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19472 Invalid = true;
19473 } else {
19474 return false;
19475 }
19476 }
19477
19478 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19479 if (const auto *PT = CaptureType->getAs<PointerType>()) {
19480 QualType PointeeTy = PT->getPointeeType();
19481
19482 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
19484 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
19485 if (BuildAndDiagnose) {
19486 SourceLocation VarLoc = Var->getLocation();
19487 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
19488 S.Diag(VarLoc, diag::note_declare_parameter_strong);
19489 }
19490 }
19491 }
19492
19493 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
19494 if (HasBlocksAttr || CaptureType->isReferenceType() ||
19495 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
19496 // Block capture by reference does not change the capture or
19497 // declaration reference types.
19498 ByRef = true;
19499 } else {
19500 // Block capture by copy introduces 'const'.
19501 CaptureType = CaptureType.getNonReferenceType().withConst();
19502 DeclRefType = CaptureType;
19503 }
19504
19505 // Actually capture the variable.
19506 if (BuildAndDiagnose)
19507 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
19508 CaptureType, Invalid);
19509
19510 return !Invalid;
19511}
19512
19513/// Capture the given variable in the captured region.
19516 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
19517 const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope,
19518 Sema &S, bool Invalid) {
19519 // By default, capture variables by reference.
19520 bool ByRef = true;
19521 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19522 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19523 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
19524 // Using an LValue reference type is consistent with Lambdas (see below).
19525 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
19526 bool HasConst = DeclRefType.isConstQualified();
19527 DeclRefType = DeclRefType.getUnqualifiedType();
19528 // Don't lose diagnostics about assignments to const.
19529 if (HasConst)
19530 DeclRefType.addConst();
19531 }
19532 // Do not capture firstprivates in tasks.
19533 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
19534 RSI->OpenMPCaptureLevel) != OMPC_unknown)
19535 return true;
19536 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
19537 RSI->OpenMPCaptureLevel);
19538 }
19539
19540 if (ByRef)
19541 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19542 else
19543 CaptureType = DeclRefType;
19544
19545 // Actually capture the variable.
19546 if (BuildAndDiagnose)
19547 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
19548 Loc, SourceLocation(), CaptureType, Invalid);
19549
19550 return !Invalid;
19551}
19552
19553/// Capture the given variable in the lambda.
19555 SourceLocation Loc, const bool BuildAndDiagnose,
19556 QualType &CaptureType, QualType &DeclRefType,
19557 const bool RefersToCapturedVariable,
19558 const TryCaptureKind Kind,
19559 SourceLocation EllipsisLoc, const bool IsTopScope,
19560 Sema &S, bool Invalid) {
19561 // Determine whether we are capturing by reference or by value.
19562 bool ByRef = false;
19563 if (IsTopScope && Kind != TryCaptureKind::Implicit) {
19564 ByRef = (Kind == TryCaptureKind::ExplicitByRef);
19565 } else {
19566 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
19567 }
19568
19569 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19571 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19572 Invalid = true;
19573 }
19574
19575 // Compute the type of the field that will capture this variable.
19576 if (ByRef) {
19577 // C++11 [expr.prim.lambda]p15:
19578 // An entity is captured by reference if it is implicitly or
19579 // explicitly captured but not captured by copy. It is
19580 // unspecified whether additional unnamed non-static data
19581 // members are declared in the closure type for entities
19582 // captured by reference.
19583 //
19584 // FIXME: It is not clear whether we want to build an lvalue reference
19585 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19586 // to do the former, while EDG does the latter. Core issue 1249 will
19587 // clarify, but for now we follow GCC because it's a more permissive and
19588 // easily defensible position.
19589 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19590 } else {
19591 // C++11 [expr.prim.lambda]p14:
19592 // For each entity captured by copy, an unnamed non-static
19593 // data member is declared in the closure type. The
19594 // declaration order of these members is unspecified. The type
19595 // of such a data member is the type of the corresponding
19596 // captured entity if the entity is not a reference to an
19597 // object, or the referenced type otherwise. [Note: If the
19598 // captured entity is a reference to a function, the
19599 // corresponding data member is also a reference to a
19600 // function. - end note ]
19601 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19602 if (!RefType->getPointeeType()->isFunctionType())
19603 CaptureType = RefType->getPointeeType();
19604 }
19605
19606 // Forbid the lambda copy-capture of autoreleasing variables.
19607 if (!Invalid &&
19609 if (BuildAndDiagnose) {
19610 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19611 S.Diag(Var->getLocation(), diag::note_previous_decl)
19612 << Var->getDeclName();
19613 Invalid = true;
19614 } else {
19615 return false;
19616 }
19617 }
19618
19619 // Make sure that by-copy captures are of a complete and non-abstract type.
19620 if (!Invalid && BuildAndDiagnose) {
19621 if (!CaptureType->isDependentType() &&
19623 Loc, CaptureType,
19624 diag::err_capture_of_incomplete_or_sizeless_type,
19625 Var->getDeclName()))
19626 Invalid = true;
19627 else if (S.RequireNonAbstractType(Loc, CaptureType,
19628 diag::err_capture_of_abstract_type))
19629 Invalid = true;
19630 }
19631 }
19632
19633 // Compute the type of a reference to this captured variable.
19634 if (ByRef)
19635 DeclRefType = CaptureType.getNonReferenceType();
19636 else {
19637 // C++ [expr.prim.lambda]p5:
19638 // The closure type for a lambda-expression has a public inline
19639 // function call operator [...]. This function call operator is
19640 // declared const (9.3.1) if and only if the lambda-expression's
19641 // parameter-declaration-clause is not followed by mutable.
19642 DeclRefType = CaptureType.getNonReferenceType();
19643 bool Const = LSI->lambdaCaptureShouldBeConst();
19644 // C++ [expr.prim.lambda]p10:
19645 // The type of such a data member is [...] an lvalue reference to the
19646 // referenced function type if the entity is a reference to a function.
19647 // [...]
19648 if (Const && !CaptureType->isReferenceType() &&
19649 !DeclRefType->isFunctionType())
19650 DeclRefType.addConst();
19651 }
19652
19653 // Add the capture.
19654 if (BuildAndDiagnose)
19655 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19656 Loc, EllipsisLoc, CaptureType, Invalid);
19657
19658 return !Invalid;
19659}
19660
19662 const ASTContext &Context) {
19663 // Offer a Copy fix even if the type is dependent.
19664 if (Var->getType()->isDependentType())
19665 return true;
19667 if (T.isTriviallyCopyableType(Context))
19668 return true;
19669 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19670
19671 if (!(RD = RD->getDefinition()))
19672 return false;
19673 if (RD->hasSimpleCopyConstructor())
19674 return true;
19675 if (RD->hasUserDeclaredCopyConstructor())
19676 for (CXXConstructorDecl *Ctor : RD->ctors())
19677 if (Ctor->isCopyConstructor())
19678 return !Ctor->isDeleted();
19679 }
19680 return false;
19681}
19682
19683/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19684/// default capture. Fixes may be omitted if they aren't allowed by the
19685/// standard, for example we can't emit a default copy capture fix-it if we
19686/// already explicitly copy capture capture another variable.
19688 ValueDecl *Var) {
19690 // Don't offer Capture by copy of default capture by copy fixes if Var is
19691 // known not to be copy constructible.
19692 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19693
19694 SmallString<32> FixBuffer;
19695 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19696 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19697 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19698 if (ShouldOfferCopyFix) {
19699 // Offer fixes to insert an explicit capture for the variable.
19700 // [] -> [VarName]
19701 // [OtherCapture] -> [OtherCapture, VarName]
19702 FixBuffer.assign({Separator, Var->getName()});
19703 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19704 << Var << /*value*/ 0
19705 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19706 }
19707 // As above but capture by reference.
19708 FixBuffer.assign({Separator, "&", Var->getName()});
19709 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19710 << Var << /*reference*/ 1
19711 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19712 }
19713
19714 // Only try to offer default capture if there are no captures excluding this
19715 // and init captures.
19716 // [this]: OK.
19717 // [X = Y]: OK.
19718 // [&A, &B]: Don't offer.
19719 // [A, B]: Don't offer.
19720 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19721 return !C.isThisCapture() && !C.isInitCapture();
19722 }))
19723 return;
19724
19725 // The default capture specifiers, '=' or '&', must appear first in the
19726 // capture body.
19727 SourceLocation DefaultInsertLoc =
19729
19730 if (ShouldOfferCopyFix) {
19731 bool CanDefaultCopyCapture = true;
19732 // [=, *this] OK since c++17
19733 // [=, this] OK since c++20
19734 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19735 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19737 : false;
19738 // We can't use default capture by copy if any captures already specified
19739 // capture by copy.
19740 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19741 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19742 })) {
19743 FixBuffer.assign({"=", Separator});
19744 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19745 << /*value*/ 0
19746 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19747 }
19748 }
19749
19750 // We can't use default capture by reference if any captures already specified
19751 // capture by reference.
19752 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19753 return !C.isInitCapture() && C.isReferenceCapture() &&
19754 !C.isThisCapture();
19755 })) {
19756 FixBuffer.assign({"&", Separator});
19757 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19758 << /*reference*/ 1
19759 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19760 }
19761}
19762
19764 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19765 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19766 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19767 // An init-capture is notionally from the context surrounding its
19768 // declaration, but its parent DC is the lambda class.
19769 DeclContext *VarDC = Var->getDeclContext();
19770 DeclContext *DC = CurContext;
19771
19772 // Skip past RequiresExprBodys because they don't constitute function scopes.
19773 while (DC->isRequiresExprBody())
19774 DC = DC->getParent();
19775
19776 // tryCaptureVariable is called every time a DeclRef is formed,
19777 // it can therefore have non-negigible impact on performances.
19778 // For local variables and when there is no capturing scope,
19779 // we can bailout early.
19780 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19781 return true;
19782
19783 // Exception: Function parameters are not tied to the function's DeclContext
19784 // until we enter the function definition. Capturing them anyway would result
19785 // in an out-of-bounds error while traversing DC and its parents.
19786 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
19787 return true;
19788
19789 const auto *VD = dyn_cast<VarDecl>(Var);
19790 if (VD) {
19791 if (VD->isInitCapture())
19792 VarDC = VarDC->getParent();
19793 } else {
19795 }
19796 assert(VD && "Cannot capture a null variable");
19797
19798 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19799 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19800 // We need to sync up the Declaration Context with the
19801 // FunctionScopeIndexToStopAt
19802 if (FunctionScopeIndexToStopAt) {
19803 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19804 unsigned FSIndex = FunctionScopes.size() - 1;
19805 // When we're parsing the lambda parameter list, the current DeclContext is
19806 // NOT the lambda but its parent. So move away the current LSI before
19807 // aligning DC and FunctionScopeIndexToStopAt.
19808 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
19809 FSIndex && LSI && !LSI->AfterParameterList)
19810 --FSIndex;
19811 assert(MaxFunctionScopesIndex <= FSIndex &&
19812 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19813 "FunctionScopes.");
19814 while (FSIndex != MaxFunctionScopesIndex) {
19816 --FSIndex;
19817 }
19818 }
19819
19820 // Capture global variables if it is required to use private copy of this
19821 // variable.
19822 bool IsGlobal = !VD->hasLocalStorage();
19823 if (IsGlobal && !(LangOpts.OpenMP &&
19824 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19825 MaxFunctionScopesIndex)))
19826 return true;
19827
19828 if (isa<VarDecl>(Var))
19829 Var = cast<VarDecl>(Var->getCanonicalDecl());
19830
19831 // Walk up the stack to determine whether we can capture the variable,
19832 // performing the "simple" checks that don't depend on type. We stop when
19833 // we've either hit the declared scope of the variable or find an existing
19834 // capture of that variable. We start from the innermost capturing-entity
19835 // (the DC) and ensure that all intervening capturing-entities
19836 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19837 // declcontext can either capture the variable or have already captured
19838 // the variable.
19839 CaptureType = Var->getType();
19840 DeclRefType = CaptureType.getNonReferenceType();
19841 bool Nested = false;
19842 bool Explicit = (Kind != TryCaptureKind::Implicit);
19843 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19844 do {
19845
19846 LambdaScopeInfo *LSI = nullptr;
19847 if (!FunctionScopes.empty())
19848 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19849 FunctionScopes[FunctionScopesIndex]);
19850
19851 bool IsInScopeDeclarationContext =
19852 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19853
19854 if (LSI && !LSI->AfterParameterList) {
19855 // This allows capturing parameters from a default value which does not
19856 // seems correct
19857 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19858 return true;
19859 }
19860 // If the variable is declared in the current context, there is no need to
19861 // capture it.
19862 if (IsInScopeDeclarationContext &&
19863 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19864 return true;
19865
19866 // Only block literals, captured statements, and lambda expressions can
19867 // capture; other scopes don't work.
19868 DeclContext *ParentDC =
19869 !IsInScopeDeclarationContext
19870 ? DC->getParent()
19871 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19872 BuildAndDiagnose, *this);
19873 // We need to check for the parent *first* because, if we *have*
19874 // private-captured a global variable, we need to recursively capture it in
19875 // intermediate blocks, lambdas, etc.
19876 if (!ParentDC) {
19877 if (IsGlobal) {
19878 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19879 break;
19880 }
19881 return true;
19882 }
19883
19884 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19886
19887 // Check whether we've already captured it.
19888 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19889 DeclRefType)) {
19890 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19891 break;
19892 }
19893
19894 // When evaluating some attributes (like enable_if) we might refer to a
19895 // function parameter appertaining to the same declaration as that
19896 // attribute.
19897 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19898 Parm && Parm->getDeclContext() == DC)
19899 return true;
19900
19901 // If we are instantiating a generic lambda call operator body,
19902 // we do not want to capture new variables. What was captured
19903 // during either a lambdas transformation or initial parsing
19904 // should be used.
19906 if (BuildAndDiagnose) {
19909 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19910 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19911 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19912 buildLambdaCaptureFixit(*this, LSI, Var);
19913 } else
19915 }
19916 return true;
19917 }
19918
19919 // Try to capture variable-length arrays types.
19920 if (Var->getType()->isVariablyModifiedType()) {
19921 // We're going to walk down into the type and look for VLA
19922 // expressions.
19923 QualType QTy = Var->getType();
19924 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19925 QTy = PVD->getOriginalType();
19927 }
19928
19929 if (getLangOpts().OpenMP) {
19930 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19931 // OpenMP private variables should not be captured in outer scope, so
19932 // just break here. Similarly, global variables that are captured in a
19933 // target region should not be captured outside the scope of the region.
19934 if (RSI->CapRegionKind == CR_OpenMP) {
19935 // FIXME: We should support capturing structured bindings in OpenMP.
19936 if (isa<BindingDecl>(Var)) {
19937 if (BuildAndDiagnose) {
19938 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19939 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19940 }
19941 return true;
19942 }
19943 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19944 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19945 // If the variable is private (i.e. not captured) and has variably
19946 // modified type, we still need to capture the type for correct
19947 // codegen in all regions, associated with the construct. Currently,
19948 // it is captured in the innermost captured region only.
19949 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19950 Var->getType()->isVariablyModifiedType()) {
19951 QualType QTy = Var->getType();
19952 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19953 QTy = PVD->getOriginalType();
19954 for (int I = 1,
19955 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
19956 I < E; ++I) {
19957 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19958 FunctionScopes[FunctionScopesIndex - I]);
19959 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19960 "Wrong number of captured regions associated with the "
19961 "OpenMP construct.");
19962 captureVariablyModifiedType(Context, QTy, OuterRSI);
19963 }
19964 }
19965 bool IsTargetCap =
19966 IsOpenMPPrivateDecl != OMPC_private &&
19967 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19968 RSI->OpenMPCaptureLevel);
19969 // Do not capture global if it is not privatized in outer regions.
19970 bool IsGlobalCap =
19971 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19972 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19973
19974 // When we detect target captures we are looking from inside the
19975 // target region, therefore we need to propagate the capture from the
19976 // enclosing region. Therefore, the capture is not initially nested.
19977 if (IsTargetCap)
19978 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19979 RSI->OpenMPLevel);
19980
19981 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19982 (IsGlobal && !IsGlobalCap)) {
19983 Nested = !IsTargetCap;
19984 bool HasConst = DeclRefType.isConstQualified();
19985 DeclRefType = DeclRefType.getUnqualifiedType();
19986 // Don't lose diagnostics about assignments to const.
19987 if (HasConst)
19988 DeclRefType.addConst();
19989 CaptureType = Context.getLValueReferenceType(DeclRefType);
19990 break;
19991 }
19992 }
19993 }
19994 }
19996 // No capture-default, and this is not an explicit capture
19997 // so cannot capture this variable.
19998 if (BuildAndDiagnose) {
19999 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
20000 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
20001 auto *LSI = cast<LambdaScopeInfo>(CSI);
20002 if (LSI->Lambda) {
20003 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
20004 buildLambdaCaptureFixit(*this, LSI, Var);
20005 }
20006 // FIXME: If we error out because an outer lambda can not implicitly
20007 // capture a variable that an inner lambda explicitly captures, we
20008 // should have the inner lambda do the explicit capture - because
20009 // it makes for cleaner diagnostics later. This would purely be done
20010 // so that the diagnostic does not misleadingly claim that a variable
20011 // can not be captured by a lambda implicitly even though it is captured
20012 // explicitly. Suggestion:
20013 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
20014 // at the function head
20015 // - cache the StartingDeclContext - this must be a lambda
20016 // - captureInLambda in the innermost lambda the variable.
20017 }
20018 return true;
20019 }
20020 Explicit = false;
20021 FunctionScopesIndex--;
20022 if (IsInScopeDeclarationContext)
20023 DC = ParentDC;
20024 } while (!VarDC->Equals(DC));
20025
20026 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
20027 // computing the type of the capture at each step, checking type-specific
20028 // requirements, and adding captures if requested.
20029 // If the variable had already been captured previously, we start capturing
20030 // at the lambda nested within that one.
20031 bool Invalid = false;
20032 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
20033 ++I) {
20035
20036 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
20037 // certain types of variables (unnamed, variably modified types etc.)
20038 // so check for eligibility.
20039 if (!Invalid)
20040 Invalid =
20041 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
20042
20043 // After encountering an error, if we're actually supposed to capture, keep
20044 // capturing in nested contexts to suppress any follow-on diagnostics.
20045 if (Invalid && !BuildAndDiagnose)
20046 return true;
20047
20048 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
20049 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20050 DeclRefType, Nested, *this, Invalid);
20051 Nested = true;
20052 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
20054 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
20055 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
20056 Nested = true;
20057 } else {
20059 Invalid =
20060 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
20061 DeclRefType, Nested, Kind, EllipsisLoc,
20062 /*IsTopScope*/ I == N - 1, *this, Invalid);
20063 Nested = true;
20064 }
20065
20066 if (Invalid && !BuildAndDiagnose)
20067 return true;
20068 }
20069 return Invalid;
20070}
20071
20073 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
20074 QualType CaptureType;
20075 QualType DeclRefType;
20076 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
20077 /*BuildAndDiagnose=*/true, CaptureType,
20078 DeclRefType, nullptr);
20079}
20080
20082 QualType CaptureType;
20083 QualType DeclRefType;
20084 return !tryCaptureVariable(
20086 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType, nullptr);
20087}
20088
20090 assert(Var && "Null value cannot be captured");
20091
20092 QualType CaptureType;
20093 QualType DeclRefType;
20094
20095 // Determine whether we can capture this variable.
20097 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType,
20098 nullptr))
20099 return QualType();
20100
20101 return DeclRefType;
20102}
20103
20104namespace {
20105// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20106// The produced TemplateArgumentListInfo* points to data stored within this
20107// object, so should only be used in contexts where the pointer will not be
20108// used after the CopiedTemplateArgs object is destroyed.
20109class CopiedTemplateArgs {
20110 bool HasArgs;
20111 TemplateArgumentListInfo TemplateArgStorage;
20112public:
20113 template<typename RefExpr>
20114 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
20115 if (HasArgs)
20116 E->copyTemplateArgumentsInto(TemplateArgStorage);
20117 }
20118 operator TemplateArgumentListInfo*()
20119#ifdef __has_cpp_attribute
20120#if __has_cpp_attribute(clang::lifetimebound)
20121 [[clang::lifetimebound]]
20122#endif
20123#endif
20124 {
20125 return HasArgs ? &TemplateArgStorage : nullptr;
20126 }
20127};
20128}
20129
20130/// Walk the set of potential results of an expression and mark them all as
20131/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20132///
20133/// \return A new expression if we found any potential results, ExprEmpty() if
20134/// not, and ExprError() if we diagnosed an error.
20136 NonOdrUseReason NOUR) {
20137 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20138 // an object that satisfies the requirements for appearing in a
20139 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20140 // is immediately applied." This function handles the lvalue-to-rvalue
20141 // conversion part.
20142 //
20143 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20144 // transform it into the relevant kind of non-odr-use node and rebuild the
20145 // tree of nodes leading to it.
20146 //
20147 // This is a mini-TreeTransform that only transforms a restricted subset of
20148 // nodes (and only certain operands of them).
20149
20150 // Rebuild a subexpression.
20151 auto Rebuild = [&](Expr *Sub) {
20152 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
20153 };
20154
20155 // Check whether a potential result satisfies the requirements of NOUR.
20156 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
20157 // Any entity other than a VarDecl is always odr-used whenever it's named
20158 // in a potentially-evaluated expression.
20159 auto *VD = dyn_cast<VarDecl>(D);
20160 if (!VD)
20161 return true;
20162
20163 // C++2a [basic.def.odr]p4:
20164 // A variable x whose name appears as a potentially-evalauted expression
20165 // e is odr-used by e unless
20166 // -- x is a reference that is usable in constant expressions, or
20167 // -- x is a variable of non-reference type that is usable in constant
20168 // expressions and has no mutable subobjects, and e is an element of
20169 // the set of potential results of an expression of
20170 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20171 // conversion is applied, or
20172 // -- x is a variable of non-reference type, and e is an element of the
20173 // set of potential results of a discarded-value expression to which
20174 // the lvalue-to-rvalue conversion is not applied
20175 //
20176 // We check the first bullet and the "potentially-evaluated" condition in
20177 // BuildDeclRefExpr. We check the type requirements in the second bullet
20178 // in CheckLValueToRValueConversionOperand below.
20179 switch (NOUR) {
20180 case NOUR_None:
20181 case NOUR_Unevaluated:
20182 llvm_unreachable("unexpected non-odr-use-reason");
20183
20184 case NOUR_Constant:
20185 // Constant references were handled when they were built.
20186 if (VD->getType()->isReferenceType())
20187 return true;
20188 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
20189 if (RD->hasDefinition() && RD->hasMutableFields())
20190 return true;
20191 if (!VD->isUsableInConstantExpressions(S.Context))
20192 return true;
20193 break;
20194
20195 case NOUR_Discarded:
20196 if (VD->getType()->isReferenceType())
20197 return true;
20198 break;
20199 }
20200 return false;
20201 };
20202
20203 // Check whether this expression may be odr-used in CUDA/HIP.
20204 auto MaybeCUDAODRUsed = [&]() -> bool {
20205 if (!S.LangOpts.CUDA)
20206 return false;
20207 LambdaScopeInfo *LSI = S.getCurLambda();
20208 if (!LSI)
20209 return false;
20210 auto *DRE = dyn_cast<DeclRefExpr>(E);
20211 if (!DRE)
20212 return false;
20213 auto *VD = dyn_cast<VarDecl>(DRE->getDecl());
20214 if (!VD)
20215 return false;
20216 return LSI->CUDAPotentialODRUsedVars.count(VD);
20217 };
20218
20219 // Mark that this expression does not constitute an odr-use.
20220 auto MarkNotOdrUsed = [&] {
20221 if (!MaybeCUDAODRUsed()) {
20222 S.MaybeODRUseExprs.remove(E);
20223 if (LambdaScopeInfo *LSI = S.getCurLambda())
20224 LSI->markVariableExprAsNonODRUsed(E);
20225 }
20226 };
20227
20228 // C++2a [basic.def.odr]p2:
20229 // The set of potential results of an expression e is defined as follows:
20230 switch (E->getStmtClass()) {
20231 // -- If e is an id-expression, ...
20232 case Expr::DeclRefExprClass: {
20233 auto *DRE = cast<DeclRefExpr>(E);
20234 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
20235 break;
20236
20237 // Rebuild as a non-odr-use DeclRefExpr.
20238 MarkNotOdrUsed();
20239 return DeclRefExpr::Create(
20240 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
20241 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
20242 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
20243 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
20244 }
20245
20246 case Expr::FunctionParmPackExprClass: {
20247 auto *FPPE = cast<FunctionParmPackExpr>(E);
20248 // If any of the declarations in the pack is odr-used, then the expression
20249 // as a whole constitutes an odr-use.
20250 for (ValueDecl *D : *FPPE)
20251 if (IsPotentialResultOdrUsed(D))
20252 return ExprEmpty();
20253
20254 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20255 // nothing cares about whether we marked this as an odr-use, but it might
20256 // be useful for non-compiler tools.
20257 MarkNotOdrUsed();
20258 break;
20259 }
20260
20261 // -- If e is a subscripting operation with an array operand...
20262 case Expr::ArraySubscriptExprClass: {
20263 auto *ASE = cast<ArraySubscriptExpr>(E);
20264 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
20265 if (!OldBase->getType()->isArrayType())
20266 break;
20267 ExprResult Base = Rebuild(OldBase);
20268 if (!Base.isUsable())
20269 return Base;
20270 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
20271 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
20272 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
20273 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
20274 ASE->getRBracketLoc());
20275 }
20276
20277 case Expr::MemberExprClass: {
20278 auto *ME = cast<MemberExpr>(E);
20279 // -- If e is a class member access expression [...] naming a non-static
20280 // data member...
20281 if (isa<FieldDecl>(ME->getMemberDecl())) {
20282 ExprResult Base = Rebuild(ME->getBase());
20283 if (!Base.isUsable())
20284 return Base;
20285 return MemberExpr::Create(
20286 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
20287 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
20288 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
20289 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
20290 ME->getObjectKind(), ME->isNonOdrUse());
20291 }
20292
20293 if (ME->getMemberDecl()->isCXXInstanceMember())
20294 break;
20295
20296 // -- If e is a class member access expression naming a static data member,
20297 // ...
20298 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
20299 break;
20300
20301 // Rebuild as a non-odr-use MemberExpr.
20302 MarkNotOdrUsed();
20303 return MemberExpr::Create(
20304 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
20305 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
20306 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
20307 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
20308 }
20309
20310 case Expr::BinaryOperatorClass: {
20311 auto *BO = cast<BinaryOperator>(E);
20312 Expr *LHS = BO->getLHS();
20313 Expr *RHS = BO->getRHS();
20314 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20315 if (BO->getOpcode() == BO_PtrMemD) {
20316 ExprResult Sub = Rebuild(LHS);
20317 if (!Sub.isUsable())
20318 return Sub;
20319 BO->setLHS(Sub.get());
20320 // -- If e is a comma expression, ...
20321 } else if (BO->getOpcode() == BO_Comma) {
20322 ExprResult Sub = Rebuild(RHS);
20323 if (!Sub.isUsable())
20324 return Sub;
20325 BO->setRHS(Sub.get());
20326 } else {
20327 break;
20328 }
20329 return ExprResult(BO);
20330 }
20331
20332 // -- If e has the form (e1)...
20333 case Expr::ParenExprClass: {
20334 auto *PE = cast<ParenExpr>(E);
20335 ExprResult Sub = Rebuild(PE->getSubExpr());
20336 if (!Sub.isUsable())
20337 return Sub;
20338 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
20339 }
20340
20341 // -- If e is a glvalue conditional expression, ...
20342 // We don't apply this to a binary conditional operator. FIXME: Should we?
20343 case Expr::ConditionalOperatorClass: {
20344 auto *CO = cast<ConditionalOperator>(E);
20345 ExprResult LHS = Rebuild(CO->getLHS());
20346 if (LHS.isInvalid())
20347 return ExprError();
20348 ExprResult RHS = Rebuild(CO->getRHS());
20349 if (RHS.isInvalid())
20350 return ExprError();
20351 if (!LHS.isUsable() && !RHS.isUsable())
20352 return ExprEmpty();
20353 if (!LHS.isUsable())
20354 LHS = CO->getLHS();
20355 if (!RHS.isUsable())
20356 RHS = CO->getRHS();
20357 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
20358 CO->getCond(), LHS.get(), RHS.get());
20359 }
20360
20361 // [Clang extension]
20362 // -- If e has the form __extension__ e1...
20363 case Expr::UnaryOperatorClass: {
20364 auto *UO = cast<UnaryOperator>(E);
20365 if (UO->getOpcode() != UO_Extension)
20366 break;
20367 ExprResult Sub = Rebuild(UO->getSubExpr());
20368 if (!Sub.isUsable())
20369 return Sub;
20370 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
20371 Sub.get());
20372 }
20373
20374 // [Clang extension]
20375 // -- If e has the form _Generic(...), the set of potential results is the
20376 // union of the sets of potential results of the associated expressions.
20377 case Expr::GenericSelectionExprClass: {
20378 auto *GSE = cast<GenericSelectionExpr>(E);
20379
20380 SmallVector<Expr *, 4> AssocExprs;
20381 bool AnyChanged = false;
20382 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
20383 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
20384 if (AssocExpr.isInvalid())
20385 return ExprError();
20386 if (AssocExpr.isUsable()) {
20387 AssocExprs.push_back(AssocExpr.get());
20388 AnyChanged = true;
20389 } else {
20390 AssocExprs.push_back(OrigAssocExpr);
20391 }
20392 }
20393
20394 void *ExOrTy = nullptr;
20395 bool IsExpr = GSE->isExprPredicate();
20396 if (IsExpr)
20397 ExOrTy = GSE->getControllingExpr();
20398 else
20399 ExOrTy = GSE->getControllingType();
20400 return AnyChanged ? S.CreateGenericSelectionExpr(
20401 GSE->getGenericLoc(), GSE->getDefaultLoc(),
20402 GSE->getRParenLoc(), IsExpr, ExOrTy,
20403 GSE->getAssocTypeSourceInfos(), AssocExprs)
20404 : ExprEmpty();
20405 }
20406
20407 // [Clang extension]
20408 // -- If e has the form __builtin_choose_expr(...), the set of potential
20409 // results is the union of the sets of potential results of the
20410 // second and third subexpressions.
20411 case Expr::ChooseExprClass: {
20412 auto *CE = cast<ChooseExpr>(E);
20413
20414 ExprResult LHS = Rebuild(CE->getLHS());
20415 if (LHS.isInvalid())
20416 return ExprError();
20417
20418 ExprResult RHS = Rebuild(CE->getLHS());
20419 if (RHS.isInvalid())
20420 return ExprError();
20421
20422 if (!LHS.get() && !RHS.get())
20423 return ExprEmpty();
20424 if (!LHS.isUsable())
20425 LHS = CE->getLHS();
20426 if (!RHS.isUsable())
20427 RHS = CE->getRHS();
20428
20429 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
20430 RHS.get(), CE->getRParenLoc());
20431 }
20432
20433 // Step through non-syntactic nodes.
20434 case Expr::ConstantExprClass: {
20435 auto *CE = cast<ConstantExpr>(E);
20436 ExprResult Sub = Rebuild(CE->getSubExpr());
20437 if (!Sub.isUsable())
20438 return Sub;
20439 return ConstantExpr::Create(S.Context, Sub.get());
20440 }
20441
20442 // We could mostly rely on the recursive rebuilding to rebuild implicit
20443 // casts, but not at the top level, so rebuild them here.
20444 case Expr::ImplicitCastExprClass: {
20445 auto *ICE = cast<ImplicitCastExpr>(E);
20446 // Only step through the narrow set of cast kinds we expect to encounter.
20447 // Anything else suggests we've left the region in which potential results
20448 // can be found.
20449 switch (ICE->getCastKind()) {
20450 case CK_NoOp:
20451 case CK_DerivedToBase:
20452 case CK_UncheckedDerivedToBase: {
20453 ExprResult Sub = Rebuild(ICE->getSubExpr());
20454 if (!Sub.isUsable())
20455 return Sub;
20456 CXXCastPath Path(ICE->path());
20457 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
20458 ICE->getValueKind(), &Path);
20459 }
20460
20461 default:
20462 break;
20463 }
20464 break;
20465 }
20466
20467 default:
20468 break;
20469 }
20470
20471 // Can't traverse through this node. Nothing to do.
20472 return ExprEmpty();
20473}
20474
20476 // Check whether the operand is or contains an object of non-trivial C union
20477 // type.
20478 if (E->getType().isVolatileQualified() &&
20484
20485 // C++2a [basic.def.odr]p4:
20486 // [...] an expression of non-volatile-qualified non-class type to which
20487 // the lvalue-to-rvalue conversion is applied [...]
20488 if (E->getType().isVolatileQualified() || E->getType()->isRecordType())
20489 return E;
20490
20493 if (Result.isInvalid())
20494 return ExprError();
20495 return Result.get() ? Result : E;
20496}
20497
20499 if (!Res.isUsable())
20500 return Res;
20501
20502 // If a constant-expression is a reference to a variable where we delay
20503 // deciding whether it is an odr-use, just assume we will apply the
20504 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20505 // (a non-type template argument), we have special handling anyway.
20507}
20508
20510 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20511 // call.
20512 MaybeODRUseExprSet LocalMaybeODRUseExprs;
20513 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
20514
20515 for (Expr *E : LocalMaybeODRUseExprs) {
20516 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
20517 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
20518 DRE->getLocation(), *this);
20519 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
20520 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
20521 *this);
20522 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
20523 for (ValueDecl *VD : *FP)
20524 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
20525 } else {
20526 llvm_unreachable("Unexpected expression");
20527 }
20528 }
20529
20530 assert(MaybeODRUseExprs.empty() &&
20531 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20532}
20533
20535 ValueDecl *Var, Expr *E) {
20537 if (!VD)
20538 return;
20539
20540 const bool RefersToEnclosingScope =
20541 (SemaRef.CurContext != VD->getDeclContext() &&
20543 if (RefersToEnclosingScope) {
20544 LambdaScopeInfo *const LSI =
20545 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20546 if (LSI && (!LSI->CallOperator ||
20547 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
20548 // If a variable could potentially be odr-used, defer marking it so
20549 // until we finish analyzing the full expression for any
20550 // lvalue-to-rvalue
20551 // or discarded value conversions that would obviate odr-use.
20552 // Add it to the list of potential captures that will be analyzed
20553 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20554 // unless the variable is a reference that was initialized by a constant
20555 // expression (this will never need to be captured or odr-used).
20556 //
20557 // FIXME: We can simplify this a lot after implementing P0588R1.
20558 assert(E && "Capture variable should be used in an expression.");
20559 if (!Var->getType()->isReferenceType() ||
20562 }
20563 }
20564}
20565
20567 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
20568 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20569 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
20571 "Invalid Expr argument to DoMarkVarDeclReferenced");
20572 Var->setReferenced();
20573
20574 if (Var->isInvalidDecl())
20575 return;
20576
20577 auto *MSI = Var->getMemberSpecializationInfo();
20578 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
20580
20581 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20582 bool UsableInConstantExpr =
20584
20585 // Only track variables with internal linkage or local scope.
20586 // Use canonical decl so in-class declarations and out-of-class definitions
20587 // of static data members in anonymous namespaces are tracked as a single
20588 // entry.
20589 const VarDecl *CanonVar = Var->getCanonicalDecl();
20590 if ((CanonVar->isLocalVarDeclOrParm() ||
20591 CanonVar->isInternalLinkageFileVar()) &&
20592 !CanonVar->hasExternalStorage()) {
20593 RefsMinusAssignments.insert({CanonVar, 0}).first->getSecond()++;
20594 }
20595
20596 // C++20 [expr.const]p12:
20597 // A variable [...] is needed for constant evaluation if it is [...] a
20598 // variable whose name appears as a potentially constant evaluated
20599 // expression that is either a contexpr variable or is of non-volatile
20600 // const-qualified integral type or of reference type
20601 bool NeededForConstantEvaluation =
20602 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
20603
20604 bool NeedDefinition =
20605 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation ||
20606 (TSK != clang::TSK_Undeclared && !UsableInConstantExpr &&
20607 Var->getType()->isUndeducedType());
20608
20610 "Can't instantiate a partial template specialization.");
20611
20612 // If this might be a member specialization of a static data member, check
20613 // the specialization is visible. We already did the checks for variable
20614 // template specializations when we created them.
20615 if (NeedDefinition && TSK != TSK_Undeclared &&
20618
20619 // Perform implicit instantiation of static data members, static data member
20620 // templates of class templates, and variable template specializations. Delay
20621 // instantiations of variable templates, except for those that could be used
20622 // in a constant expression.
20623 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20624 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20625 // instantiation declaration if a variable is usable in a constant
20626 // expression (among other cases).
20627 bool TryInstantiating =
20629 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20630
20631 if (TryInstantiating) {
20632 SourceLocation PointOfInstantiation =
20633 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20634 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20635 if (FirstInstantiation) {
20636 PointOfInstantiation = Loc;
20637 if (MSI)
20638 MSI->setPointOfInstantiation(PointOfInstantiation);
20639 // FIXME: Notify listener.
20640 else
20641 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20642 }
20643
20644 if (UsableInConstantExpr || Var->getType()->isUndeducedType()) {
20645 // Do not defer instantiations of variables that could be used in a
20646 // constant expression.
20647 // The type deduction also needs a complete initializer.
20648 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20649 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20650 });
20651
20652 // The size of an incomplete array type can be updated by
20653 // instantiating the initializer. The DeclRefExpr's type should be
20654 // updated accordingly too, or users of it would be confused!
20655 if (E)
20657
20658 // Re-set the member to trigger a recomputation of the dependence bits
20659 // for the expression.
20660 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20661 DRE->setDecl(DRE->getDecl());
20662 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20663 ME->setMemberDecl(ME->getMemberDecl());
20664 } else if (FirstInstantiation) {
20666 .push_back(std::make_pair(Var, PointOfInstantiation));
20667 } else {
20668 bool Inserted = false;
20669 for (auto &I : SemaRef.SavedPendingInstantiations) {
20670 auto Iter = llvm::find_if(
20671 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20672 return P.first == Var;
20673 });
20674 if (Iter != I.end()) {
20675 SemaRef.PendingInstantiations.push_back(*Iter);
20676 I.erase(Iter);
20677 Inserted = true;
20678 break;
20679 }
20680 }
20681
20682 // FIXME: For a specialization of a variable template, we don't
20683 // distinguish between "declaration and type implicitly instantiated"
20684 // and "implicit instantiation of definition requested", so we have
20685 // no direct way to avoid enqueueing the pending instantiation
20686 // multiple times.
20687 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20689 .push_back(std::make_pair(Var, PointOfInstantiation));
20690 }
20691 }
20692 }
20693
20694 // C++2a [basic.def.odr]p4:
20695 // A variable x whose name appears as a potentially-evaluated expression e
20696 // is odr-used by e unless
20697 // -- x is a reference that is usable in constant expressions
20698 // -- x is a variable of non-reference type that is usable in constant
20699 // expressions and has no mutable subobjects [FIXME], and e is an
20700 // element of the set of potential results of an expression of
20701 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20702 // conversion is applied
20703 // -- x is a variable of non-reference type, and e is an element of the set
20704 // of potential results of a discarded-value expression to which the
20705 // lvalue-to-rvalue conversion is not applied [FIXME]
20706 //
20707 // We check the first part of the second bullet here, and
20708 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20709 // FIXME: To get the third bullet right, we need to delay this even for
20710 // variables that are not usable in constant expressions.
20711
20712 // If we already know this isn't an odr-use, there's nothing more to do.
20713 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20714 if (DRE->isNonOdrUse())
20715 return;
20716 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20717 if (ME->isNonOdrUse())
20718 return;
20719
20720 switch (OdrUse) {
20721 case OdrUseContext::None:
20722 // In some cases, a variable may not have been marked unevaluated, if it
20723 // appears in a defaukt initializer.
20724 assert((!E || isa<FunctionParmPackExpr>(E) ||
20726 "missing non-odr-use marking for unevaluated decl ref");
20727 break;
20728
20729 case OdrUseContext::FormallyOdrUsed:
20730 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20731 // behavior.
20732 break;
20733
20734 case OdrUseContext::Used:
20735 // If we might later find that this expression isn't actually an odr-use,
20736 // delay the marking.
20738 SemaRef.MaybeODRUseExprs.insert(E);
20739 else
20740 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20741 break;
20742
20743 case OdrUseContext::Dependent:
20744 // If this is a dependent context, we don't need to mark variables as
20745 // odr-used, but we may still need to track them for lambda capture.
20746 // FIXME: Do we also need to do this inside dependent typeid expressions
20747 // (which are modeled as unevaluated at this point)?
20748 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20749 break;
20750 }
20751}
20752
20754 BindingDecl *BD, Expr *E) {
20755 BD->setReferenced();
20756
20757 if (BD->isInvalidDecl())
20758 return;
20759
20760 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20761 if (OdrUse == OdrUseContext::Used) {
20762 QualType CaptureType, DeclRefType;
20764 /*EllipsisLoc*/ SourceLocation(),
20765 /*BuildAndDiagnose*/ true, CaptureType,
20766 DeclRefType,
20767 /*FunctionScopeIndexToStopAt*/ nullptr);
20768 } else if (OdrUse == OdrUseContext::Dependent) {
20769 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20770 }
20771}
20772
20774 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20775}
20776
20777// C++ [temp.dep.expr]p3:
20778// An id-expression is type-dependent if it contains:
20779// - an identifier associated by name lookup with an entity captured by copy
20780// in a lambda-expression that has an explicit object parameter whose type
20781// is dependent ([dcl.fct]),
20783 Sema &SemaRef, ValueDecl *D, Expr *E) {
20784 auto *ID = dyn_cast<DeclRefExpr>(E);
20785 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20786 return;
20787
20788 // If any enclosing lambda with a dependent explicit object parameter either
20789 // explicitly captures the variable by value, or has a capture default of '='
20790 // and does not capture the variable by reference, then the type of the DRE
20791 // is dependent on the type of that lambda's explicit object parameter.
20792 auto IsDependent = [&]() {
20793 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
20794 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
20795 if (!LSI)
20796 continue;
20797
20798 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
20799 LSI->AfterParameterList)
20800 return false;
20801
20802 const auto *MD = LSI->CallOperator;
20803 if (MD->getType().isNull())
20804 continue;
20805
20806 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20807 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20808 !Ty->getParamType(0)->isDependentType())
20809 continue;
20810
20811 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
20812 if (C->isCopyCapture())
20813 return true;
20814 continue;
20815 }
20816
20817 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20818 return true;
20819 }
20820 return false;
20821 }();
20822
20823 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20824 IsDependent, SemaRef.getASTContext());
20825}
20826
20827static void
20829 bool MightBeOdrUse,
20830 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20833
20834 if (SemaRef.getLangOpts().OpenACC)
20835 SemaRef.OpenACC().CheckDeclReference(Loc, E, D);
20836
20837 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20839 if (SemaRef.getLangOpts().CPlusPlus)
20841 Var, E);
20842 return;
20843 }
20844
20845 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20847 if (SemaRef.getLangOpts().CPlusPlus)
20849 Decl, E);
20850 return;
20851 }
20852 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20853
20854 // If this is a call to a method via a cast, also mark the method in the
20855 // derived class used in case codegen can devirtualize the call.
20856 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20857 if (!ME)
20858 return;
20859 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20860 if (!MD)
20861 return;
20862 // Only attempt to devirtualize if this is truly a virtual call.
20863 bool IsVirtualCall = MD->isVirtual() &&
20865 if (!IsVirtualCall)
20866 return;
20867
20868 // If it's possible to devirtualize the call, mark the called function
20869 // referenced.
20871 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20872 if (DM)
20873 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20874}
20875
20877 // [basic.def.odr] (CWG 1614)
20878 // A function is named by an expression or conversion [...]
20879 // unless it is a pure virtual function and either the expression is not an
20880 // id-expression naming the function with an explicitly qualified name or
20881 // the expression forms a pointer to member
20882 bool OdrUse = true;
20883 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20884 if (Method->isVirtual() &&
20885 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20886 OdrUse = false;
20887
20888 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20892 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20893 !FD->isDependentContext())
20894 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20895 }
20896 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20898}
20899
20901 // C++11 [basic.def.odr]p2:
20902 // A non-overloaded function whose name appears as a potentially-evaluated
20903 // expression or a member of a set of candidate functions, if selected by
20904 // overload resolution when referred to from a potentially-evaluated
20905 // expression, is odr-used, unless it is a pure virtual function and its
20906 // name is not explicitly qualified.
20907 bool MightBeOdrUse = true;
20909 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20910 if (Method->isPureVirtual())
20911 MightBeOdrUse = false;
20912 }
20913 SourceLocation Loc =
20914 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20915 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20917}
20918
20924
20925/// Perform marking for a reference to an arbitrary declaration. It
20926/// marks the declaration referenced, and performs odr-use checking for
20927/// functions and variables. This method should not be used when building a
20928/// normal expression which refers to a variable.
20930 bool MightBeOdrUse) {
20931 if (MightBeOdrUse) {
20932 if (auto *VD = dyn_cast<VarDecl>(D)) {
20933 MarkVariableReferenced(Loc, VD);
20934 return;
20935 }
20936 }
20937 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20938 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20939 return;
20940 }
20941 D->setReferenced();
20942}
20943
20944namespace {
20945 // Mark all of the declarations used by a type as referenced.
20946 // FIXME: Not fully implemented yet! We need to have a better understanding
20947 // of when we're entering a context we should not recurse into.
20948 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20949 // TreeTransforms rebuilding the type in a new context. Rather than
20950 // duplicating the TreeTransform logic, we should consider reusing it here.
20951 // Currently that causes problems when rebuilding LambdaExprs.
20952class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20953 Sema &S;
20954 SourceLocation Loc;
20955
20956public:
20957 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20958
20959 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20960};
20961}
20962
20963bool MarkReferencedDecls::TraverseTemplateArgument(
20964 const TemplateArgument &Arg) {
20965 {
20966 // A non-type template argument is a constant-evaluated context.
20967 EnterExpressionEvaluationContext Evaluated(
20970 if (Decl *D = Arg.getAsDecl())
20971 S.MarkAnyDeclReferenced(Loc, D, true);
20972 } else if (Arg.getKind() == TemplateArgument::Expression) {
20974 }
20975 }
20976
20978}
20979
20981 MarkReferencedDecls Marker(*this, Loc);
20982 Marker.TraverseType(T);
20983}
20984
20985namespace {
20986/// Helper class that marks all of the declarations referenced by
20987/// potentially-evaluated subexpressions as "referenced".
20988class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20989public:
20990 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20991 bool SkipLocalVariables;
20993
20994 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20996 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20997
20998 void visitUsedDecl(SourceLocation Loc, Decl *D) {
21000 }
21001
21002 void Visit(Expr *E) {
21003 if (llvm::is_contained(StopAt, E))
21004 return;
21005 Inherited::Visit(E);
21006 }
21007
21008 void VisitConstantExpr(ConstantExpr *E) {
21009 // Don't mark declarations within a ConstantExpression, as this expression
21010 // will be evaluated and folded to a value.
21011 }
21012
21013 void VisitDeclRefExpr(DeclRefExpr *E) {
21014 // If we were asked not to visit local variables, don't.
21015 if (SkipLocalVariables) {
21016 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
21017 if (VD->hasLocalStorage())
21018 return;
21019 }
21020
21021 // FIXME: This can trigger the instantiation of the initializer of a
21022 // variable, which can cause the expression to become value-dependent
21023 // or error-dependent. Do we need to propagate the new dependence bits?
21025 }
21026
21027 void VisitMemberExpr(MemberExpr *E) {
21029 Visit(E->getBase());
21030 }
21031};
21032} // namespace
21033
21035 bool SkipLocalVariables,
21036 ArrayRef<const Expr*> StopAt) {
21037 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
21038}
21039
21040/// Emit a diagnostic when statements are reachable.
21042 const PartialDiagnostic &PD) {
21043 VarDecl *Decl = ExprEvalContexts.back().DeclForInitializer;
21044 // The initializer of a constexpr variable or of the first declaration of a
21045 // static data member is not syntactically a constant evaluated constant,
21046 // but nonetheless is always required to be a constant expression, so we
21047 // can skip diagnosing.
21048 if (Decl &&
21049 (Decl->isConstexpr() || (Decl->isStaticDataMember() &&
21050 Decl->isFirstDecl() && !Decl->isInline())))
21051 return false;
21052
21053 if (Stmts.empty()) {
21054 Diag(Loc, PD);
21055 return true;
21056 }
21057
21058 if (getCurFunction()) {
21059 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
21060 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21061 return true;
21062 }
21063
21064 // For non-constexpr file-scope variables with reachability context (non-empty
21065 // Stmts), build a CFG for the initializer and check whether the context in
21066 // question is reachable.
21067 if (Decl && Decl->isFileVarDecl()) {
21068 AnalysisWarnings.registerVarDeclWarning(
21069 Decl, sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
21070 return true;
21071 }
21072
21073 Diag(Loc, PD);
21074 return true;
21075}
21076
21077/// Emit a diagnostic that describes an effect on the run-time behavior
21078/// of the program being compiled.
21079///
21080/// This routine emits the given diagnostic when the code currently being
21081/// type-checked is "potentially evaluated", meaning that there is a
21082/// possibility that the code will actually be executable. Code in sizeof()
21083/// expressions, code used only during overload resolution, etc., are not
21084/// potentially evaluated. This routine will suppress such diagnostics or,
21085/// in the absolutely nutty case of potentially potentially evaluated
21086/// expressions (C++ typeid), queue the diagnostic to potentially emit it
21087/// later.
21088///
21089/// This routine should be used for all diagnostics that describe the run-time
21090/// behavior of a program, such as passing a non-POD value through an ellipsis.
21091/// Failure to do so will likely result in spurious diagnostics or failures
21092/// during overload resolution or within sizeof/alignof/typeof/typeid.
21094 const PartialDiagnostic &PD) {
21095
21096 if (ExprEvalContexts.back().isDiscardedStatementContext())
21097 return false;
21098
21099 switch (ExprEvalContexts.back().Context) {
21104 // The argument will never be evaluated, so don't complain.
21105 break;
21106
21109 // Relevant diagnostics should be produced by constant evaluation.
21110 break;
21111
21114 return DiagIfReachable(Loc, Stmts, PD);
21115 }
21116
21117 return false;
21118}
21119
21121 const PartialDiagnostic &PD) {
21122 return DiagRuntimeBehavior(
21123 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
21124 PD);
21125}
21126
21128 CallExpr *CE, FunctionDecl *FD) {
21129 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
21130 return false;
21131
21132 // If we're inside a decltype's expression, don't check for a valid return
21133 // type or construct temporaries until we know whether this is the last call.
21134 if (ExprEvalContexts.back().ExprContext ==
21136 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
21137 return false;
21138 }
21139
21140 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
21141 FunctionDecl *FD;
21142 CallExpr *CE;
21143
21144 public:
21145 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
21146 : FD(FD), CE(CE) { }
21147
21148 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
21149 if (!FD) {
21150 S.Diag(Loc, diag::err_call_incomplete_return)
21151 << T << CE->getSourceRange();
21152 return;
21153 }
21154
21155 S.Diag(Loc, diag::err_call_function_incomplete_return)
21156 << CE->getSourceRange() << FD << T;
21157 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
21158 << FD->getDeclName();
21159 }
21160 } Diagnoser(FD, CE);
21161
21162 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
21163 return true;
21164
21165 return false;
21166}
21167
21168// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21169// will prevent this condition from triggering, which is what we want.
21171 SourceLocation Loc;
21172
21173 unsigned diagnostic = diag::warn_condition_is_assignment;
21174 bool IsOrAssign = false;
21175
21176 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
21177 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
21178 return;
21179
21180 IsOrAssign = Op->getOpcode() == BO_OrAssign;
21181
21182 // Greylist some idioms by putting them into a warning subcategory.
21183 if (ObjCMessageExpr *ME
21184 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
21185 Selector Sel = ME->getSelector();
21186
21187 // self = [<foo> init...]
21188 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
21189 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21190
21191 // <foo> = [<bar> nextObject]
21192 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
21193 diagnostic = diag::warn_condition_is_idiomatic_assignment;
21194 }
21195
21196 Loc = Op->getOperatorLoc();
21197 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
21198 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
21199 return;
21200
21201 IsOrAssign = Op->getOperator() == OO_PipeEqual;
21202 Loc = Op->getOperatorLoc();
21203 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
21204 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
21205 else {
21206 // Not an assignment.
21207 return;
21208 }
21209
21210 Diag(Loc, diagnostic) << E->getSourceRange();
21211
21214 Diag(Loc, diag::note_condition_assign_silence)
21216 << FixItHint::CreateInsertion(Close, ")");
21217
21218 if (IsOrAssign)
21219 Diag(Loc, diag::note_condition_or_assign_to_comparison)
21220 << FixItHint::CreateReplacement(Loc, "!=");
21221 else
21222 Diag(Loc, diag::note_condition_assign_to_comparison)
21223 << FixItHint::CreateReplacement(Loc, "==");
21224}
21225
21227 // Don't warn if the parens came from a macro.
21228 SourceLocation parenLoc = ParenE->getBeginLoc();
21229 if (parenLoc.isInvalid() || parenLoc.isMacroID())
21230 return;
21231 // Don't warn for dependent expressions.
21232 if (ParenE->isTypeDependent())
21233 return;
21234
21235 Expr *E = ParenE->IgnoreParens();
21236 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
21237 return;
21238
21239 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
21240 if (opE->getOpcode() == BO_EQ &&
21241 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
21242 == Expr::MLV_Valid) {
21243 SourceLocation Loc = opE->getOperatorLoc();
21244
21245 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
21246 SourceRange ParenERange = ParenE->getSourceRange();
21247 Diag(Loc, diag::note_equality_comparison_silence)
21248 << FixItHint::CreateRemoval(ParenERange.getBegin())
21249 << FixItHint::CreateRemoval(ParenERange.getEnd());
21250 Diag(Loc, diag::note_equality_comparison_to_assign)
21251 << FixItHint::CreateReplacement(Loc, "=");
21252 }
21253}
21254
21256 bool IsConstexpr) {
21258 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
21260
21261 ExprResult result = CheckPlaceholderExpr(E);
21262 if (result.isInvalid()) return ExprError();
21263 E = result.get();
21264
21265 if (!E->isTypeDependent()) {
21266 if (E->getType() == Context.AMDGPUFeaturePredicateTy)
21268
21269 if (getLangOpts().CPlusPlus)
21270 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
21271
21273 if (ERes.isInvalid())
21274 return ExprError();
21275 E = ERes.get();
21276
21277 QualType T = E->getType();
21278 if (!T->isScalarType()) { // C99 6.8.4.1p1
21279 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
21280 << T << E->getSourceRange();
21281 return ExprError();
21282 }
21283 CheckBoolLikeConversion(E, Loc);
21284 }
21285
21286 return E;
21287}
21288
21290 Expr *SubExpr, ConditionKind CK,
21291 bool MissingOK) {
21292 // MissingOK indicates whether having no condition expression is valid
21293 // (for loop) or invalid (e.g. while loop).
21294 if (!SubExpr)
21295 return MissingOK ? ConditionResult() : ConditionError();
21296
21298 switch (CK) {
21300 Cond = CheckBooleanCondition(Loc, SubExpr);
21301 break;
21302
21304 // Note: this might produce a FullExpr
21305 Cond = CheckBooleanCondition(Loc, SubExpr, true);
21306 break;
21307
21309 Cond = CheckSwitchCondition(Loc, SubExpr);
21310 break;
21311 }
21312 if (Cond.isInvalid()) {
21313 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
21314 {SubExpr}, PreferredConditionType(CK));
21315 if (!Cond.get())
21316 return ConditionError();
21317 } else if (Cond.isUsable() && !isa<FullExpr>(Cond.get()))
21318 Cond = ActOnFinishFullExpr(Cond.get(), Loc, /*DiscardedValue*/ false);
21319
21320 if (!Cond.isUsable())
21321 return ConditionError();
21322
21323 return ConditionResult(*this, nullptr, Cond,
21325}
21326
21327namespace {
21328 /// A visitor for rebuilding a call to an __unknown_any expression
21329 /// to have an appropriate type.
21330 struct RebuildUnknownAnyFunction
21331 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
21332
21333 Sema &S;
21334
21335 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
21336
21337 ExprResult VisitStmt(Stmt *S) {
21338 llvm_unreachable("unexpected statement!");
21339 }
21340
21341 ExprResult VisitExpr(Expr *E) {
21342 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
21343 << E->getSourceRange();
21344 return ExprError();
21345 }
21346
21347 /// Rebuild an expression which simply semantically wraps another
21348 /// expression which it shares the type and value kind of.
21349 template <class T> ExprResult rebuildSugarExpr(T *E) {
21350 ExprResult SubResult = Visit(E->getSubExpr());
21351 if (SubResult.isInvalid()) return ExprError();
21352
21353 Expr *SubExpr = SubResult.get();
21354 E->setSubExpr(SubExpr);
21355 E->setType(SubExpr->getType());
21356 E->setValueKind(SubExpr->getValueKind());
21357 assert(E->getObjectKind() == OK_Ordinary);
21358 return E;
21359 }
21360
21361 ExprResult VisitParenExpr(ParenExpr *E) {
21362 return rebuildSugarExpr(E);
21363 }
21364
21365 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21366 return rebuildSugarExpr(E);
21367 }
21368
21369 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21370 ExprResult SubResult = Visit(E->getSubExpr());
21371 if (SubResult.isInvalid()) return ExprError();
21372
21373 Expr *SubExpr = SubResult.get();
21374 E->setSubExpr(SubExpr);
21375 E->setType(S.Context.getPointerType(SubExpr->getType()));
21376 assert(E->isPRValue());
21377 assert(E->getObjectKind() == OK_Ordinary);
21378 return E;
21379 }
21380
21381 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
21382 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
21383
21384 E->setType(VD->getType());
21385
21386 assert(E->isPRValue());
21387 if (S.getLangOpts().CPlusPlus &&
21388 !(isa<CXXMethodDecl>(VD) &&
21389 cast<CXXMethodDecl>(VD)->isInstance()))
21391
21392 return E;
21393 }
21394
21395 ExprResult VisitMemberExpr(MemberExpr *E) {
21396 return resolveDecl(E, E->getMemberDecl());
21397 }
21398
21399 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21400 return resolveDecl(E, E->getDecl());
21401 }
21402 };
21403}
21404
21405/// Given a function expression of unknown-any type, try to rebuild it
21406/// to have a function type.
21408 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
21409 if (Result.isInvalid()) return ExprError();
21410 return S.DefaultFunctionArrayConversion(Result.get());
21411}
21412
21413namespace {
21414 /// A visitor for rebuilding an expression of type __unknown_anytype
21415 /// into one which resolves the type directly on the referring
21416 /// expression. Strict preservation of the original source
21417 /// structure is not a goal.
21418 struct RebuildUnknownAnyExpr
21419 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
21420
21421 Sema &S;
21422
21423 /// The current destination type.
21424 QualType DestType;
21425
21426 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
21427 : S(S), DestType(CastType) {}
21428
21429 ExprResult VisitStmt(Stmt *S) {
21430 llvm_unreachable("unexpected statement!");
21431 }
21432
21433 ExprResult VisitExpr(Expr *E) {
21434 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21435 << E->getSourceRange();
21436 return ExprError();
21437 }
21438
21439 ExprResult VisitCallExpr(CallExpr *E);
21440 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
21441
21442 /// Rebuild an expression which simply semantically wraps another
21443 /// expression which it shares the type and value kind of.
21444 template <class T> ExprResult rebuildSugarExpr(T *E) {
21445 ExprResult SubResult = Visit(E->getSubExpr());
21446 if (SubResult.isInvalid()) return ExprError();
21447 Expr *SubExpr = SubResult.get();
21448 E->setSubExpr(SubExpr);
21449 E->setType(SubExpr->getType());
21450 E->setValueKind(SubExpr->getValueKind());
21451 assert(E->getObjectKind() == OK_Ordinary);
21452 return E;
21453 }
21454
21455 ExprResult VisitParenExpr(ParenExpr *E) {
21456 return rebuildSugarExpr(E);
21457 }
21458
21459 ExprResult VisitUnaryExtension(UnaryOperator *E) {
21460 return rebuildSugarExpr(E);
21461 }
21462
21463 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
21464 const PointerType *Ptr = DestType->getAs<PointerType>();
21465 if (!Ptr) {
21466 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
21467 << E->getSourceRange();
21468 return ExprError();
21469 }
21470
21471 if (isa<CallExpr>(E->getSubExpr())) {
21472 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
21473 << E->getSourceRange();
21474 return ExprError();
21475 }
21476
21477 assert(E->isPRValue());
21478 assert(E->getObjectKind() == OK_Ordinary);
21479 E->setType(DestType);
21480
21481 // Build the sub-expression as if it were an object of the pointee type.
21482 DestType = Ptr->getPointeeType();
21483 ExprResult SubResult = Visit(E->getSubExpr());
21484 if (SubResult.isInvalid()) return ExprError();
21485 E->setSubExpr(SubResult.get());
21486 return E;
21487 }
21488
21489 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
21490
21491 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
21492
21493 ExprResult VisitMemberExpr(MemberExpr *E) {
21494 return resolveDecl(E, E->getMemberDecl());
21495 }
21496
21497 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
21498 return resolveDecl(E, E->getDecl());
21499 }
21500 };
21501}
21502
21503/// Rebuilds a call expression which yielded __unknown_anytype.
21504ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
21505 Expr *CalleeExpr = E->getCallee();
21506
21507 enum FnKind {
21508 FK_MemberFunction,
21509 FK_FunctionPointer,
21510 FK_BlockPointer
21511 };
21512
21513 FnKind Kind;
21514 QualType CalleeType = CalleeExpr->getType();
21515 if (CalleeType == S.Context.BoundMemberTy) {
21517 Kind = FK_MemberFunction;
21518 CalleeType = Expr::findBoundMemberType(CalleeExpr);
21519 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
21520 CalleeType = Ptr->getPointeeType();
21521 Kind = FK_FunctionPointer;
21522 } else {
21523 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
21524 Kind = FK_BlockPointer;
21525 }
21526 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
21527
21528 // Verify that this is a legal result type of a function.
21529 if ((DestType->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
21530 DestType->isFunctionType()) {
21531 unsigned diagID = diag::err_func_returning_array_function;
21532 if (Kind == FK_BlockPointer)
21533 diagID = diag::err_block_returning_array_function;
21534
21535 S.Diag(E->getExprLoc(), diagID)
21536 << DestType->isFunctionType() << DestType;
21537 return ExprError();
21538 }
21539
21540 // Otherwise, go ahead and set DestType as the call's result.
21541 E->setType(DestType.getNonLValueExprType(S.Context));
21543 assert(E->getObjectKind() == OK_Ordinary);
21544
21545 // Rebuild the function type, replacing the result type with DestType.
21546 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
21547 if (Proto) {
21548 // __unknown_anytype(...) is a special case used by the debugger when
21549 // it has no idea what a function's signature is.
21550 //
21551 // We want to build this call essentially under the K&R
21552 // unprototyped rules, but making a FunctionNoProtoType in C++
21553 // would foul up all sorts of assumptions. However, we cannot
21554 // simply pass all arguments as variadic arguments, nor can we
21555 // portably just call the function under a non-variadic type; see
21556 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21557 // However, it turns out that in practice it is generally safe to
21558 // call a function declared as "A foo(B,C,D);" under the prototype
21559 // "A foo(B,C,D,...);". The only known exception is with the
21560 // Windows ABI, where any variadic function is implicitly cdecl
21561 // regardless of its normal CC. Therefore we change the parameter
21562 // types to match the types of the arguments.
21563 //
21564 // This is a hack, but it is far superior to moving the
21565 // corresponding target-specific code from IR-gen to Sema/AST.
21566
21567 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
21568 SmallVector<QualType, 8> ArgTypes;
21569 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
21570 ArgTypes.reserve(E->getNumArgs());
21571 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
21572 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
21573 }
21574 ParamTypes = ArgTypes;
21575 }
21576 DestType = S.Context.getFunctionType(DestType, ParamTypes,
21577 Proto->getExtProtoInfo());
21578 } else {
21579 DestType = S.Context.getFunctionNoProtoType(DestType,
21580 FnType->getExtInfo());
21581 }
21582
21583 // Rebuild the appropriate pointer-to-function type.
21584 switch (Kind) {
21585 case FK_MemberFunction:
21586 // Nothing to do.
21587 break;
21588
21589 case FK_FunctionPointer:
21590 DestType = S.Context.getPointerType(DestType);
21591 break;
21592
21593 case FK_BlockPointer:
21594 DestType = S.Context.getBlockPointerType(DestType);
21595 break;
21596 }
21597
21598 // Finally, we can recurse.
21599 ExprResult CalleeResult = Visit(CalleeExpr);
21600 if (!CalleeResult.isUsable()) return ExprError();
21601 E->setCallee(CalleeResult.get());
21602
21603 // Bind a temporary if necessary.
21604 return S.MaybeBindToTemporary(E);
21605}
21606
21607ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
21608 // Verify that this is a legal result type of a call.
21609 if (DestType->isArrayType() || DestType->isFunctionType()) {
21610 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
21611 << DestType->isFunctionType() << DestType;
21612 return ExprError();
21613 }
21614
21615 // Rewrite the method result type if available.
21616 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
21617 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
21618 Method->setReturnType(DestType);
21619 }
21620
21621 // Change the type of the message.
21622 E->setType(DestType.getNonReferenceType());
21624
21625 return S.MaybeBindToTemporary(E);
21626}
21627
21628ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21629 // The only case we should ever see here is a function-to-pointer decay.
21630 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21631 assert(E->isPRValue());
21632 assert(E->getObjectKind() == OK_Ordinary);
21633
21634 E->setType(DestType);
21635
21636 // Rebuild the sub-expression as the pointee (function) type.
21637 DestType = DestType->castAs<PointerType>()->getPointeeType();
21638
21639 ExprResult Result = Visit(E->getSubExpr());
21640 if (!Result.isUsable()) return ExprError();
21641
21642 E->setSubExpr(Result.get());
21643 return E;
21644 } else if (E->getCastKind() == CK_LValueToRValue) {
21645 assert(E->isPRValue());
21646 assert(E->getObjectKind() == OK_Ordinary);
21647
21648 assert(isa<BlockPointerType>(E->getType()));
21649
21650 E->setType(DestType);
21651
21652 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21653 DestType = S.Context.getLValueReferenceType(DestType);
21654
21655 ExprResult Result = Visit(E->getSubExpr());
21656 if (!Result.isUsable()) return ExprError();
21657
21658 E->setSubExpr(Result.get());
21659 return E;
21660 } else {
21661 llvm_unreachable("Unhandled cast type!");
21662 }
21663}
21664
21665ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21666 ExprValueKind ValueKind = VK_LValue;
21667 QualType Type = DestType;
21668
21669 // We know how to make this work for certain kinds of decls:
21670
21671 // - functions
21672 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21673 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21674 DestType = Ptr->getPointeeType();
21675 ExprResult Result = resolveDecl(E, VD);
21676 if (Result.isInvalid()) return ExprError();
21677 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21678 VK_PRValue);
21679 }
21680
21681 if (!Type->isFunctionType()) {
21682 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21683 << VD << E->getSourceRange();
21684 return ExprError();
21685 }
21686 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21687 // We must match the FunctionDecl's type to the hack introduced in
21688 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21689 // type. See the lengthy commentary in that routine.
21690 QualType FDT = FD->getType();
21691 const FunctionType *FnType = FDT->castAs<FunctionType>();
21692 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21693 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21694 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21695 SourceLocation Loc = FD->getLocation();
21696 FunctionDecl *NewFD = FunctionDecl::Create(
21697 S.Context, FD->getDeclContext(), Loc, Loc,
21698 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21700 false /*isInlineSpecified*/, FD->hasPrototype(),
21701 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21702
21703 if (FD->getQualifier())
21704 NewFD->setQualifierInfo(FD->getQualifierLoc());
21705
21706 SmallVector<ParmVarDecl*, 16> Params;
21707 for (const auto &AI : FT->param_types()) {
21708 ParmVarDecl *Param =
21709 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21710 Param->setScopeInfo(0, Params.size());
21711 Params.push_back(Param);
21712 }
21713 NewFD->setParams(Params);
21714 DRE->setDecl(NewFD);
21715 VD = DRE->getDecl();
21716 }
21717 }
21718
21719 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21720 if (MD->isInstance()) {
21721 ValueKind = VK_PRValue;
21723 }
21724
21725 // Function references aren't l-values in C.
21726 if (!S.getLangOpts().CPlusPlus)
21727 ValueKind = VK_PRValue;
21728
21729 // - variables
21730 } else if (isa<VarDecl>(VD)) {
21731 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21732 Type = RefTy->getPointeeType();
21733 } else if (Type->isFunctionType()) {
21734 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21735 << VD << E->getSourceRange();
21736 return ExprError();
21737 }
21738
21739 // - nothing else
21740 } else {
21741 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21742 << VD << E->getSourceRange();
21743 return ExprError();
21744 }
21745
21746 // Modifying the declaration like this is friendly to IR-gen but
21747 // also really dangerous.
21748 VD->setType(DestType);
21749 E->setType(Type);
21750 E->setValueKind(ValueKind);
21751 return E;
21752}
21753
21756 ExprValueKind &VK, CXXCastPath &Path) {
21757 // The type we're casting to must be either void or complete.
21758 if (!CastType->isVoidType() &&
21760 diag::err_typecheck_cast_to_incomplete))
21761 return ExprError();
21762
21763 // Rewrite the casted expression from scratch.
21764 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21765 if (!result.isUsable()) return ExprError();
21766
21767 CastExpr = result.get();
21769 CastKind = CK_NoOp;
21770
21771 return CastExpr;
21772}
21773
21775 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21776}
21777
21779 Expr *arg, QualType &paramType) {
21780 // If the syntactic form of the argument is not an explicit cast of
21781 // any sort, just do default argument promotion.
21782 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21783 if (!castArg) {
21785 if (result.isInvalid()) return ExprError();
21786 paramType = result.get()->getType();
21787 return result;
21788 }
21789
21790 // Otherwise, use the type that was written in the explicit cast.
21791 assert(!arg->hasPlaceholderType());
21792 paramType = castArg->getTypeAsWritten();
21793
21794 // Copy-initialize a parameter of that type.
21795 InitializedEntity entity =
21797 /*consumed*/ false);
21798 return PerformCopyInitialization(entity, callLoc, arg);
21799}
21800
21802 Expr *orig = E;
21803 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21804 while (true) {
21805 E = E->IgnoreParenImpCasts();
21806 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21807 E = call->getCallee();
21808 diagID = diag::err_uncasted_call_of_unknown_any;
21809 } else {
21810 break;
21811 }
21812 }
21813
21814 SourceLocation loc;
21815 NamedDecl *d;
21816 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21817 loc = ref->getLocation();
21818 d = ref->getDecl();
21819 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21820 loc = mem->getMemberLoc();
21821 d = mem->getMemberDecl();
21822 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21823 diagID = diag::err_uncasted_call_of_unknown_any;
21824 loc = msg->getSelectorStartLoc();
21825 d = msg->getMethodDecl();
21826 if (!d) {
21827 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21828 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21829 << orig->getSourceRange();
21830 return ExprError();
21831 }
21832 } else {
21833 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21834 << E->getSourceRange();
21835 return ExprError();
21836 }
21837
21838 S.Diag(loc, diagID) << d << orig->getSourceRange();
21839
21840 // Never recoverable.
21841 return ExprError();
21842}
21843
21845 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21846 if (!placeholderType) return E;
21847
21848 switch (placeholderType->getKind()) {
21849 case BuiltinType::UnresolvedTemplate: {
21850 auto *ULE = cast<UnresolvedLookupExpr>(E->IgnoreParens());
21851 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21852 // There's only one FoundDecl for UnresolvedTemplate type. See
21853 // BuildTemplateIdExpr.
21854 NamedDecl *Temp = *ULE->decls_begin();
21855 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
21856
21857 NestedNameSpecifier NNS = ULE->getQualifierLoc().getNestedNameSpecifier();
21858 // FIXME: AssumedTemplate is not very appropriate for error recovery here,
21859 // as it models only the unqualified-id case, where this case can clearly be
21860 // qualified. Thus we can't just qualify an assumed template.
21861 TemplateName TN;
21862 if (auto *TD = dyn_cast<TemplateDecl>(Temp))
21863 TN = Context.getQualifiedTemplateName(NNS, ULE->hasTemplateKeyword(),
21864 TemplateName(TD));
21865 else
21866 TN = Context.getAssumedTemplateName(NameInfo.getName());
21867
21868 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21869 << TN << ULE->getSourceRange() << IsTypeAliasTemplateDecl;
21870 Diag(Temp->getLocation(), diag::note_referenced_type_template)
21871 << IsTypeAliasTemplateDecl;
21872
21873 TemplateArgumentListInfo TAL(ULE->getLAngleLoc(), ULE->getRAngleLoc());
21874 bool HasAnyDependentTA = false;
21875 for (const TemplateArgumentLoc &Arg : ULE->template_arguments()) {
21876 HasAnyDependentTA |= Arg.getArgument().isDependent();
21877 TAL.addArgument(Arg);
21878 }
21879
21880 QualType TST;
21881 {
21882 SFINAETrap Trap(*this);
21883 TST = CheckTemplateIdType(
21884 ElaboratedTypeKeyword::None, TN, NameInfo.getBeginLoc(), TAL,
21885 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
21886 }
21887 if (TST.isNull())
21888 TST = Context.getTemplateSpecializationType(
21889 ElaboratedTypeKeyword::None, TN, ULE->template_arguments(),
21890 /*CanonicalArgs=*/{},
21891 HasAnyDependentTA ? Context.DependentTy : Context.IntTy);
21892 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {},
21893 TST);
21894 }
21895
21896 // Overloaded expressions.
21897 case BuiltinType::Overload: {
21898 // Try to resolve a single function template specialization.
21899 // This is obligatory.
21900 ExprResult Result = E;
21902 return Result;
21903
21904 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21905 // leaves Result unchanged on failure.
21906 Result = E;
21908 return Result;
21909
21910 // If that failed, try to recover with a call.
21911 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21912 /*complain*/ true);
21913 return Result;
21914 }
21915
21916 // Bound member functions.
21917 case BuiltinType::BoundMember: {
21918 ExprResult result = E;
21919 const Expr *BME = E->IgnoreParens();
21920 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21921 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21923 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21924 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21925 if (ME->getMemberNameInfo().getName().getNameKind() ==
21927 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21928 }
21929 tryToRecoverWithCall(result, PD,
21930 /*complain*/ true);
21931 return result;
21932 }
21933
21934 // ARC unbridged casts.
21935 case BuiltinType::ARCUnbridgedCast: {
21936 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
21937 ObjC().diagnoseARCUnbridgedCast(realCast);
21938 return realCast;
21939 }
21940
21941 // Expressions of unknown type.
21942 case BuiltinType::UnknownAny:
21943 return diagnoseUnknownAnyExpr(*this, E);
21944
21945 // Pseudo-objects.
21946 case BuiltinType::PseudoObject:
21947 return PseudoObject().checkRValue(E);
21948
21949 case BuiltinType::BuiltinFn: {
21950 // Accept __noop without parens by implicitly converting it to a call expr.
21951 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21952 if (DRE) {
21953 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21954 unsigned BuiltinID = FD->getBuiltinID();
21955 if (BuiltinID == Builtin::BI__noop) {
21956 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21957 CK_BuiltinFnToFnPtr)
21958 .get();
21959 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21962 }
21963
21964 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21965 // Any use of these other than a direct call is ill-formed as of C++20,
21966 // because they are not addressable functions. In earlier language
21967 // modes, warn and force an instantiation of the real body.
21968 Diag(E->getBeginLoc(),
21970 ? diag::err_use_of_unaddressable_function
21971 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21972 if (FD->isImplicitlyInstantiable()) {
21973 // Require a definition here because a normal attempt at
21974 // instantiation for a builtin will be ignored, and we won't try
21975 // again later. We assume that the definition of the template
21976 // precedes this use.
21978 /*Recursive=*/false,
21979 /*DefinitionRequired=*/true,
21980 /*AtEndOfTU=*/false);
21981 }
21982 // Produce a properly-typed reference to the function.
21983 CXXScopeSpec SS;
21984 SS.Adopt(DRE->getQualifierLoc());
21985 TemplateArgumentListInfo TemplateArgs;
21986 DRE->copyTemplateArgumentsInto(TemplateArgs);
21987 return BuildDeclRefExpr(
21988 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21989 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21990 DRE->getTemplateKeywordLoc(),
21991 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21992 }
21993 }
21994
21995 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21996 return ExprError();
21997 }
21998
21999 case BuiltinType::IncompleteMatrixIdx: {
22000 auto *MS = cast<MatrixSubscriptExpr>(E->IgnoreParens());
22001 // At this point, we know there was no second [] to complete the operator.
22002 // In HLSL, treat "m[row]" as selecting a row lane of column sized vector.
22003 if (getLangOpts().HLSL) {
22005 MS->getBase(), MS->getRowIdx(), E->getExprLoc());
22006 }
22007 Diag(MS->getRowIdx()->getBeginLoc(), diag::err_matrix_incomplete_index);
22008 return ExprError();
22009 }
22010
22011 // Expressions of unknown type.
22012 case BuiltinType::ArraySection:
22013 // If we've already diagnosed something on the array section type, we
22014 // shouldn't need to do any further diagnostic here.
22015 if (!E->containsErrors())
22016 Diag(E->getBeginLoc(), diag::err_array_section_use)
22017 << cast<ArraySectionExpr>(E->IgnoreParens())->isOMPArraySection();
22018 return ExprError();
22019
22020 // Expressions of unknown type.
22021 case BuiltinType::OMPArrayShaping:
22022 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
22023
22024 case BuiltinType::OMPIterator:
22025 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
22026
22027 // Everything else should be impossible.
22028#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
22029 case BuiltinType::Id:
22030#include "clang/Basic/OpenCLImageTypes.def"
22031#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
22032 case BuiltinType::Id:
22033#include "clang/Basic/OpenCLExtensionTypes.def"
22034#define SVE_TYPE(Name, Id, SingletonId) \
22035 case BuiltinType::Id:
22036#include "clang/Basic/AArch64ACLETypes.def"
22037#define PPC_VECTOR_TYPE(Name, Id, Size) \
22038 case BuiltinType::Id:
22039#include "clang/Basic/PPCTypes.def"
22040#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22041#include "clang/Basic/RISCVVTypes.def"
22042#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22043#include "clang/Basic/WebAssemblyReferenceTypes.def"
22044#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
22045#include "clang/Basic/AMDGPUTypes.def"
22046#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
22047#include "clang/Basic/HLSLIntangibleTypes.def"
22048#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
22049#define PLACEHOLDER_TYPE(Id, SingletonId)
22050#include "clang/AST/BuiltinTypes.def"
22051 break;
22052 }
22053
22054 llvm_unreachable("invalid placeholder type!");
22055}
22056
22058 if (E->isTypeDependent())
22059 return true;
22061 return E->getType()->isIntegralOrEnumerationType();
22062 return false;
22063}
22064
22066 ArrayRef<Expr *> SubExprs, QualType T) {
22067 if (!Context.getLangOpts().RecoveryAST)
22068 return ExprError();
22069
22070 if (isSFINAEContext())
22071 return ExprError();
22072
22073 if (T.isNull() || T->isUndeducedType() ||
22074 !Context.getLangOpts().RecoveryASTType)
22075 // We don't know the concrete type, fallback to dependent type.
22076 T = Context.DependentTy;
22077
22078 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
22079}
Defines the clang::ASTContext interface.
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
static bool isObjCPointer(const MemRegion *R)
Defines enum values for all the target-independent builtin functions.
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::Expr interface and subclasses for C++ expressions.
Token Tok
The Token.
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition MachO.h:51
llvm::MachO::Record Record
Definition MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
static QualType getUnderlyingType(const SubRegion *R)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis for CUDA constructs.
CastType
Definition SemaCast.cpp:50
static void DetectPrecisionLossInComplexDivision(Sema &S, QualType DivisorTy, SourceLocation OpLoc)
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, IdentifierInfo *UDSuffix, SourceLocation UDSuffixLoc, ArrayRef< Expr * > Args, SourceLocation LitEndLoc)
BuildCookedLiteralOperatorCall - A user-defined literal was found.
static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHS, Expr *RHS)
Build an overloaded binary operator expression in the given scope.
static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int, QualType FloatTy)
Test if a (constant) integer Int can be casted to floating point type FloatTy without losing precisio...
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison operators are mixed in a way t...
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc, Expr *Condition, const Expr *LHSExpr, const Expr *RHSExpr)
DiagnoseConditionalPrecedence - Emit a warning when a conditional operator and binary operator are mi...
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, bool AcceptInvalid)
Diagnoses obvious problems with the use of the given declaration as an expression.
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
static QualType OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Return the resulting type for the conditional operator in OpenCL (aka "ternary selection operator",...
static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
static AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn)
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
@ NCCK_Block
@ NCCK_None
@ NCCK_Lambda
static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar, QualType scalarTy, QualType vectorEltTy, QualType vectorTy, unsigned &DiagID)
Try to convert a value of non-vector type to a vector type by converting the type to the element type...
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
static Expr * recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, DeclarationNameInfo &NameInfo, SourceLocation TemplateKWLoc, const TemplateArgumentListInfo *TemplateArgs)
In Microsoft mode, if we are inside a template class whose parent class has dependent base classes,...
static AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(Sema &SemaRef, ValueDecl *D, Expr *E)
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
static void SuggestParentheses(Sema &Self, SourceLocation Loc, const PartialDiagnostic &Note, SourceRange ParenRange)
SuggestParentheses - Emit a note with a fixit hint that wraps ParenRange in parentheses.
static Decl * getPredefinedExprDecl(DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
static bool ExprLooksBoolean(const Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, SourceLocation OpLoc, bool IsBuiltin)
DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
diagnoseStringPlusInt - Emit a warning when adding an integer to a string literal.
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
static bool checkCondition(Sema &S, const Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
static bool checkForArray(const Expr *E)
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
static bool areTypesCompatibleForGeneric(ASTContext &Ctx, QualType T, QualType U)
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
static bool MayBeFunctionType(const ASTContext &Context, const Expr *E)
static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S)
Convert vector E to a vector with the same number of elements but different element type.
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode, const Expr **RHSExprs)
IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary expression, either using a built-i...
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, BinaryOperatorKind Opc, QualType ResultTy, ExprValueKind VK, ExprObjectKind OK, bool IsCompAssign, SourceLocation OpLoc, FPOptionsOverride FPFeatures)
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
@ ConstUnknown
@ ConstVariable
@ NestedConstMember
@ ConstMember
@ ConstFunction
static void ConstructTransparentUnion(Sema &S, ASTContext &C, ExprResult &EResult, QualType UnionType, FieldDecl *Field)
Constructs a transparent union from an expression that is used to initialize the transparent union.
static QualType OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType CondTy, SourceLocation QuestionLoc)
Convert scalar operands to a vector that matches the condition in length.
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
static void CheckUnicodeArithmeticConversions(Sema &SemaRef, Expr *LHS, Expr *RHS, SourceLocation Loc, ArithConvKind ACK)
static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *SubExpr)
Look for bitwise op in the left or right hand of a bitwise op with lower precedence and emit a diagno...
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation OpLoc, bool IsInc, bool IsPrefix)
CheckIncrementDecrementOperand - unlike most "Check" methods, this routine doesn't need to call Usual...
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy, SourceLocation QuestionLoc)
Return false if the vector condition type and the vector result type are compatible.
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, const Expr *E)
Check whether E is a pointer from a decayed array type (the decayed pointer type is equal to T) and e...
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition SemaExpr.cpp:149
static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType)
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, const TryCaptureKind Kind, SourceLocation EllipsisLoc, const bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the lambda.
static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, QualType RHSType)
Diagnose attempts to convert between __float128, __ibm128 and long double if there is no support for ...
static void MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Emit a warning when adding a char literal to a string.
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S, const NamedDecl *D, SourceLocation Loc)
Check whether we're in an extern inline function and referring to a variable or function with interna...
Definition SemaExpr.cpp:165
static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD)
Return true if this function has a calling convention that requires mangling in the size of the param...
static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Returns false if the pointers are converted to a composite type, true otherwise.
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle conversions with GCC complex int extension.
static AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, SourceLocation Loc)
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar, ExprResult *Vector)
Attempt to convert and splat Scalar into a vector whose types matches Vector following GCC conversion...
static void diagnoseScopedEnums(Sema &S, const SourceLocation Loc, const ExprResult &LHS, const ExprResult &RHS, BinaryOperatorKind Opc)
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the left hand of a '||' expr.
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition SemaExpr.cpp:562
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
static OdrUseContext isOdrUseContext(Sema &SemaRef)
Are we within a context in which references to resolved functions or to variables result in odr-use?
static void DiagnoseConstAssignment(Sema &S, const Expr *E, SourceLocation Loc)
Emit the "read-only variable not assignable" error and print notes to give more information about why...
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
static void CheckSufficientAllocSize(Sema &S, QualType DestType, const Expr *E)
Check that a call to alloc_size function specifies sufficient space for the destination type.
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
static QualType handleOverflowBehaviorTypeConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, unsigned Offset)
getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the location of the token and the off...
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
OriginalExprKind
@ OEK_Variable
@ OEK_LValue
@ OEK_Member
static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S, bool Invalid)
static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmethic conversion with floating point types.
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Return the resulting type when a vector is shifted by a scalar or vector shift amount.
static FieldDecl * FindFieldDeclInstantiationPattern(const ASTContext &Ctx, FieldDecl *Field)
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
static bool IsReadonlyMessage(Expr *E, Sema &S)
static std::optional< bool > isTautologicalBoundsCheck(Sema &S, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opc)
Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a pointer and size is an unsigne...
static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI, ValueDecl *Var)
Create up to 4 fix-its for explicit reference and value capture of Var or default capture.
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, TryCaptureKind Kind, bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the captured region.
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int, Expr *PointerExpr, SourceLocation Loc, bool IsIntFirstExpr)
Return false if the first expression is not an integer and the second expression is not a pointer,...
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
static bool IsArithmeticOp(BinaryOperatorKind Opc)
static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr, ExprResult &ComplexExpr, QualType IntTy, QualType ComplexTy, bool SkipCast)
Convert complex integers to complex floats and real integers to real floats as required for complex a...
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, SourceLocation OpLoc)
Check if a bitwise-& is performed on an Objective-C pointer.
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition SemaExpr.cpp:587
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn)
Given a function expression of unknown-any type, try to rebuild it to have a function type.
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, ExprResult &IntExpr, QualType FloatTy, QualType IntTy, bool ConvertFloat, bool ConvertInt)
Handle arithmetic conversion from integer to float.
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, QualType ShorterType, QualType LongerType, bool PromotePrecision)
static FunctionDecl * rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, FunctionDecl *FDecl, MultiExprArg ArgExprs)
If a builtin function has a pointer argument with no explicit address space, then it should be able t...
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind)
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition SemaExpr.cpp:111
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, QualType RHSTy)
handleFixedPointConversion - Fixed point operations between fixed point types and integers or other f...
static QualType handleComplexConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx, Expr *E0, Expr *E1=nullptr)
Returns true if conversion between vectors of halfs and vectors of floats is needed.
static bool isObjCObjectLiteral(ExprResult &E)
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
static QualType checkConditionalBlockPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both block pointers.
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, QualType OtherIntTy)
Test if a (constant) integer Int can be casted to another integer type IntTy without losing precision...
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E, NonOdrUseReason NOUR)
Walk the set of potential results of an expression and mark them all as non-odr-uses if they satisfy ...
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
static bool isScopedEnumerationType(QualType T)
static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Check the validity of a binary arithmetic operation w.r.t.
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis for expressions involving.
static bool isInvalid(LocType Loc, bool *Invalid)
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
Defines enumerations for the type traits support.
C Language Family Type Representation.
@ Open
The standard open() call: int open(const char *path, int oflag, ...);.
a trap message and trap category.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
APSInt & getInt()
Definition APValue.h:508
bool hasValue() const
Definition APValue.h:483
bool isInt() const
Definition APValue.h:485
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:974
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
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:806
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:802
const LangOptions & getLangOpts() const
Definition ASTContext.h:959
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
const QualType GetHigherPrecisionFPType(QualType ElementType) const
Definition ASTContext.h:924
bool typesAreBlockPointerCompatible(QualType, QualType)
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
llvm::SetVector< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
llvm::SetVector< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
QualType getCorrespondingSaturatedType(QualType Ty) const
CanQualType BoundMemberTy
CanQualType CharTy
CanQualType IntTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnknownAnyTy
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:921
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:4556
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2727
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:2782
Wrapper for source info for arrays.
Definition TypeLoc.h:1777
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
ArraySizeModifier getSizeModifier() const
Definition TypeBase.h:3800
QualType getElementType() const
Definition TypeBase.h:3798
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition Expr.h:6736
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:4459
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
Expr * getLHS() const
Definition Expr.h:4094
static bool isRelationalOp(Opcode Opc)
Definition Expr.h:4138
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2187
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4144
StringRef getOpcodeStr() const
Definition Expr.h:4110
bool isRelationalOp() const
Definition Expr.h:4139
SourceLocation getOperatorLoc() const
Definition Expr.h:4086
bool isMultiplicativeOp() const
Definition Expr.h:4129
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2140
bool isShiftOp() const
Definition Expr.h:4133
Expr * getRHS() const
Definition Expr.h:4096
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:5104
bool isBitwiseOp() const
Definition Expr.h:4136
bool isAdditiveOp() const
Definition Expr.h:4131
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4180
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4185
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:2212
Opcode getOpcode() const
Definition Expr.h:4089
bool isAssignmentOp() const
Definition Expr.h:4183
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition Expr.cpp:2149
static bool isEqualityOp(Opcode Opc)
Definition Expr.h:4141
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4135
BinaryOperatorKind Opcode
Definition Expr.h:4049
A binding in a decomposition declaration.
Definition DeclCXX.h:4203
A class which contains all the information about a particular captured value.
Definition Decl.h:4700
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4694
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.cpp:5442
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition Decl.h:4776
void setBlockMissingReturnType(bool val=true)
Definition Decl.h:4833
void setIsVariadic(bool value)
Definition Decl.h:4770
SourceLocation getCaretLocation() const
Definition Decl.h:4767
void setBody(CompoundStmt *B)
Definition Decl.h:4774
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:4780
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition Decl.cpp:5453
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5646
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6675
Pointer to a block type.
Definition TypeBase.h:3606
This class is used for builtin types like 'int'.
Definition TypeBase.h:3228
bool isSVEBool() const
Definition TypeBase.h:3305
Kind getKind() const
Definition TypeBase.h:3276
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:1967
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:2633
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2965
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition DeclCXX.cpp:3285
Represents a C++ base or member initializer.
Definition DeclCXX.h:2398
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1274
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition ExprCXX.cpp:1046
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1381
static CXXDefaultInitExpr * Create(const ASTContext &Ctx, SourceLocation Loc, FieldDecl *Field, DeclContext *UsedContext, Expr *RewrittenInitExpr)
Field is the non-static data member whose default initializer is used by this expression.
Definition ExprCXX.cpp:1100
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1112
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition ExprCXX.cpp:1557
Represents a C++ destructor within a class.
Definition DeclCXX.h:2895
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
bool isVirtual() const
Definition DeclCXX.h:2200
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2284
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:2522
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:1998
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:1230
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition DeclCXX.cpp:604
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1023
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition DeclCXX.cpp:2085
bool hasDefinition() const
Definition DeclCXX.h:561
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition DeclCXX.h:623
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
static CXXReflectExpr * Create(ASTContext &C, SourceLocation OperatorLoc, TypeSourceInfo *TL)
Definition ExprCXX.cpp:1943
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:2949
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition Expr.h:3166
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:1523
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3132
Expr * getCallee()
Definition Expr.h:3096
void computeDependence()
Compute and set dependence bits.
Definition Expr.h:3172
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3140
void setCallee(Expr *F)
Definition Expr.h:3098
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:3682
CastKind getCastKind() const
Definition Expr.h:3726
const char * getCastKindName() const
Definition Expr.h:3730
void setSubExpr(Expr *E)
Definition Expr.h:3734
Expr * getSubExpr()
Definition Expr.h:3732
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Represents a byte-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition CharUnits.h:122
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:63
unsigned getValue() const
Definition Expr.h:1635
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4854
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3339
QualType getElementType() const
Definition TypeBase.h:3349
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:5126
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3611
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1750
bool body_empty() const
Definition Stmt.h:1794
Stmt * body_back()
Definition Stmt.h:1818
ConditionalOperator - The ?
Definition Expr.h:4397
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3824
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition TypeBase.h:3880
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3900
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1088
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:1138
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
bool isImmediateInvocation() const
Definition Expr.h:1160
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4451
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4470
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4467
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
void setTypoName(const IdentifierInfo *II)
void setTypoNNS(NestedNameSpecifier NNS)
Wrapper for source info for pointers decayed from arrays and functions.
Definition TypeLoc.h:1474
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1462
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2122
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2251
bool isRequiresExprBody() const
Definition DeclBase.h:2207
DeclContextLookupResult lookup_result
Definition DeclBase.h:2590
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isRecord() const
Definition DeclBase.h:2202
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
bool isFunctionOrMethod() const
Definition DeclBase.h:2174
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition Expr.h:1387
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition Expr.h:1431
NestedNameSpecifier getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition Expr.h:1377
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1480
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:1435
DeclarationNameInfo getNameInfo() const
Definition Expr.h:1348
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition Expr.h:1403
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:1365
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition Expr.h:1369
ValueDecl * getDecl()
Definition Expr.h:1344
SourceLocation getBeginLoc() const
Definition Expr.h:1355
SourceLocation getLocation() const
Definition Expr.h:1352
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
T * getAttr() const
Definition DeclBase.h:581
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition DeclBase.cpp:776
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:591
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition DeclBase.h:1083
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
void setReferenced(bool R=true)
Definition DeclBase.h:631
DeclContext * getDeclContext()
Definition DeclBase.h:456
bool hasAttr() const
Definition DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition DeclBase.h:991
Kind getKind() const
Definition DeclBase.h:450
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition Decl.cpp:2015
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h: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:549
A little helper class used to produce diagnostics.
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:960
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:729
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
virtual bool TraverseTemplateArgument(const TemplateArgument &Arg)
Represents a reference to emded data.
Definition Expr.h:5132
RAII object that enters a new expression evaluation context.
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4206
ExplicitCastExpr - An explicit cast written in the source code.
Definition Expr.h:3934
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition Expr.h:3961
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1471
This represents one expression.
Definition Expr.h:112
LValueClassification
Definition Expr.h:289
@ LV_ArrayTemporary
Definition Expr.h:300
@ LV_ClassTemporary
Definition Expr.h:299
@ LV_MemberFunction
Definition Expr.h:297
@ LV_IncompleteVoidType
Definition Expr.h:292
@ LV_Valid
Definition Expr.h:290
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
Definition Expr.cpp:3126
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:681
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition Expr.cpp:3055
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:3104
void setType(QualType t)
Definition Expr.h:145
LValueClassification ClassifyLValue(ASTContext &Ctx) const
Reasons why an expression might not be an l-value.
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition Expr.h:241
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3099
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3087
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition Expr.cpp:3108
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3095
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3348
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:837
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition Expr.h:833
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:841
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3697
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3079
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition Expr.h:808
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:817
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition Expr.h:820
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition Expr.h:823
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition Expr.h:810
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:4077
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:464
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp: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:4329
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition Expr.h:467
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
isModifiableLvalueResult
Definition Expr.h:305
@ MLV_DuplicateVectorComponents
Definition Expr.h:309
@ MLV_LValueCast
Definition Expr.h:312
@ MLV_InvalidMessageExpression
Definition Expr.h:321
@ MLV_DuplicateMatrixComponents
Definition Expr.h:310
@ MLV_ConstQualifiedField
Definition Expr.h:315
@ MLV_InvalidExpression
Definition Expr.h:311
@ MLV_IncompleteType
Definition Expr.h:313
@ MLV_Valid
Definition Expr.h:306
@ MLV_ConstQualified
Definition Expr.h:314
@ MLV_NoSetterProperty
Definition Expr.h:318
@ MLV_ArrayTemporary
Definition Expr.h:323
@ MLV_SubObjCPropertySetting
Definition Expr.h:320
@ MLV_ConstAddrSpace
Definition Expr.h:316
@ MLV_MemberFunction
Definition Expr.h:319
@ MLV_NotObjectType
Definition Expr.h:307
@ MLV_ArrayType
Definition Expr.h:317
@ MLV_ClassTemporary
Definition Expr.h:322
@ MLV_IncompleteVoidType
Definition Expr.h:308
QualType getType() const
Definition Expr.h:144
bool isOrdinaryOrBitFieldObject() const
Definition Expr.h:458
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:437
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
Definition Expr.cpp:138
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6613
ExtVectorType - Extended vector type.
Definition TypeBase.h:4331
Represents difference between two FPOptions values.
bool isFPConstrained() const
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3182
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3285
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3362
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3418
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:80
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:141
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:130
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:104
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition Expr.cpp: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:1068
bool ValidateCandidate(const TypoCorrection &candidate) override
Simple predicate used by the default RankCandidate to determine whether to return an edit distance of...
Represents a function declaration or definition.
Definition Decl.h:2018
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, const AssociatedConstraint &TrailingRequiresClause={})
Definition Decl.h:2207
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2815
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition Decl.cpp:3823
bool isImmediateFunction() const
Definition Decl.cpp:3316
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition Decl.cpp:4000
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3738
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3841
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition Decl.h:2939
QualType getReturnType() const
Definition Decl.h:2863
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2792
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition Decl.h:2461
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition Decl.cpp:3594
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
bool isImmediateEscalating() const
Definition Decl.cpp:3287
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition Decl.h:2951
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4106
bool isConsteval() const
Definition Decl.h:2500
size_t param_size() const
Definition Decl.h:2808
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3175
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition Decl.cpp:4016
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition Decl.h:2899
Represents a reference to a function parameter pack, init-capture pack, or binding pack that has been...
Definition ExprCXX.h:4841
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition ExprCXX.h:4870
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5875
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition TypeBase.h:5678
bool isParamConsumed(unsigned I) const
Definition TypeBase.h:5889
unsigned getNumParams() const
Definition TypeBase.h:5649
QualType getParamType(unsigned i) const
Definition TypeBase.h:5651
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5775
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5660
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5656
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5811
Declaration of a template function.
unsigned getNumParams() const
Definition TypeLoc.h:1716
ParmVarDecl * getParam(unsigned i) const
Definition TypeLoc.h:1722
SourceLocation getLocalRangeEnd() const
Definition TypeLoc.h:1668
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1725
SourceLocation getLocalRangeBegin() const
Definition TypeLoc.h:1660
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4678
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4749
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4606
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
ExtInfo getExtInfo() const
Definition TypeBase.h:4923
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition TypeBase.h:4915
bool getCFIUncheckedCalleeAttr() const
Determine whether this is a function prototype that includes the cfi_unchecked_callee attribute.
Definition Type.cpp:3698
QualType getReturnType() const
Definition TypeBase.h:4907
bool getCmseNSCallAttr() const
Definition TypeBase.h:4921
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4935
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition Expr.h:4929
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:4725
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:1737
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3859
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2079
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:622
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3489
Describes an C or C++ initializer list.
Definition Expr.h:5305
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
static InitializationKind CreateCStyleCast(SourceLocation StartLoc, SourceRange TypeRange, bool InitList)
Create a direct initialization for a C-style cast.
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeStmtExprResult(SourceLocation ReturnLoc, QualType Type)
static InitializedEntity InitializeTemporary(QualType Type)
Create the initialization entity for a temporary.
static InitializedEntity InitializeBlock(SourceLocation BlockVarLoc, QualType Type)
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeCompoundLiteralInit(TypeSourceInfo *TSI)
Create the entity for a compound literal initializer.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:981
Represents the declaration of a label.
Definition Decl.h:524
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1972
CXXMethodDecl * getCallOperator() const
Retrieve the function call operator associated with this lambda expression.
Definition ExprCXX.cpp:1411
FPEvalMethodKind
Possible float expression evaluation method choices.
@ FEM_Extended
Use extended type for fp arithmetic.
@ FEM_Double
Use the type double for fp arithmetic.
@ FEM_UnsetOnCommandLine
Used only for FE option processing; this is only used to indicate that the user did not specify an ex...
@ FEM_Source
Use the declared type for fp arithmetic.
@ CX_Promoted
Implementation of complex division using algebraic formulas at higher precision.
@ None
Permit no implicit vector bitcasts.
@ Integer
Permit vector bitcasts between integer vectors with different numbers of elements but the same total ...
@ All
Permit vector bitcasts between all vectors with the same total bit-width.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
clang::ObjCRuntime ObjCRuntime
bool isSignedOverflowDefined() const
bool allowArrayReturnTypes() const
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1074
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token,...
Definition Lexer.h:407
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping '\' and " characters and ii) ...
Definition Lexer.cpp:319
Represents the results of name lookup.
Definition Lookup.h:147
DeclClass * getAsSingle() const
Definition Lookup.h:558
A global _GUID constant.
Definition DeclCXX.h:4416
MS property subscript expression.
Definition ExprCXX.h:1010
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
MatrixSingleSubscriptExpr - Matrix single subscript expression for the MatrixType extension when you ...
Definition Expr.h:2801
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition Expr.h:2871
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition TypeBase.h:4401
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4415
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3559
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
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:1756
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3588
Expr * getBase() const
Definition Expr.h:3447
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1800
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1681
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1207
bool isExternallyVisible() const
Definition Decl.h:433
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition Decl.h:397
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
CXXRecordDecl * getAsRecordDecl() const
Retrieve the record declaration stored in this nested name specifier, or null.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
NumericLiteralParser - This performs strict semantic analysis of the content of a ppnumber,...
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
bool hasDefinition() const
Determine whether this class has been defined.
Definition DeclObjC.h:1528
ivar_iterator ivar_begin() const
Definition DeclObjC.h:1453
ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.cpp:349
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8009
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition ExprObjC.h:1529
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1952
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition ExprObjC.h:580
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprObjC.h:626
SourceLocation getLocation() const
Definition ExprObjC.h:623
SourceLocation getOpLoc() const
Definition ExprObjC.h:631
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:610
bool isArrow() const
Definition ExprObjC.h:618
SourceLocation getEndLoc() const LLVM_READONLY
Definition ExprObjC.h:629
const Expr * getBase() const
Definition ExprObjC.h:614
An expression that sends a message to the given Objective-C object or class.
Definition ExprObjC.h:971
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1395
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
ImplicitParamDecl * getSelfDecl() const
Definition DeclObjC.h:418
bool isClassMethod() const
Definition DeclObjC.h:434
Represents a pointer to an Objective C object.
Definition TypeBase.h:8065
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1889
qual_range quals() const
Definition TypeBase.h:8184
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:731
Represents an Objective-C protocol declaration.
Definition DeclObjC.h:2084
bool allowsSizeofAlignof() const
Does this runtime allow sizeof or alignof on object types?
bool allowsPointerArithmetic() const
Does this runtime allow pointer arithmetic on objects?
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr * > exprs, SourceLocation RParenLoc)
Definition Expr.cpp:1659
Helper class for OffsetOfExpr.
Definition Expr.h:2427
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:1184
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition ExprCXX.h:3132
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3193
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2188
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2209
const Expr * getSubExpr() const
Definition Expr.h:2205
bool isProducedByFoldExpansion() const
Definition Expr.h:2230
Expr * getExpr(unsigned Init)
Definition Expr.h:6115
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition Expr.cpp:4976
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition Expr.h:6113
SourceLocation getLParenLoc() const
Definition Expr.h:6132
SourceLocation getRParenLoc() const
Definition Expr.h:6133
Represents a parameter to a function.
Definition Decl.h:1808
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1841
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2933
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
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
bool isMacroDefined(StringRef Id)
IdentifierTable & getIdentifierTable()
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6807
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8536
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:3682
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition Type.cpp:3023
bool isAddressSpaceOverlapping(QualType T, const ASTContext &Ctx) const
Returns true if address space qualifiers overlap with T address space qualifiers.
Definition TypeBase.h:1431
QualType withConst() const
Definition TypeBase.h:1174
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1171
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8573
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:8487
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:2800
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1453
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8632
QualType getCanonicalType() const
Definition TypeBase.h:8499
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition Type.cpp:3042
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1194
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C.
Definition TypeBase.h:8639
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8520
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1719
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1560
bool isCanonical() const
Definition TypeBase.h:8504
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition TypeBase.h:1324
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1347
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition Type.cpp:2788
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition TypeBase.h:8612
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8479
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition Type.h:73
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
void removeObjCLifetime()
Definition TypeBase.h:551
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:727
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:708
void removeAddressSpace()
Definition TypeBase.h:596
void setAddressSpace(LangAS space)
Definition TypeBase.h:591
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
Qualifiers withoutObjCLifetime() const
Definition TypeBase.h:533
Qualifiers withoutObjCGCAttr() const
Definition TypeBase.h:528
LangAS getAddressSpace() const
Definition TypeBase.h:571
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:750
Represents a struct/union/class.
Definition Decl.h:4347
bool hasFlexibleArrayMember() const
Definition Decl.h:4380
field_iterator field_end() const
Definition Decl.h:4553
field_range fields() const
Definition Decl.h:4550
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4535
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition Expr.cpp:5462
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:3637
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
bool isClassScope() const
isClassScope - Return true if this scope is a class/struct/union scope.
Definition Scope.h:410
bool Contains(const Scope &rhs) const
Returns if rhs has a higher scope depth than this.
Definition Scope.h:619
bool isInCFunctionScope() const
isInObjcMethodScope - Return true if this scope is, or is contained, in an C function body.
Definition Scope.h:430
bool isFunctionPrototypeScope() const
isFunctionPrototypeScope - Return true if this scope is a function prototype scope.
Definition Scope.h:469
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isUnarySelector() const
Expr * ExpandAMDGPUPredicateBuiltIn(Expr *CE)
Expand a valid use of the feature identification builtins into its corresponding sequence of instruct...
void AddPotentiallyUnguardedBuiltinUser(FunctionDecl *FD)
Diagnose unguarded usages of AMDGPU builtins and recommend guarding with __builtin_amdgcn_is_invocabl...
bool checkSVETypeSupport(QualType Ty, SourceLocation Loc, const FunctionDecl *FD, const llvm::StringMap< bool > &FeatureMap)
Definition SemaARM.cpp:1764
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:795
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:208
bool CheckCall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition SemaCUDA.cpp:973
@ 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)
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures.
Definition SemaObjC.h:858
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr)
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr)
const DeclContext * getCurObjCLexicalContext() const
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
void diagnoseARCUnbridgedCast(Expr *e)
Given that we saw an expression with the ARCUnbridgedCastTy placeholder type, complain bitterly.
ObjCMethodDecl * LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance)
LookupMethodInQualifiedType - Lookups up a method in protocol qualifier list of a qualified objective...
ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose=true, bool DiagnoseCFAudited=false, BinaryOperatorKind Opc=BO_PtrMemD, bool IsReinterpretCast=false)
Checks for invalid conversions and casts between retainable pointers and other pointer kinds for ARC ...
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod)
Build an ObjC subscript pseudo-object expression, given that that's supported by the runtime.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition SemaObjC.h:591
void CheckDeclReference(SourceLocation Loc, Expr *E, Decl *D)
ExprResult ActOnArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, Expr *Length, SourceLocation RBLoc)
Checks and creates an Array Section used in an OpenACC construct/clause.
ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig)
Given the potential call expression Call, determine if there is a specialization via the OpenMP decla...
void tryCaptureOpenMPLambdas(ValueDecl *V)
Function tries to capture lambda's captured variables in the OpenMP region before the original lambda...
OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) const
Check if the specified variable is used in 'private' clause.
VarDecl * isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo=false, unsigned StopAt=0)
Check if the specified variable is used in one of the private clauses (private, firstprivate,...
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc)
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const
Return true if the provided declaration VD should be captured by reference.
bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified variable is captured by 'target' directive.
bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified global variable must be captured by outer capture regions.
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition SemaOpenMP.h:378
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
const ValueDecl * getOpenMPDeclareMapperVarName() const
ExprResult checkAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS)
ExprResult checkIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op)
Check an increment or decrement of a pseudo-object expression.
ExprResult checkRValue(Expr *E)
void CheckDeviceUseOfDecl(NamedDecl *ND, SourceLocation Loc)
Issues a deferred diagnostic if use of the declaration designated by 'ND' is invalid in a device cont...
Definition SemaSYCL.cpp:224
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8534
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12552
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition Sema.h:12596
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7803
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T)
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1448
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
ExprResult ActOnCXXParenListInitExpr(ArrayRef< Expr * > Args, QualType T, unsigned NumUserSpecifiedExprs, SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition Sema.h:8287
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13688
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1141
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8337
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
bool isAlwaysConstantEvaluatedContext() const
Definition Sema.h:8255
bool isExternalWithNoLinkageType(const ValueDecl *VD) const
Determine if VD, which must be a variable or function, is an external symbol that nonetheless can't b...
Definition Sema.cpp:955
bool isAttrContext() const
Definition Sema.h:7034
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
ExprResult 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:8330
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9420
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition Sema.h:9459
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9428
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition SemaExpr.cpp:416
ExprResult CreateBuiltinMatrixSingleSubscriptExpr(Expr *Base, Expr *RowIdx, SourceLocation RBLoc)
ExprResult ActOnConstantExpression(ExprResult Res)
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool areVectorTypesSameSize(QualType srcType, QualType destType)
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs)
Decomposes the given name into a DeclarationNameInfo, its location, and possibly a list of template a...
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition Sema.h:1533
void ActOnStartStmtExpr()
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec)
Emit a warning for all pending noderef expressions that we recorded.
void ActOnStmtExprError()
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false, ArrayRef< const Expr * > StopAt={})
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
bool BoundsSafetyCheckAssignmentToCountAttrPtr(QualType LHSTy, Expr *RHSExpr, AssignmentAction Action, SourceLocation Loc, const ValueDecl *Assignee, bool ShowFullyQualifiedAssigneeName)
Perform Bounds Safety Semantic checks for assigning to a __counted_by or __counted_by_or_null pointer...
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
void CheckFloatComparison(SourceLocation Loc, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition Sema.h:1251
SemaCUDA & CUDA()
Definition Sema.h:1473
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
Definition Sema.h:7924
@ Switch
An integral condition for a 'switch' statement.
Definition Sema.h:7926
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
Definition Sema.h:7925
bool needsRebuildOfDefaultArgOrInit() const
Definition Sema.h:8275
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicCallType::DoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
SourceLocation LocationOfExcessPrecisionNotSatisfied
Definition Sema.h:8417
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1244
Preprocessor & getPreprocessor() const
Definition Sema.h:938
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition Sema.h:7012
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition Sema.cpp:2427
QualType GetSignedSizelessVectorType(QualType V)
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of 'this' is actually available in the current context, if it is a potentially ev...
llvm::SmallPtrSet< ConstantExpr *, 4 > FailedImmediateInvocations
Definition Sema.h:8406
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition Sema.h:8318
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor)
Do semantic checks to allow the complete destructor variant to be emitted when the destructor is defi...
void MarkCaptureUsedInEnclosingContext(ValueDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex)
llvm::SmallSetVector< Expr *, 4 > MaybeODRUseExprSet
Store a set of either DeclRefExprs or MemberExprs that contain a reference to a variable (constant) t...
Definition Sema.h:6841
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation, bool ReportInvalid)
type checking for vector binary operators.
LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef< QualType > ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit=nullptr)
LookupLiteralOperator - Determine which literal operator should be used for a user-defined literal,...
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2077
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types?
ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs)
ActOnDependentIdExpression - Handle a dependent id-expression that was just parsed.
ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth)
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=RedeclarationKind::NotForRedeclaration)
Look up a name, looking for a single declaration.
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
SemaSYCL & SYCL()
Definition Sema.h:1558
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition Sema.h:7024
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1725
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
bool CheckConceptUseInDefinition(NamedDecl *Concept, SourceLocation Loc)
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition SemaExpr.cpp:839
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
ExprResult CheckUnevaluatedOperand(Expr *E)
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Look for instances where it is likely the comma operator is confused with another operator.
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
std::vector< Token > ExpandFunctionLocalPredefinedMacros(ArrayRef< Token > Toks)
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
ASTContext & Context
Definition Sema.h:1308
static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading=false)
To be used for checking whether the arguments being passed to function exceeds the number of paramete...
Definition Sema.h:8242
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
the following "Check" methods will return a valid/converted QualType or a null QualType (indicating a...
bool DiagIfReachable(SourceLocation Loc, ArrayRef< const Stmt * > Stmts, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the statements's reachability analysis.
bool BoundsSafetyCheckUseOfCountAttrPtr(const Expr *E)
Perform Bounds Safety semantic checks for uses of invalid uses counted_by or counted_by_or_null point...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:226
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:936
ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME)
This is not an AltiVec-style cast or or C++ direct-initialization, so turn the ParenListExpr into a s...
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
bool CheckCaseExpression(Expr *E)
SemaObjC & ObjC()
Definition Sema.h:1518
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain=false, bool(*IsPlausibleResult)(QualType)=nullptr)
Try to recover by turning the given expression into a call.
Definition Sema.cpp:2937
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:760
bool isImmediateFunctionContext() const
Definition Sema.h:8267
ASTContext & getASTContext() const
Definition Sema.h:939
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1081
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition SemaExpr.cpp:770
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
void DiagnoseUnguardedAvailabilityViolations(Decl *FD)
Issue any -Wunguarded-availability warnings in FD.
void PopExpressionEvaluationContext()
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:762
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition SemaExpr.cpp:889
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr)
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition Sema.h:6159
@ None
This is not a defaultable comparison operator.
Definition Sema.h:6161
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1212
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition Sema.cpp:1730
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< TypeSourceInfo * > Types, ArrayRef< Expr * > Exprs)
ControllingExprOrType is either a TypeSourceInfo * or an Expr *.
AssumedTemplateKind
Definition Sema.h:11514
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
SourceRange getExprRange(Expr *E) const
Definition SemaExpr.cpp:511
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitCopyConstructor - Checks for feasibility of defining this constructor as the copy const...
std::optional< ExpressionEvaluationContextRecord::InitializationContext > OutermostDeclarationWithDelayedImmediateInvocations() const
Definition Sema.h:8302
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition SemaStmt.cpp:406
FPOptions & getCurFPFeatures()
Definition Sema.h:934
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition Sema.h:8400
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
@ UPPC_Block
Block expression.
Definition Sema.h:14568
const LangOptions & getLangOpts() const
Definition Sema.h:932
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage)
Lookup the specified comparison category types in the standard library, an check the VarDecls possibl...
void DiagnoseInvalidJumps(Stmt *Body)
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2558
QualType CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
SemaOpenACC & OpenACC()
Definition Sema.h:1523
ReuseLambdaContextDecl_t
Definition Sema.h:7103
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void MarkExpressionAsImmediateEscalating(Expr *E)
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc)
Produce diagnostics if FD is an aligned allocation or deallocation function that is unavailable.
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E)
Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false)
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
Preprocessor & PP
Definition Sema.h:1307
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R, bool IsAddressOfOperand)
Check whether an expression might be an implicit class member access.
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D=nullptr)
Check if the type is allowed to be used for the current target.
Definition Sema.cpp:2236
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:1306
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2673
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:958
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition Sema.h:6585
SemaHLSL & HLSL()
Definition Sema.h:1483
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
void CheckUnusedVolatileAssignment(Expr *E)
Check whether E, which is either a discarded-value expression or an unevaluated operand,...
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition Sema.h:15799
ExprResult prepareMatrixSplat(QualType MatrixTy, Expr *SplattedExpr)
Prepare SplattedExpr for a matrix splat operation, adding implicit casts if necessary.
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition SemaExpr.cpp:215
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
Definition Sema.h:5321
ExprResult BuildCXXReflectExpr(SourceLocation OperatorLoc, TypeSourceInfo *TSI)
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition SemaExpr.cpp:77
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Diagnose cases where a scalar was implicitly converted to a vector and diagnose the underlying types.
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any ArgDependent DiagnoseIfAttr...
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7048
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition Sema.h:6615
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs=true)
Find a merged pointer type and convert the two expressions to it.
SmallVector< std::deque< PendingImplicitInstantiation >, 8 > SavedPendingInstantiations
Definition Sema.h:14110
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition Sema.cpp:869
void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a block pointer.
void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor)
DefineImplicitDestructor - Checks for feasibility of defining this destructor as the default destruct...
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1341
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, StringLiteral *BinaryData, StringRef FileName)
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr)
DiagnoseAssignmentEnum - Warn if assignment to enum is a constant integer not in the range of enum va...
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition Sema.h:7045
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2410
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:644
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition Sema.h:8271
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< ParsedType > ArgTypes, ArrayRef< Expr * > ArgExprs)
ControllingExprOrType is either an opaque pointer coming out of a ParsedType or an Expr *.
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
bool IsAssignConvertCompatible(AssignConvertType ConvTy)
Definition Sema.h:8138
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition Sema.cpp:2628
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1446
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path)
Check a cast of an unknown-any type.
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition Sema.h:12623
SemaOpenCL & OpenCL()
Definition Sema.h:1528
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition Sema.h:14119
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared copy assignment operator.
bool DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation QuestionLoc)
Emit a specialized diagnostic when one expression is a null pointer constant and the other is not a p...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8263
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition Sema.cpp:1705
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr, bool ForTypeDeduction=false)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition Sema.h:6844
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
ExprResult TransformToPotentiallyEvaluated(Expr *E)
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef< Expr * > Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14054
SourceManager & getSourceManager() const
Definition Sema.h:937
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
bool CheckVecStepExpr(Expr *E)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckVectorCompareOperands - vector comparisons are a clang extension that operates on extended vecto...
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks, ObjCInterfaceDecl *ClassReceiver)
CallExpr::ADLCallKind ADLCallKind
Definition Sema.h:7557
@ NTCUK_Destruct
Definition Sema.h:4139
@ NTCUK_Copy
Definition Sema.h:4140
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition Sema.h:8416
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
bool anyAltivecTypes(QualType srcType, QualType destType)
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition Sema.cpp:2458
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
QualType CXXCheckConditionalOperands(ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc)
Check the operands of ?
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
MaybeODRUseExprSet MaybeODRUseExprs
Definition Sema.h:6842
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool isSFINAEContext() const
Definition Sema.h:13787
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:15571
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:2613
bool isConstantEvaluatedContext() const
Definition Sema.h:2639
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
void FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *DeclInit)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
ASTConsumer & Consumer
Definition Sema.h:1309
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition Sema.h:4698
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType.
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:7052
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:125
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1346
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition Sema.h:14102
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
QualType CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc)
Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition Sema.h:6786
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6808
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6798
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6813
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6803
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6823
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6792
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6818
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6833
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range)
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Parse a __builtin_astype expression.
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition Sema.h:1267
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD)
QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope.
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition Sema.h:8253
void DiscardCleanupsInEvaluationContext()
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8403
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AvailabilityMergeKind::Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
SourceManager & SourceMgr
Definition Sema.h:1311
@ TemplateNameIsRequired
Definition Sema.h:11491
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:789
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const
Determine whether FD is an aligned allocation or deallocation function that is unavailable.
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1310
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:933
FPOptions CurFPFeatures
Definition Sema.h:1304
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:520
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType)
Are the two types lax-compatible vector types?
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc, bool IsExplicit)
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
friend class InitializationSequence
Definition Sema.h:1588
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
void PopDeclContext()
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition Sema.h:6619
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope)
ActOnBlockStmtExpr - This is called when the body of a block statement literal was successfully compl...
void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD)
Produce notes explaining why a defaulted function was defined as deleted.
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:631
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained=nullptr)
DiagnoseAssignmentResult - Emit a diagnostic, if required, for the assignment conversion type specifi...
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
ExprResult ActOnStmtExprResult(ExprResult E)
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2219
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
QualType CheckMatrixLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange)
ActOnUnaryExprOrTypeTraitExpr - Handle sizeof(type) and sizeof expr and the same for alignof and __al...
QualType PreferredConditionType(ConditionKind K) const
Definition Sema.h:8061
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition Sema.h:9473
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition Sema.h:9479
@ LOLR_Error
The lookup resulted in an error.
Definition Sema.h:9471
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition Sema.h:9476
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition Sema.h:9487
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition Sema.h:9483
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6500
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition Sema.h:14098
unsigned getTemplateDepth(Scope *S) const
Determine the number of levels of enclosing template parameters.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void checkEnumArithmeticConversions(Expr *LHS, Expr *RHS, SourceLocation Loc, ArithConvKind ACK)
Check that the usual arithmetic conversions can be performed on this pair of expressions that might b...
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
static ConditionResult ConditionError()
Definition Sema.h:7910
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ActOnConvertVectorExpr - create a new convert-vector expression from the provided arguments.
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType)
Type-check an expression that's being passed to an __unknown_anytype parameter.
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
SemaPseudoObject & PseudoObject()
Definition Sema.h:1543
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition Sema.cpp:2604
bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy)
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
bool isCheckingDefaultArgumentOrInitializer() const
Definition Sema.h:8279
SemaARM & ARM()
Definition Sema.h:1453
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
SmallVector< std::pair< Scope *, SourceLocation >, 2 > CurrentDefer
Stack of '_Defer' statements that are currently being parsed, as well as the locations of their '_Def...
Definition Sema.h:11061
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:8748
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:5023
SourceLocation getBeginLoc() const
Definition Expr.h:5068
const DeclContext * getParentContext() const
If the SourceLocExpr has been resolved return the subexpression representing the resolved value.
Definition Expr.h:5064
SourceLocation getEndLoc() const
Definition Expr.h:5069
SourceLocIdentKind getIdentKind() const
Definition Expr.h:5043
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition Overload.h:298
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:309
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition Overload.h:396
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4601
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Stmt - This represents one statement.
Definition Stmt.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
StmtClass getStmtClass() const
Definition Stmt.h:1503
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
unsigned getLength() const
Definition Expr.h:1915
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
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1888
StringRef getString() const
Definition Expr.h:1873
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3840
bool isUnion() const
Definition Decl.h:3950
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
Exposes information about the current target.
Definition TargetInfo.h:227
virtual bool hasLongDoubleType() const
Determine whether the long double type is supported on this target.
Definition TargetInfo.h:736
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition TargetInfo.h:336
virtual bool useFP16ConversionIntrinsics() const
Check whether conversions to and from __fp16 should go through an integer bitcast with i16.
bool shouldUseMicrosoftCCforMangling() const
Should the Microsoft mangling scheme be used for C Calling Convention.
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
Location wrapper for a TemplateArgument.
Represents a template argument.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Represents a C++ template name within the type system.
A template parameter object.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
void setKind(tok::TokenKind K)
Definition Token.h:100
void startToken()
Reset all flags to cleared.
Definition Token.h:187
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
EnsureImmediateInvocationInDefaultArgs & getDerived()
Represents a declaration of a type.
Definition Decl.h:3535
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3569
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition TypeLoc.h:217
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
SourceRange getLocalSourceRange() const
Get the local source range.
Definition TypeLoc.h:160
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:2735
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8418
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:8429
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2545
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition TypeBase.h:9118
bool isBlockPointerType() const
Definition TypeBase.h:8704
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
bool isObjCBuiltinType() const
Definition TypeBase.h:8914
bool isMFloat8Type() const
Definition TypeBase.h:9075
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition Type.cpp:2000
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition TypeBase.h:9237
bool isIncompleteArrayType() const
Definition TypeBase.h:8791
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:9026
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:761
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2173
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9217
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
Definition Type.cpp:2119
bool isVoidPointerType() const
Definition Type.cpp:749
const ComplexType * getAsComplexIntegerType() const
Definition Type.cpp:782
bool isArrayType() const
Definition TypeBase.h:8783
bool isCharType() const
Definition Type.cpp:2193
bool isFunctionPointerType() const
Definition TypeBase.h:8751
bool isArithmeticType() const
Definition Type.cpp:2422
bool isConstantMatrixType() const
Definition TypeBase.h:8851
bool isPointerType() const
Definition TypeBase.h:8684
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2667
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
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:9138
bool isEnumeralType() const
Definition TypeBase.h:8815
bool isScalarType() const
Definition TypeBase.h:9156
bool isVariableArrayType() const
Definition TypeBase.h:8795
bool isSizelessBuiltinType() const
Definition Type.cpp:2623
bool isClkEventT() const
Definition TypeBase.h:8936
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2701
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2156
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8884
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9172
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition Type.cpp:2376
bool isExtVectorType() const
Definition TypeBase.h:8827
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2229
bool isExtVectorBoolType() const
Definition TypeBase.h:8831
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2740
bool isImageType() const
Definition TypeBase.h:8948
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition TypeBase.h:9044
bool isPipeType() const
Definition TypeBase.h:8955
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2854
bool isBitIntType() const
Definition TypeBase.h:8959
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9019
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8807
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
bool isAnyComplexType() const
Definition TypeBase.h:8819
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9110
bool isHalfType() const
Definition TypeBase.h:9054
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9126
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2465
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition Type.cpp:2454
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9032
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition Type.cpp:2310
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2651
bool isQueueT() const
Definition TypeBase.h:8940
bool isMemberPointerType() const
Definition TypeBase.h:8765
bool isAtomicType() const
Definition TypeBase.h:8876
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9200
bool isObjCIdType() const
Definition TypeBase.h:8896
bool isMatrixType() const
Definition TypeBase.h:8847
bool isOverflowBehaviorType() const
Definition TypeBase.h:8855
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:2864
bool isComplexIntegerType() const
Definition Type.cpp:767
bool isUnscopedEnumerationType() const
Definition Type.cpp:2186
bool isObjCObjectType() const
Definition TypeBase.h:8867
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition Type.cpp:5361
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9330
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5450
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9193
bool isHLSLResourceRecord() const
Definition Type.cpp:5510
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isDoubleType() const
Definition TypeBase.h:9067
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2527
bool isFunctionType() const
Definition TypeBase.h:8680
bool isObjCObjectPointerType() const
Definition TypeBase.h:8863
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition Type.cpp:2397
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9152
bool isVectorType() const
Definition TypeBase.h:8823
bool isObjCQualifiedClassType() const
Definition TypeBase.h:8890
bool isObjCClassType() const
Definition TypeBase.h:8902
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2405
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2688
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2985
@ STK_FloatingComplex
Definition TypeBase.h:2828
@ STK_ObjCObjectPointer
Definition TypeBase.h:2822
@ STK_IntegralComplex
Definition TypeBase.h:2827
@ STK_MemberPointer
Definition TypeBase.h:2823
bool isFloatingType() const
Definition Type.cpp:2389
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2332
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
Definition TypeBase.h:2992
bool isAnyPointerType() const
Definition TypeBase.h:8692
bool isRealType() const
Definition Type.cpp:2411
TypeClass getTypeClass() const
Definition TypeBase.h:2445
bool isSubscriptableVectorType() const
Definition TypeBase.h:8843
bool isSamplerT() const
Definition TypeBase.h:8928
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
bool isNullPtrType() const
Definition TypeBase.h:9087
bool isRecordType() const
Definition TypeBase.h:8811
bool isHLSLResourceRecordArray() const
Definition Type.cpp:5514
bool isScopedEnumeralType() const
Determine whether this type is a scoped enumeration type.
Definition Type.cpp:772
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5152
bool isUnicodeCharacterType() const
Definition Type.cpp:2249
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
Definition Type.cpp:2444
Wrapper for source info for typedefs.
Definition TypeLoc.h:777
Simple class containing the result of Sema::CorrectTypo.
IdentifierInfo * getCorrectionAsIdentifierInfo() const
std::string getAsString(const LangOptions &LO) const
SourceRange getCorrectionRange() const
void WillReplaceSpecifier(bool ForceReplacement)
DeclClass * getCorrectionDeclAs() const
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
NestedNameSpecifier getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2631
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
void setSubExpr(Expr *E)
Definition Expr.h:2292
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition Expr.h:2295
Expr * getSubExpr() const
Definition Expr.h:2291
Opcode getOpcode() const
Definition Expr.h:2286
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1436
static bool isIncrementDecrementOp(Opcode Op)
Definition Expr.h:2346
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:5161
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition DeclCXX.h:4473
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:3390
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:437
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4126
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition ExprCXX.cpp:1690
bool isImplicitAccess() const
True if this is an implicit access, i.e., one in which the member being accessed was not written in t...
Definition ExprCXX.cpp:1652
A set of unresolved declarations.
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition ExprCXX.h:644
Represents a call to the builtin function __builtin_va_arg.
Definition Expr.h:4963
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
void setType(QualType newType)
Definition Decl.h:724
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5577
VarDecl * getPotentiallyDecomposedVarDecl()
Definition DeclCXX.cpp:3683
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:924
bool hasInit() const
Definition Decl.cpp:2377
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:2236
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1591
bool isInternalLinkageFileVar() const
Returns true if this is a file-scope variable with internal linkage.
Definition Decl.h:1214
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1296
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1239
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition Decl.cpp:2465
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition Decl.cpp:2867
bool isInline() const
Whether this variable is (C++1z) inline.
Definition Decl.h:1564
const Expr * getInit() const
Definition Decl.h:1381
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition Decl.h:1230
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1182
@ TLS_None
Not a TLS variable.
Definition Decl.h:944
@ DeclarationOnly
This declaration is only a declaration.
Definition Decl.h:1308
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition Decl.cpp:2354
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition Decl.cpp:2507
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2760
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition Decl.h:1275
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition Decl.cpp:2739
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2858
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4030
Expr * getSizeExpr() const
Definition TypeBase.h:4044
Represents a GCC generic vector type.
Definition TypeBase.h:4239
unsigned getNumElements() const
Definition TypeBase.h:4254
VectorKind getVectorKind() const
Definition TypeBase.h:4259
QualType getElementType() const
Definition TypeBase.h:4253
Retains information about a block that is currently being parsed.
Definition ScopeInfo.h:786
Scope * TheScope
TheScope - This is the scope for the block itself, which contains arguments etc.
Definition ScopeInfo.h:792
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition ScopeInfo.h:796
ValueDecl * getVariable() const
Definition ScopeInfo.h:671
bool isBlockCapture() const
Definition ScopeInfo.h:652
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:682
void markUsed(bool IsODRUse)
Definition ScopeInfo.h:664
bool isInvalid() const
Definition ScopeInfo.h:657
bool isThisCapture() const
Definition ScopeInfo.h:645
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition ScopeInfo.h:691
bool isCopyCapture() const
Definition ScopeInfo.h:650
bool isNested() const
Definition ScopeInfo.h:655
Retains information about a captured region.
Definition ScopeInfo.h:812
unsigned short CapRegionKind
The kind of captured region.
Definition ScopeInfo.h:827
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition ScopeInfo.h:741
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:728
bool ContainsUnexpandedParameterPack
Whether this contains an unexpanded parameter pack.
Definition ScopeInfo.h:724
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:717
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:704
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of 'this'; zero if 'this' is not captured.
Definition ScopeInfo.h:714
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition ScopeInfo.h:754
llvm::DenseMap< ValueDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition ScopeInfo.h:710
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:751
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:733
Capture & getCapture(ValueDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition ScopeInfo.h:767
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:1086
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:489
llvm::SmallVector< AddrLabelExpr *, 4 > AddrLabels
The set of GNU address of label extension "&&label".
Definition ScopeInfo.h:246
bool HasOMPDeclareReductionCombiner
True if current scope is for OpenMP declare reduction combiner.
Definition ScopeInfo.h:135
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:880
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:988
void addPotentialThisCapture(SourceLocation Loc)
Definition ScopeInfo.h:994
llvm::SmallPtrSet< VarDecl *, 4 > CUDAPotentialODRUsedVars
Variables that are potentially ODR-used in CUDA/HIP.
Definition ScopeInfo.h:949
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:867
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition ScopeInfo.h:888
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:875
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:870
Defines the clang::TargetInfo interface.
Definition SPIR.cpp:35
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition TokenKinds.h:93
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:213
@ CPlusPlus23
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus14
@ CPlusPlus26
@ CPlusPlus17
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ GVA_StrongExternal
Definition Linkage.h:76
VariadicCallType
Definition Sema.h:513
bool isTargetAddressSpace(LangAS AS)
CUDAFunctionTarget
Definition Cuda.h:63
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
TryCaptureKind
Definition Sema.h:653
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition Sema.h:661
@ BitwiseOp
A bitwise operation.
Definition Sema.h:665
@ Arithmetic
An arithmetic operation.
Definition Sema.h:663
@ Conditional
A conditional (?:) operator.
Definition Sema.h:669
@ CompAssign
A compound assignment expression.
Definition Sema.h:671
@ Comparison
A comparison.
Definition Sema.h:667
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:349
@ Nullable
Values of this type can be null.
Definition Specifiers.h:353
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:358
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:351
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition Specifiers.h:150
@ OK_VectorComponent
A vector component is an element or range of elements of a vector.
Definition Specifiers.h:158
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition Specifiers.h:162
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition Specifiers.h:155
@ OK_MatrixComponent
A matrix component is a single element or range of elements of a matrix.
Definition Specifiers.h:170
std::string FormatUTFCodeUnitAsCodepoint(unsigned Value, QualType T)
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h: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
Expr * Cond
};
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
Definition Parser.h:142
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition TypeTraits.h:51
unsigned toTargetAddressSpace(LangAS AS)
ExprResult ExprEmpty()
Definition Ownership.h:272
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:205
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_Identity
Identity conversion (no conversion)
Definition Overload.h:106
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition Overload.h:136
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition Overload.h:115
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:689
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:712
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition Sema.h:787
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition Sema.h:704
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition Sema.h:759
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition Sema.h:749
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition Sema.h:776
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition Sema.h:763
@ CompatibleOBTDiscards
CompatibleOBTDiscards - Assignment discards overflow behavior.
Definition Sema.h:783
@ IncompatibleOBTKinds
IncompatibleOBTKinds - Assigning between incompatible OverflowBehaviorType kinds, e....
Definition Sema.h:780
@ CompatibleVoidPtrToNonVoidPtr
CompatibleVoidPtrToNonVoidPtr - The types are compatible in C because a void * can implicitly convert...
Definition Sema.h:696
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition Sema.h:738
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:733
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition Sema.h:772
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:691
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition Sema.h:723
@ IncompatiblePointerDiscardsOverflowBehavior
IncompatiblePointerDiscardsOverflowBehavior - The assignment discards overflow behavior annotations b...
Definition Sema.h:743
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition Sema.h:700
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition Sema.h:708
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition Sema.h:755
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition Sema.h:717
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:729
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition Sema.h:767
bool isFunctionLocalStringLiteralMacro(tok::TokenKind K, const LangOptions &LO)
Return true if the token corresponds to a function local predefined macro, which expands to a string ...
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:564
@ AR_Unavailable
Definition DeclBase.h:76
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
AllowFoldKind
Definition Sema.h:655
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
VarArgKind
Definition Sema.h:676
bool isLambdaConversionOperator(CXXConversionDecl *C)
Definition ASTLambda.h:69
AssignmentAction
Definition Sema.h:216
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
@ TNK_Concept_template
The name refers to a concept.
BuiltinCountedByRefKind
Definition Sema.h:521
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool isPtrSizeAddressSpace(LangAS AS)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
const char * getTraitSpelling(ExpressionTrait T) LLVM_READONLY
Return the spelling of the type trait TT. Never null.
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
@ 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:1769
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:4209
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4218
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4203
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4206
@ Neon
is ARM Neon vector
Definition TypeBase.h:4212
@ Generic
not a target-specific vector type
Definition TypeBase.h:4200
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4224
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4227
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4221
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:5010
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:5991
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition OpenMPKinds.h:28
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Other
Other implicit parameter.
Definition Decl.h:1763
PredefinedIdentKind
Definition Expr.h:1995
@ Implicit
An implicit conversion.
Definition Sema.h:440
OptionalUnsigned< NullabilityKind > NullabilityKindOrNone
Definition Specifiers.h:365
CharacterLiteralKind
Definition Expr.h:1609
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:5099
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:652
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:654
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:640
bool DiagEmitted
Whether any diagnostic has been emitted.
Definition Expr.h:624
bool HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition Expr.h:620
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:615
Extra information about a function prototype.
Definition TypeBase.h:5456
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13216
Data structure used to record current or nested expression evaluation contexts.
Definition Sema.h:6848
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition Sema.h:6883
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition Sema.h:6934
Decl * ManglingContextDecl
The declaration that provides context for lambda expressions and block literals if the normal declara...
Definition Sema.h:6868
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition Sema.h:6888
llvm::SmallPtrSet< DeclRefExpr *, 4 > ReferenceToConsteval
Set of DeclRefExprs referencing a consteval function when used in a context not already known to be i...
Definition Sema.h:6896
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition Sema.h:6892
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition Sema.h:6902
enum clang::Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext
SmallVector< LambdaExpr *, 2 > Lambdas
The lambdas that are present within this context, if it is indeed an unevaluated context.
Definition Sema.h:6863
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition Sema.h:6910
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition Sema.h:6853
ExpressionEvaluationContext Context
The expression evaluation context.
Definition Sema.h:6850
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition Sema.h:6857
Abstract class used to diagnose incomplete types.
Definition Sema.h:8344
Location information for a TemplateArgument.
TemplateNameKind Kind
The kind of template that Template refers to.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.
Describes an entity that is being assigned.