clang 20.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"
18#include "clang/AST/ASTLambda.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclObjC.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/ExprObjC.h"
31#include "clang/AST/Type.h"
32#include "clang/AST/TypeLoc.h"
43#include "clang/Sema/DeclSpec.h"
48#include "clang/Sema/Lookup.h"
49#include "clang/Sema/Overload.h"
51#include "clang/Sema/Scope.h"
53#include "clang/Sema/SemaCUDA.h"
55#include "clang/Sema/SemaHLSL.h"
57#include "clang/Sema/SemaObjC.h"
60#include "clang/Sema/Template.h"
61#include "llvm/ADT/STLExtras.h"
62#include "llvm/ADT/STLForwardCompat.h"
63#include "llvm/ADT/StringExtras.h"
64#include "llvm/Support/ConvertUTF.h"
65#include "llvm/Support/SaveAndRestore.h"
66#include "llvm/Support/TimeProfiler.h"
67#include "llvm/Support/TypeSize.h"
68#include <optional>
69
70using namespace clang;
71using namespace sema;
72
73bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
74 // See if this is an auto-typed variable whose initializer we are parsing.
75 if (ParsingInitForAutoVars.count(D))
76 return false;
77
78 // See if this is a deleted function.
79 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
80 if (FD->isDeleted())
81 return false;
82
83 // If the function has a deduced return type, and we can't deduce it,
84 // then we can't use it either.
85 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
86 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
87 return false;
88
89 // See if this is an aligned allocation/deallocation function that is
90 // unavailable.
91 if (TreatUnavailableAsInvalid &&
93 return false;
94 }
95
96 // See if this function is unavailable.
97 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
98 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
99 return false;
100
101 if (isa<UnresolvedUsingIfExistsDecl>(D))
102 return false;
103
104 return true;
105}
106
108 // Warn if this is used but marked unused.
109 if (const auto *A = D->getAttr<UnusedAttr>()) {
110 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
111 // should diagnose them.
112 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
113 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
114 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
115 if (DC && !DC->hasAttr<UnusedAttr>())
116 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
117 }
118 }
119}
120
122 assert(Decl && Decl->isDeleted());
123
124 if (Decl->isDefaulted()) {
125 // If the method was explicitly defaulted, point at that declaration.
126 if (!Decl->isImplicit())
127 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
128
129 // Try to diagnose why this special member function was implicitly
130 // deleted. This might fail, if that reason no longer applies.
132 return;
133 }
134
135 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
136 if (Ctor && Ctor->isInheritingConstructor())
138
139 Diag(Decl->getLocation(), diag::note_availability_specified_here)
140 << Decl << 1;
141}
142
143/// Determine whether a FunctionDecl was ever declared with an
144/// explicit storage class.
146 for (auto *I : D->redecls()) {
147 if (I->getStorageClass() != SC_None)
148 return true;
149 }
150 return false;
151}
152
153/// Check whether we're in an extern inline function and referring to a
154/// variable or function with internal linkage (C11 6.7.4p3).
155///
156/// This is only a warning because we used to silently accept this code, but
157/// in many cases it will not behave correctly. This is not enabled in C++ mode
158/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
159/// and so while there may still be user mistakes, most of the time we can't
160/// prove that there are errors.
162 const NamedDecl *D,
164 // This is disabled under C++; there are too many ways for this to fire in
165 // contexts where the warning is a false positive, or where it is technically
166 // correct but benign.
167 if (S.getLangOpts().CPlusPlus)
168 return;
169
170 // Check if this is an inlined function or method.
171 FunctionDecl *Current = S.getCurFunctionDecl();
172 if (!Current)
173 return;
174 if (!Current->isInlined())
175 return;
176 if (!Current->isExternallyVisible())
177 return;
178
179 // Check if the decl has internal linkage.
180 if (D->getFormalLinkage() != Linkage::Internal)
181 return;
182
183 // Downgrade from ExtWarn to Extension if
184 // (1) the supposedly external inline function is in the main file,
185 // and probably won't be included anywhere else.
186 // (2) the thing we're referencing is a pure function.
187 // (3) the thing we're referencing is another inline function.
188 // This last can give us false negatives, but it's better than warning on
189 // wrappers for simple C library functions.
190 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
191 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
192 if (!DowngradeWarning && UsedFn)
193 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
194
195 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
196 : diag::ext_internal_in_extern_inline)
197 << /*IsVar=*/!UsedFn << D;
198
200
201 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
202 << D;
203}
204
206 const FunctionDecl *First = Cur->getFirstDecl();
207
208 // Suggest "static" on the function, if possible.
210 SourceLocation DeclBegin = First->getSourceRange().getBegin();
211 Diag(DeclBegin, diag::note_convert_inline_to_static)
212 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
213 }
214}
215
217 const ObjCInterfaceDecl *UnknownObjCClass,
218 bool ObjCPropertyAccess,
219 bool AvoidPartialAvailabilityChecks,
220 ObjCInterfaceDecl *ClassReceiver,
221 bool SkipTrailingRequiresClause) {
222 SourceLocation Loc = Locs.front();
223 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
224 // If there were any diagnostics suppressed by template argument deduction,
225 // emit them now.
226 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
227 if (Pos != SuppressedDiagnostics.end()) {
228 for (const PartialDiagnosticAt &Suppressed : Pos->second)
229 Diag(Suppressed.first, Suppressed.second);
230
231 // Clear out the list of suppressed diagnostics, so that we don't emit
232 // them again for this specialization. However, we don't obsolete this
233 // entry from the table, because we want to avoid ever emitting these
234 // diagnostics again.
235 Pos->second.clear();
236 }
237
238 // C++ [basic.start.main]p3:
239 // The function 'main' shall not be used within a program.
240 if (cast<FunctionDecl>(D)->isMain())
241 Diag(Loc, diag::ext_main_used);
242
243 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
244 }
245
246 // See if this is an auto-typed variable whose initializer we are parsing.
247 if (ParsingInitForAutoVars.count(D)) {
248 if (isa<BindingDecl>(D)) {
249 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
250 << D->getDeclName();
251 } else {
252 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
253 << D->getDeclName() << cast<VarDecl>(D)->getType();
254 }
255 return true;
256 }
257
258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
259 // See if this is a deleted function.
260 if (FD->isDeleted()) {
261 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
262 if (Ctor && Ctor->isInheritingConstructor())
263 Diag(Loc, diag::err_deleted_inherited_ctor_use)
264 << Ctor->getParent()
265 << Ctor->getInheritedConstructor().getConstructor()->getParent();
266 else {
267 StringLiteral *Msg = FD->getDeletedMessage();
268 Diag(Loc, diag::err_deleted_function_use)
269 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
270 }
272 return true;
273 }
274
275 // [expr.prim.id]p4
276 // A program that refers explicitly or implicitly to a function with a
277 // trailing requires-clause whose constraint-expression is not satisfied,
278 // other than to declare it, is ill-formed. [...]
279 //
280 // See if this is a function with constraints that need to be satisfied.
281 // Check this before deducing the return type, as it might instantiate the
282 // definition.
283 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
284 ConstraintSatisfaction Satisfaction;
285 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
286 /*ForOverloadResolution*/ true))
287 // A diagnostic will have already been generated (non-constant
288 // constraint expression, for example)
289 return true;
290 if (!Satisfaction.IsSatisfied) {
291 Diag(Loc,
292 diag::err_reference_to_function_with_unsatisfied_constraints)
293 << D;
294 DiagnoseUnsatisfiedConstraint(Satisfaction);
295 return true;
296 }
297 }
298
299 // If the function has a deduced return type, and we can't deduce it,
300 // then we can't use it either.
301 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
303 return true;
304
305 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
306 return true;
307
308 }
309
310 if (auto *Concept = dyn_cast<ConceptDecl>(D);
312 return true;
313
314 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
315 // Lambdas are only default-constructible or assignable in C++2a onwards.
316 if (MD->getParent()->isLambda() &&
317 ((isa<CXXConstructorDecl>(MD) &&
318 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
319 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
320 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
321 << !isa<CXXConstructorDecl>(MD);
322 }
323 }
324
325 auto getReferencedObjCProp = [](const NamedDecl *D) ->
326 const ObjCPropertyDecl * {
327 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
328 return MD->findPropertyDecl();
329 return nullptr;
330 };
331 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
333 return true;
335 return true;
336 }
337
338 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
339 // Only the variables omp_in and omp_out are allowed in the combiner.
340 // Only the variables omp_priv and omp_orig are allowed in the
341 // initializer-clause.
342 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
343 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
344 isa<VarDecl>(D)) {
345 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
347 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348 return true;
349 }
350
351 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
352 // List-items in map clauses on this construct may only refer to the declared
353 // variable var and entities that could be referenced by a procedure defined
354 // at the same location.
355 // [OpenMP 5.2] Also allow iterator declared variables.
356 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
357 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
358 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
360 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
361 return true;
362 }
363
364 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
365 Diag(Loc, diag::err_use_of_empty_using_if_exists);
366 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
367 return true;
368 }
369
370 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
371 AvoidPartialAvailabilityChecks, ClassReceiver);
372
373 DiagnoseUnusedOfDecl(*this, D, Loc);
374
376
377 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
378 if (getLangOpts().getFPEvalMethod() !=
381 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
382 Diag(D->getLocation(),
383 diag::err_type_available_only_in_default_eval_method)
384 << D->getName();
385 }
386
387 if (auto *VD = dyn_cast<ValueDecl>(D))
388 checkTypeSupport(VD->getType(), Loc, VD);
389
390 if (LangOpts.SYCLIsDevice ||
391 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
393 if (const auto *VD = dyn_cast<VarDecl>(D))
394 if (VD->getTLSKind() != VarDecl::TLS_None)
395 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
396 }
397
398 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
400 // C++ [expr.prim.req.nested] p3
401 // A local parameter shall only appear as an unevaluated operand
402 // (Clause 8) within the constraint-expression.
403 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
404 << D;
405 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
406 return true;
407 }
408
409 return false;
410}
411
413 ArrayRef<Expr *> Args) {
414 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
415 if (!Attr)
416 return;
417
418 // The number of formal parameters of the declaration.
419 unsigned NumFormalParams;
420
421 // The kind of declaration. This is also an index into a %select in
422 // the diagnostic.
423 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
424
425 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
426 NumFormalParams = MD->param_size();
427 CalleeKind = CK_Method;
428 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
429 NumFormalParams = FD->param_size();
430 CalleeKind = CK_Function;
431 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
432 QualType Ty = VD->getType();
433 const FunctionType *Fn = nullptr;
434 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
435 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
436 if (!Fn)
437 return;
438 CalleeKind = CK_Function;
439 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
440 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
441 CalleeKind = CK_Block;
442 } else {
443 return;
444 }
445
446 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
447 NumFormalParams = proto->getNumParams();
448 else
449 NumFormalParams = 0;
450 } else {
451 return;
452 }
453
454 // "NullPos" is the number of formal parameters at the end which
455 // effectively count as part of the variadic arguments. This is
456 // useful if you would prefer to not have *any* formal parameters,
457 // but the language forces you to have at least one.
458 unsigned NullPos = Attr->getNullPos();
459 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
460 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
461
462 // The number of arguments which should follow the sentinel.
463 unsigned NumArgsAfterSentinel = Attr->getSentinel();
464
465 // If there aren't enough arguments for all the formal parameters,
466 // the sentinel, and the args after the sentinel, complain.
467 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
468 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
469 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
470 return;
471 }
472
473 // Otherwise, find the sentinel expression.
474 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
475 if (!SentinelExpr)
476 return;
477 if (SentinelExpr->isValueDependent())
478 return;
479 if (Context.isSentinelNullExpr(SentinelExpr))
480 return;
481
482 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
483 // or 'NULL' if those are actually defined in the context. Only use
484 // 'nil' for ObjC methods, where it's much more likely that the
485 // variadic arguments form a list of object pointers.
486 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
487 std::string NullValue;
488 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
489 NullValue = "nil";
490 else if (getLangOpts().CPlusPlus11)
491 NullValue = "nullptr";
492 else if (PP.isMacroDefined("NULL"))
493 NullValue = "NULL";
494 else
495 NullValue = "(void*) 0";
496
497 if (MissingNilLoc.isInvalid())
498 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
499 else
500 Diag(MissingNilLoc, diag::warn_missing_sentinel)
501 << int(CalleeKind)
502 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
503 Diag(D->getLocation(), diag::note_sentinel_here)
504 << int(CalleeKind) << Attr->getRange();
505}
506
508 return E ? E->getSourceRange() : SourceRange();
509}
510
511//===----------------------------------------------------------------------===//
512// Standard Promotions and Conversions
513//===----------------------------------------------------------------------===//
514
515/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
517 // Handle any placeholder expressions which made it here.
518 if (E->hasPlaceholderType()) {
520 if (result.isInvalid()) return ExprError();
521 E = result.get();
522 }
523
524 QualType Ty = E->getType();
525 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
526
527 if (Ty->isFunctionType()) {
528 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
529 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
531 return ExprError();
532
534 CK_FunctionToPointerDecay).get();
535 } else if (Ty->isArrayType()) {
536 // In C90 mode, arrays only promote to pointers if the array expression is
537 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
538 // type 'array of type' is converted to an expression that has type 'pointer
539 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
540 // that has type 'array of type' ...". The relevant change is "an lvalue"
541 // (C90) to "an expression" (C99).
542 //
543 // C++ 4.2p1:
544 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
545 // T" can be converted to an rvalue of type "pointer to T".
546 //
547 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
549 CK_ArrayToPointerDecay);
550 if (Res.isInvalid())
551 return ExprError();
552 E = Res.get();
553 }
554 }
555 return E;
556}
557
559 // Check to see if we are dereferencing a null pointer. If so,
560 // and if not volatile-qualified, this is undefined behavior that the
561 // optimizer will delete, so warn about it. People sometimes try to use this
562 // to get a deterministic trap and are surprised by clang's behavior. This
563 // only handles the pattern "*null", which is a very syntactic check.
564 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
565 if (UO && UO->getOpcode() == UO_Deref &&
566 UO->getSubExpr()->getType()->isPointerType()) {
567 const LangAS AS =
568 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
569 if ((!isTargetAddressSpace(AS) ||
570 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
571 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
573 !UO->getType().isVolatileQualified()) {
574 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
575 S.PDiag(diag::warn_indirection_through_null)
576 << UO->getSubExpr()->getSourceRange());
577 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
578 S.PDiag(diag::note_indirection_through_null));
579 }
580 }
581}
582
583static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
584 SourceLocation AssignLoc,
585 const Expr* RHS) {
586 const ObjCIvarDecl *IV = OIRE->getDecl();
587 if (!IV)
588 return;
589
590 DeclarationName MemberName = IV->getDeclName();
592 if (!Member || !Member->isStr("isa"))
593 return;
594
595 const Expr *Base = OIRE->getBase();
596 QualType BaseType = Base->getType();
597 if (OIRE->isArrow())
598 BaseType = BaseType->getPointeeType();
599 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
600 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
601 ObjCInterfaceDecl *ClassDeclared = nullptr;
602 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
603 if (!ClassDeclared->getSuperClass()
604 && (*ClassDeclared->ivar_begin()) == IV) {
605 if (RHS) {
606 NamedDecl *ObjectSetClass =
608 &S.Context.Idents.get("object_setClass"),
610 if (ObjectSetClass) {
611 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
612 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
614 "object_setClass(")
616 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
617 << FixItHint::CreateInsertion(RHSLocEnd, ")");
618 }
619 else
620 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
621 } else {
622 NamedDecl *ObjectGetClass =
624 &S.Context.Idents.get("object_getClass"),
626 if (ObjectGetClass)
627 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
629 "object_getClass(")
631 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
632 else
633 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
634 }
635 S.Diag(IV->getLocation(), diag::note_ivar_decl);
636 }
637 }
638}
639
641 // Handle any placeholder expressions which made it here.
642 if (E->hasPlaceholderType()) {
644 if (result.isInvalid()) return ExprError();
645 E = result.get();
646 }
647
648 // C++ [conv.lval]p1:
649 // A glvalue of a non-function, non-array type T can be
650 // converted to a prvalue.
651 if (!E->isGLValue()) return E;
652
653 QualType T = E->getType();
654 assert(!T.isNull() && "r-value conversion on typeless expression?");
655
656 // lvalue-to-rvalue conversion cannot be applied to types that decay to
657 // pointers (i.e. function or array types).
659 return E;
660
661 // We don't want to throw lvalue-to-rvalue casts on top of
662 // expressions of certain types in C++.
663 if (getLangOpts().CPlusPlus) {
664 if (T == Context.OverloadTy || T->isRecordType() ||
665 (T->isDependentType() && !T->isAnyPointerType() &&
667 return E;
668 }
669
670 // The C standard is actually really unclear on this point, and
671 // DR106 tells us what the result should be but not why. It's
672 // generally best to say that void types just doesn't undergo
673 // lvalue-to-rvalue at all. Note that expressions of unqualified
674 // 'void' type are never l-values, but qualified void can be.
675 if (T->isVoidType())
676 return E;
677
678 // OpenCL usually rejects direct accesses to values of 'half' type.
679 if (getLangOpts().OpenCL &&
680 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
681 T->isHalfType()) {
682 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
683 << 0 << T;
684 return ExprError();
685 }
686
688 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
689 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
690 &Context.Idents.get("object_getClass"),
692 if (ObjectGetClass)
693 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
694 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
696 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
697 else
698 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
699 }
700 else if (const ObjCIvarRefExpr *OIRE =
701 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
702 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
703
704 // C++ [conv.lval]p1:
705 // [...] If T is a non-class type, the type of the prvalue is the
706 // cv-unqualified version of T. Otherwise, the type of the
707 // rvalue is T.
708 //
709 // C99 6.3.2.1p2:
710 // If the lvalue has qualified type, the value has the unqualified
711 // version of the type of the lvalue; otherwise, the value has the
712 // type of the lvalue.
713 if (T.hasQualifiers())
714 T = T.getUnqualifiedType();
715
716 // Under the MS ABI, lock down the inheritance model now.
717 if (T->isMemberPointerType() &&
719 (void)isCompleteType(E->getExprLoc(), T);
720
722 if (Res.isInvalid())
723 return Res;
724 E = Res.get();
725
726 // Loading a __weak object implicitly retains the value, so we need a cleanup to
727 // balance that.
730
733
734 // C++ [conv.lval]p3:
735 // If T is cv std::nullptr_t, the result is a null pointer constant.
736 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
737 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
739
740 // C11 6.3.2.1p2:
741 // ... if the lvalue has atomic type, the value has the non-atomic version
742 // of the type of the lvalue ...
743 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
744 T = Atomic->getValueType().getUnqualifiedType();
745 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
746 nullptr, VK_PRValue, FPOptionsOverride());
747 }
748
749 return Res;
750}
751
754 if (Res.isInvalid())
755 return ExprError();
756 Res = DefaultLvalueConversion(Res.get());
757 if (Res.isInvalid())
758 return ExprError();
759 return Res;
760}
761
763 QualType Ty = E->getType();
764 ExprResult Res = E;
765 // Only do implicit cast for a function type, but not for a pointer
766 // to function type.
767 if (Ty->isFunctionType()) {
769 CK_FunctionToPointerDecay);
770 if (Res.isInvalid())
771 return ExprError();
772 }
773 Res = DefaultLvalueConversion(Res.get());
774 if (Res.isInvalid())
775 return ExprError();
776 return Res.get();
777}
778
779/// UsualUnaryConversions - Performs various conversions that are common to most
780/// operators (C99 6.3). The conversions of array and function types are
781/// sometimes suppressed. For example, the array->pointer conversion doesn't
782/// apply if the array is an argument to the sizeof or address (&) operators.
783/// In these instances, this routine should *not* be called.
785 // First, convert to an r-value.
787 if (Res.isInvalid())
788 return ExprError();
789 E = Res.get();
790
791 QualType Ty = E->getType();
792 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
793
794 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
795 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
796 (getLangOpts().getFPEvalMethod() !=
799 switch (EvalMethod) {
800 default:
801 llvm_unreachable("Unrecognized float evaluation method");
802 break;
804 llvm_unreachable("Float evaluation method should be set by now");
805 break;
808 // Widen the expression to double.
809 return Ty->isComplexType()
812 CK_FloatingComplexCast)
813 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
814 break;
817 // Widen the expression to long double.
818 return Ty->isComplexType()
821 CK_FloatingComplexCast)
823 CK_FloatingCast);
824 break;
825 }
826 }
827
828 // Half FP have to be promoted to float unless it is natively supported
829 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
830 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
831
832 // Try to perform integral promotions if the object has a theoretically
833 // promotable type.
835 // C99 6.3.1.1p2:
836 //
837 // The following may be used in an expression wherever an int or
838 // unsigned int may be used:
839 // - an object or expression with an integer type whose integer
840 // conversion rank is less than or equal to the rank of int
841 // and unsigned int.
842 // - A bit-field of type _Bool, int, signed int, or unsigned int.
843 //
844 // If an int can represent all values of the original type, the
845 // value is converted to an int; otherwise, it is converted to an
846 // unsigned int. These are called the integer promotions. All
847 // other types are unchanged by the integer promotions.
848
850 if (!PTy.isNull()) {
851 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
852 return E;
853 }
856 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
857 return E;
858 }
859 }
860 return E;
861}
862
863/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
864/// do not have a prototype. Arguments that have type float or __fp16
865/// are promoted to double. All other argument types are converted by
866/// UsualUnaryConversions().
868 QualType Ty = E->getType();
869 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
870
872 if (Res.isInvalid())
873 return ExprError();
874 E = Res.get();
875
876 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
877 // promote to double.
878 // Note that default argument promotion applies only to float (and
879 // half/fp16); it does not apply to _Float16.
880 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
881 if (BTy && (BTy->getKind() == BuiltinType::Half ||
882 BTy->getKind() == BuiltinType::Float)) {
883 if (getLangOpts().OpenCL &&
884 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
885 if (BTy->getKind() == BuiltinType::Half) {
886 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
887 }
888 } else {
889 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
890 }
891 }
892 if (BTy &&
893 getLangOpts().getExtendIntArgs() ==
898 E = (Ty->isUnsignedIntegerType())
899 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
900 .get()
901 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
903 "Unexpected typesize for LongLongTy");
904 }
905
906 // C++ performs lvalue-to-rvalue conversion as a default argument
907 // promotion, even on class types, but note:
908 // C++11 [conv.lval]p2:
909 // When an lvalue-to-rvalue conversion occurs in an unevaluated
910 // operand or a subexpression thereof the value contained in the
911 // referenced object is not accessed. Otherwise, if the glvalue
912 // has a class type, the conversion copy-initializes a temporary
913 // of type T from the glvalue and the result of the conversion
914 // is a prvalue for the temporary.
915 // FIXME: add some way to gate this entire thing for correctness in
916 // potentially potentially evaluated contexts.
920 E->getExprLoc(), E);
921 if (Temp.isInvalid())
922 return ExprError();
923 E = Temp.get();
924 }
925
926 // C++ [expr.call]p7, per CWG722:
927 // An argument that has (possibly cv-qualified) type std::nullptr_t is
928 // converted to void* ([conv.ptr]).
929 // (This does not apply to C23 nullptr)
931 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
932
933 return E;
934}
935
937 if (Ty->isIncompleteType()) {
938 // C++11 [expr.call]p7:
939 // After these conversions, if the argument does not have arithmetic,
940 // enumeration, pointer, pointer to member, or class type, the program
941 // is ill-formed.
942 //
943 // Since we've already performed null pointer conversion, array-to-pointer
944 // decay and function-to-pointer decay, the only such type in C++ is cv
945 // void. This also handles initializer lists as variadic arguments.
946 if (Ty->isVoidType())
947 return VAK_Invalid;
948
949 if (Ty->isObjCObjectType())
950 return VAK_Invalid;
951 return VAK_Valid;
952 }
953
955 return VAK_Invalid;
956
957 if (Context.getTargetInfo().getTriple().isWasm() &&
959 return VAK_Invalid;
960 }
961
962 if (Ty.isCXX98PODType(Context))
963 return VAK_Valid;
964
965 // C++11 [expr.call]p7:
966 // Passing a potentially-evaluated argument of class type (Clause 9)
967 // having a non-trivial copy constructor, a non-trivial move constructor,
968 // or a non-trivial destructor, with no corresponding parameter,
969 // is conditionally-supported with implementation-defined semantics.
972 if (!Record->hasNonTrivialCopyConstructor() &&
973 !Record->hasNonTrivialMoveConstructor() &&
974 !Record->hasNonTrivialDestructor())
975 return VAK_ValidInCXX11;
976
977 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
978 return VAK_Valid;
979
980 if (Ty->isObjCObjectType())
981 return VAK_Invalid;
982
984 return VAK_Valid;
985
986 if (getLangOpts().MSVCCompat)
987 return VAK_MSVCUndefined;
988
990 return VAK_Valid;
991
992 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
993 // permitted to reject them. We should consider doing so.
994 return VAK_Undefined;
995}
996
998 // Don't allow one to pass an Objective-C interface to a vararg.
999 const QualType &Ty = E->getType();
1000 VarArgKind VAK = isValidVarArgType(Ty);
1001
1002 // Complain about passing non-POD types through varargs.
1003 switch (VAK) {
1004 case VAK_ValidInCXX11:
1006 E->getBeginLoc(), nullptr,
1007 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1008 [[fallthrough]];
1009 case VAK_Valid:
1010 if (Ty->isRecordType()) {
1011 // This is unlikely to be what the user intended. If the class has a
1012 // 'c_str' member function, the user probably meant to call that.
1013 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1014 PDiag(diag::warn_pass_class_arg_to_vararg)
1015 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1016 }
1017 break;
1018
1019 case VAK_Undefined:
1020 case VAK_MSVCUndefined:
1021 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1022 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1023 << getLangOpts().CPlusPlus11 << Ty << CT);
1024 break;
1025
1026 case VAK_Invalid:
1028 Diag(E->getBeginLoc(),
1029 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1030 << Ty << CT;
1031 else if (Ty->isObjCObjectType())
1032 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1033 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1034 << Ty << CT);
1035 else
1036 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1037 << isa<InitListExpr>(E) << Ty << CT;
1038 break;
1039 }
1040}
1041
1043 FunctionDecl *FDecl) {
1044 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1045 // Strip the unbridged-cast placeholder expression off, if applicable.
1046 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1047 (CT == VariadicMethod ||
1048 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1050
1051 // Otherwise, do normal placeholder checking.
1052 } else {
1054 if (ExprRes.isInvalid())
1055 return ExprError();
1056 E = ExprRes.get();
1057 }
1058 }
1059
1061 if (ExprRes.isInvalid())
1062 return ExprError();
1063
1064 // Copy blocks to the heap.
1065 if (ExprRes.get()->getType()->isBlockPointerType())
1066 maybeExtendBlockObject(ExprRes);
1067
1068 E = ExprRes.get();
1069
1070 // Diagnostics regarding non-POD argument types are
1071 // emitted along with format string checking in Sema::CheckFunctionCall().
1073 // Turn this into a trap.
1074 CXXScopeSpec SS;
1075 SourceLocation TemplateKWLoc;
1076 UnqualifiedId Name;
1077 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1078 E->getBeginLoc());
1079 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1080 /*HasTrailingLParen=*/true,
1081 /*IsAddressOfOperand=*/false);
1082 if (TrapFn.isInvalid())
1083 return ExprError();
1084
1085 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1086 E->getEndLoc());
1087 if (Call.isInvalid())
1088 return ExprError();
1089
1090 ExprResult Comma =
1091 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1092 if (Comma.isInvalid())
1093 return ExprError();
1094 return Comma.get();
1095 }
1096
1097 if (!getLangOpts().CPlusPlus &&
1099 diag::err_call_incomplete_argument))
1100 return ExprError();
1101
1102 return E;
1103}
1104
1105/// Convert complex integers to complex floats and real integers to
1106/// real floats as required for complex arithmetic. Helper function of
1107/// UsualArithmeticConversions()
1108///
1109/// \return false if the integer expression is an integer type and is
1110/// successfully converted to the (complex) float type.
1112 ExprResult &ComplexExpr,
1113 QualType IntTy,
1114 QualType ComplexTy,
1115 bool SkipCast) {
1116 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1117 if (SkipCast) return false;
1118 if (IntTy->isIntegerType()) {
1119 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1120 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1121 } else {
1122 assert(IntTy->isComplexIntegerType());
1123 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1124 CK_IntegralComplexToFloatingComplex);
1125 }
1126 return false;
1127}
1128
1129// This handles complex/complex, complex/float, or float/complex.
1130// When both operands are complex, the shorter operand is converted to the
1131// type of the longer, and that is the type of the result. This corresponds
1132// to what is done when combining two real floating-point operands.
1133// The fun begins when size promotion occur across type domains.
1134// From H&S 6.3.4: When one operand is complex and the other is a real
1135// floating-point type, the less precise type is converted, within it's
1136// real or complex domain, to the precision of the other type. For example,
1137// when combining a "long double" with a "double _Complex", the
1138// "double _Complex" is promoted to "long double _Complex".
1140 QualType ShorterType,
1141 QualType LongerType,
1142 bool PromotePrecision) {
1143 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1145 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1146
1147 if (PromotePrecision) {
1148 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1149 Shorter =
1150 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1151 } else {
1152 if (LongerIsComplex)
1153 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1154 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1155 }
1156 }
1157 return Result;
1158}
1159
1160/// Handle arithmetic conversion with complex types. Helper function of
1161/// UsualArithmeticConversions()
1163 ExprResult &RHS, QualType LHSType,
1164 QualType RHSType, bool IsCompAssign) {
1165 // Handle (complex) integer types.
1166 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1167 /*SkipCast=*/false))
1168 return LHSType;
1169 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1170 /*SkipCast=*/IsCompAssign))
1171 return RHSType;
1172
1173 // Compute the rank of the two types, regardless of whether they are complex.
1174 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1175 if (Order < 0)
1176 // Promote the precision of the LHS if not an assignment.
1177 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1178 /*PromotePrecision=*/!IsCompAssign);
1179 // Promote the precision of the RHS unless it is already the same as the LHS.
1180 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1181 /*PromotePrecision=*/Order > 0);
1182}
1183
1184/// Handle arithmetic conversion from integer to float. Helper function
1185/// of UsualArithmeticConversions()
1187 ExprResult &IntExpr,
1188 QualType FloatTy, QualType IntTy,
1189 bool ConvertFloat, bool ConvertInt) {
1190 if (IntTy->isIntegerType()) {
1191 if (ConvertInt)
1192 // Convert intExpr to the lhs floating point type.
1193 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1194 CK_IntegralToFloating);
1195 return FloatTy;
1196 }
1197
1198 // Convert both sides to the appropriate complex float.
1199 assert(IntTy->isComplexIntegerType());
1200 QualType result = S.Context.getComplexType(FloatTy);
1201
1202 // _Complex int -> _Complex float
1203 if (ConvertInt)
1204 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1205 CK_IntegralComplexToFloatingComplex);
1206
1207 // float -> _Complex float
1208 if (ConvertFloat)
1209 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1210 CK_FloatingRealToComplex);
1211
1212 return result;
1213}
1214
1215/// Handle arithmethic conversion with floating point types. Helper
1216/// function of UsualArithmeticConversions()
1218 ExprResult &RHS, QualType LHSType,
1219 QualType RHSType, bool IsCompAssign) {
1220 bool LHSFloat = LHSType->isRealFloatingType();
1221 bool RHSFloat = RHSType->isRealFloatingType();
1222
1223 // N1169 4.1.4: If one of the operands has a floating type and the other
1224 // operand has a fixed-point type, the fixed-point operand
1225 // is converted to the floating type [...]
1226 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1227 if (LHSFloat)
1228 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1229 else if (!IsCompAssign)
1230 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1231 return LHSFloat ? LHSType : RHSType;
1232 }
1233
1234 // If we have two real floating types, convert the smaller operand
1235 // to the bigger result.
1236 if (LHSFloat && RHSFloat) {
1237 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1238 if (order > 0) {
1239 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1240 return LHSType;
1241 }
1242
1243 assert(order < 0 && "illegal float comparison");
1244 if (!IsCompAssign)
1245 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1246 return RHSType;
1247 }
1248
1249 if (LHSFloat) {
1250 // Half FP has to be promoted to float unless it is natively supported
1251 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1252 LHSType = S.Context.FloatTy;
1253
1254 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1255 /*ConvertFloat=*/!IsCompAssign,
1256 /*ConvertInt=*/ true);
1257 }
1258 assert(RHSFloat);
1259 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1260 /*ConvertFloat=*/ true,
1261 /*ConvertInt=*/!IsCompAssign);
1262}
1263
1264/// Diagnose attempts to convert between __float128, __ibm128 and
1265/// long double if there is no support for such conversion.
1266/// Helper function of UsualArithmeticConversions().
1267static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1268 QualType RHSType) {
1269 // No issue if either is not a floating point type.
1270 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1271 return false;
1272
1273 // No issue if both have the same 128-bit float semantics.
1274 auto *LHSComplex = LHSType->getAs<ComplexType>();
1275 auto *RHSComplex = RHSType->getAs<ComplexType>();
1276
1277 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1278 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1279
1280 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1281 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1282
1283 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1284 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1285 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1286 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1287 return false;
1288
1289 return true;
1290}
1291
1292typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1293
1294namespace {
1295/// These helper callbacks are placed in an anonymous namespace to
1296/// permit their use as function template parameters.
1297ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1298 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1299}
1300
1301ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1302 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1303 CK_IntegralComplexCast);
1304}
1305}
1306
1307/// Handle integer arithmetic conversions. Helper function of
1308/// UsualArithmeticConversions()
1309template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1311 ExprResult &RHS, QualType LHSType,
1312 QualType RHSType, bool IsCompAssign) {
1313 // The rules for this case are in C99 6.3.1.8
1314 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1315 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1316 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1317 if (LHSSigned == RHSSigned) {
1318 // Same signedness; use the higher-ranked type
1319 if (order >= 0) {
1320 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1321 return LHSType;
1322 } else if (!IsCompAssign)
1323 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1324 return RHSType;
1325 } else if (order != (LHSSigned ? 1 : -1)) {
1326 // The unsigned type has greater than or equal rank to the
1327 // signed type, so use the unsigned type
1328 if (RHSSigned) {
1329 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1330 return LHSType;
1331 } else if (!IsCompAssign)
1332 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1333 return RHSType;
1334 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1335 // The two types are different widths; if we are here, that
1336 // means the signed type is larger than the unsigned type, so
1337 // use the signed type.
1338 if (LHSSigned) {
1339 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1340 return LHSType;
1341 } else if (!IsCompAssign)
1342 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1343 return RHSType;
1344 } else {
1345 // The signed type is higher-ranked than the unsigned type,
1346 // but isn't actually any bigger (like unsigned int and long
1347 // on most 32-bit systems). Use the unsigned type corresponding
1348 // to the signed type.
1349 QualType result =
1350 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1351 RHS = (*doRHSCast)(S, RHS.get(), result);
1352 if (!IsCompAssign)
1353 LHS = (*doLHSCast)(S, LHS.get(), result);
1354 return result;
1355 }
1356}
1357
1358/// Handle conversions with GCC complex int extension. Helper function
1359/// of UsualArithmeticConversions()
1361 ExprResult &RHS, QualType LHSType,
1362 QualType RHSType,
1363 bool IsCompAssign) {
1364 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1365 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1366
1367 if (LHSComplexInt && RHSComplexInt) {
1368 QualType LHSEltType = LHSComplexInt->getElementType();
1369 QualType RHSEltType = RHSComplexInt->getElementType();
1370 QualType ScalarType =
1371 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1372 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1373
1374 return S.Context.getComplexType(ScalarType);
1375 }
1376
1377 if (LHSComplexInt) {
1378 QualType LHSEltType = LHSComplexInt->getElementType();
1379 QualType ScalarType =
1380 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1381 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1383 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1384 CK_IntegralRealToComplex);
1385
1386 return ComplexType;
1387 }
1388
1389 assert(RHSComplexInt);
1390
1391 QualType RHSEltType = RHSComplexInt->getElementType();
1392 QualType ScalarType =
1393 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1394 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1396
1397 if (!IsCompAssign)
1398 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1399 CK_IntegralRealToComplex);
1400 return ComplexType;
1401}
1402
1403/// Return the rank of a given fixed point or integer type. The value itself
1404/// doesn't matter, but the values must be increasing with proper increasing
1405/// rank as described in N1169 4.1.1.
1406static unsigned GetFixedPointRank(QualType Ty) {
1407 const auto *BTy = Ty->getAs<BuiltinType>();
1408 assert(BTy && "Expected a builtin type.");
1409
1410 switch (BTy->getKind()) {
1411 case BuiltinType::ShortFract:
1412 case BuiltinType::UShortFract:
1413 case BuiltinType::SatShortFract:
1414 case BuiltinType::SatUShortFract:
1415 return 1;
1416 case BuiltinType::Fract:
1417 case BuiltinType::UFract:
1418 case BuiltinType::SatFract:
1419 case BuiltinType::SatUFract:
1420 return 2;
1421 case BuiltinType::LongFract:
1422 case BuiltinType::ULongFract:
1423 case BuiltinType::SatLongFract:
1424 case BuiltinType::SatULongFract:
1425 return 3;
1426 case BuiltinType::ShortAccum:
1427 case BuiltinType::UShortAccum:
1428 case BuiltinType::SatShortAccum:
1429 case BuiltinType::SatUShortAccum:
1430 return 4;
1431 case BuiltinType::Accum:
1432 case BuiltinType::UAccum:
1433 case BuiltinType::SatAccum:
1434 case BuiltinType::SatUAccum:
1435 return 5;
1436 case BuiltinType::LongAccum:
1437 case BuiltinType::ULongAccum:
1438 case BuiltinType::SatLongAccum:
1439 case BuiltinType::SatULongAccum:
1440 return 6;
1441 default:
1442 if (BTy->isInteger())
1443 return 0;
1444 llvm_unreachable("Unexpected fixed point or integer type");
1445 }
1446}
1447
1448/// handleFixedPointConversion - Fixed point operations between fixed
1449/// point types and integers or other fixed point types do not fall under
1450/// usual arithmetic conversion since these conversions could result in loss
1451/// of precsision (N1169 4.1.4). These operations should be calculated with
1452/// the full precision of their result type (N1169 4.1.6.2.1).
1454 QualType RHSTy) {
1455 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1456 "Expected at least one of the operands to be a fixed point type");
1457 assert((LHSTy->isFixedPointOrIntegerType() ||
1458 RHSTy->isFixedPointOrIntegerType()) &&
1459 "Special fixed point arithmetic operation conversions are only "
1460 "applied to ints or other fixed point types");
1461
1462 // If one operand has signed fixed-point type and the other operand has
1463 // unsigned fixed-point type, then the unsigned fixed-point operand is
1464 // converted to its corresponding signed fixed-point type and the resulting
1465 // type is the type of the converted operand.
1466 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1468 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1470
1471 // The result type is the type with the highest rank, whereby a fixed-point
1472 // conversion rank is always greater than an integer conversion rank; if the
1473 // type of either of the operands is a saturating fixedpoint type, the result
1474 // type shall be the saturating fixed-point type corresponding to the type
1475 // with the highest rank; the resulting value is converted (taking into
1476 // account rounding and overflow) to the precision of the resulting type.
1477 // Same ranks between signed and unsigned types are resolved earlier, so both
1478 // types are either signed or both unsigned at this point.
1479 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1480 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1481
1482 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1483
1485 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1486
1487 return ResultTy;
1488}
1489
1490/// Check that the usual arithmetic conversions can be performed on this pair of
1491/// expressions that might be of enumeration type.
1494 Sema::ArithConvKind ACK) {
1495 // C++2a [expr.arith.conv]p1:
1496 // If one operand is of enumeration type and the other operand is of a
1497 // different enumeration type or a floating-point type, this behavior is
1498 // deprecated ([depr.arith.conv.enum]).
1499 //
1500 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1501 // Eventually we will presumably reject these cases (in C++23 onwards?).
1503 R = RHS->getEnumCoercedType(S.Context);
1504 bool LEnum = L->isUnscopedEnumerationType(),
1505 REnum = R->isUnscopedEnumerationType();
1506 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1507 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1508 (REnum && L->isFloatingType())) {
1509 S.Diag(Loc, S.getLangOpts().CPlusPlus26
1510 ? diag::err_arith_conv_enum_float_cxx26
1511 : S.getLangOpts().CPlusPlus20
1512 ? diag::warn_arith_conv_enum_float_cxx20
1513 : diag::warn_arith_conv_enum_float)
1514 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1515 << L << R;
1516 } else if (!IsCompAssign && LEnum && REnum &&
1518 unsigned DiagID;
1519 // In C++ 26, usual arithmetic conversions between 2 different enum types
1520 // are ill-formed.
1521 if (S.getLangOpts().CPlusPlus26)
1522 DiagID = diag::err_conv_mixed_enum_types_cxx26;
1523 else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1524 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1525 // If either enumeration type is unnamed, it's less likely that the
1526 // user cares about this, but this situation is still deprecated in
1527 // C++2a. Use a different warning group.
1528 DiagID = S.getLangOpts().CPlusPlus20
1529 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1530 : diag::warn_arith_conv_mixed_anon_enum_types;
1531 } else if (ACK == Sema::ACK_Conditional) {
1532 // Conditional expressions are separated out because they have
1533 // historically had a different warning flag.
1534 DiagID = S.getLangOpts().CPlusPlus20
1535 ? diag::warn_conditional_mixed_enum_types_cxx20
1536 : diag::warn_conditional_mixed_enum_types;
1537 } else if (ACK == Sema::ACK_Comparison) {
1538 // Comparison expressions are separated out because they have
1539 // historically had a different warning flag.
1540 DiagID = S.getLangOpts().CPlusPlus20
1541 ? diag::warn_comparison_mixed_enum_types_cxx20
1542 : diag::warn_comparison_mixed_enum_types;
1543 } else {
1544 DiagID = S.getLangOpts().CPlusPlus20
1545 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1546 : diag::warn_arith_conv_mixed_enum_types;
1547 }
1548 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1549 << (int)ACK << L << R;
1550 }
1551}
1552
1553/// UsualArithmeticConversions - Performs various conversions that are common to
1554/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1555/// routine returns the first non-arithmetic type found. The client is
1556/// responsible for emitting appropriate error diagnostics.
1559 ArithConvKind ACK) {
1560 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1561
1562 if (ACK != ACK_CompAssign) {
1563 LHS = UsualUnaryConversions(LHS.get());
1564 if (LHS.isInvalid())
1565 return QualType();
1566 }
1567
1568 RHS = UsualUnaryConversions(RHS.get());
1569 if (RHS.isInvalid())
1570 return QualType();
1571
1572 // For conversion purposes, we ignore any qualifiers.
1573 // For example, "const float" and "float" are equivalent.
1574 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1575 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1576
1577 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1578 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1579 LHSType = AtomicLHS->getValueType();
1580
1581 // If both types are identical, no conversion is needed.
1582 if (Context.hasSameType(LHSType, RHSType))
1583 return Context.getCommonSugaredType(LHSType, RHSType);
1584
1585 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1586 // The caller can deal with this (e.g. pointer + int).
1587 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1588 return QualType();
1589
1590 // Apply unary and bitfield promotions to the LHS's type.
1591 QualType LHSUnpromotedType = LHSType;
1592 if (Context.isPromotableIntegerType(LHSType))
1593 LHSType = Context.getPromotedIntegerType(LHSType);
1594 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1595 if (!LHSBitfieldPromoteTy.isNull())
1596 LHSType = LHSBitfieldPromoteTy;
1597 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1598 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1599
1600 // If both types are identical, no conversion is needed.
1601 if (Context.hasSameType(LHSType, RHSType))
1602 return Context.getCommonSugaredType(LHSType, RHSType);
1603
1604 // At this point, we have two different arithmetic types.
1605
1606 // Diagnose attempts to convert between __ibm128, __float128 and long double
1607 // where such conversions currently can't be handled.
1608 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1609 return QualType();
1610
1611 // Handle complex types first (C99 6.3.1.8p1).
1612 if (LHSType->isComplexType() || RHSType->isComplexType())
1613 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1614 ACK == ACK_CompAssign);
1615
1616 // Now handle "real" floating types (i.e. float, double, long double).
1617 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1618 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1619 ACK == ACK_CompAssign);
1620
1621 // Handle GCC complex int extension.
1622 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1623 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1624 ACK == ACK_CompAssign);
1625
1626 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1627 return handleFixedPointConversion(*this, LHSType, RHSType);
1628
1629 // Finally, we have two differing integer types.
1630 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1631 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1632}
1633
1634//===----------------------------------------------------------------------===//
1635// Semantic Analysis for various Expression Types
1636//===----------------------------------------------------------------------===//
1637
1638
1640 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1641 bool PredicateIsExpr, void *ControllingExprOrType,
1642 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1643 unsigned NumAssocs = ArgTypes.size();
1644 assert(NumAssocs == ArgExprs.size());
1645
1646 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1647 for (unsigned i = 0; i < NumAssocs; ++i) {
1648 if (ArgTypes[i])
1649 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1650 else
1651 Types[i] = nullptr;
1652 }
1653
1654 // If we have a controlling type, we need to convert it from a parsed type
1655 // into a semantic type and then pass that along.
1656 if (!PredicateIsExpr) {
1657 TypeSourceInfo *ControllingType;
1658 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1659 &ControllingType);
1660 assert(ControllingType && "couldn't get the type out of the parser");
1661 ControllingExprOrType = ControllingType;
1662 }
1663
1665 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1666 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1667 delete [] Types;
1668 return ER;
1669}
1670
1672 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1673 bool PredicateIsExpr, void *ControllingExprOrType,
1675 unsigned NumAssocs = Types.size();
1676 assert(NumAssocs == Exprs.size());
1677 assert(ControllingExprOrType &&
1678 "Must have either a controlling expression or a controlling type");
1679
1680 Expr *ControllingExpr = nullptr;
1681 TypeSourceInfo *ControllingType = nullptr;
1682 if (PredicateIsExpr) {
1683 // Decay and strip qualifiers for the controlling expression type, and
1684 // handle placeholder type replacement. See committee discussion from WG14
1685 // DR423.
1689 reinterpret_cast<Expr *>(ControllingExprOrType));
1690 if (R.isInvalid())
1691 return ExprError();
1692 ControllingExpr = R.get();
1693 } else {
1694 // The extension form uses the type directly rather than converting it.
1695 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1696 if (!ControllingType)
1697 return ExprError();
1698 }
1699
1700 bool TypeErrorFound = false,
1701 IsResultDependent = ControllingExpr
1702 ? ControllingExpr->isTypeDependent()
1703 : ControllingType->getType()->isDependentType(),
1704 ContainsUnexpandedParameterPack =
1705 ControllingExpr
1706 ? ControllingExpr->containsUnexpandedParameterPack()
1707 : ControllingType->getType()->containsUnexpandedParameterPack();
1708
1709 // The controlling expression is an unevaluated operand, so side effects are
1710 // likely unintended.
1711 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1712 ControllingExpr->HasSideEffects(Context, false))
1713 Diag(ControllingExpr->getExprLoc(),
1714 diag::warn_side_effects_unevaluated_context);
1715
1716 for (unsigned i = 0; i < NumAssocs; ++i) {
1717 if (Exprs[i]->containsUnexpandedParameterPack())
1718 ContainsUnexpandedParameterPack = true;
1719
1720 if (Types[i]) {
1721 if (Types[i]->getType()->containsUnexpandedParameterPack())
1722 ContainsUnexpandedParameterPack = true;
1723
1724 if (Types[i]->getType()->isDependentType()) {
1725 IsResultDependent = true;
1726 } else {
1727 // We relax the restriction on use of incomplete types and non-object
1728 // types with the type-based extension of _Generic. Allowing incomplete
1729 // objects means those can be used as "tags" for a type-safe way to map
1730 // to a value. Similarly, matching on function types rather than
1731 // function pointer types can be useful. However, the restriction on VM
1732 // types makes sense to retain as there are open questions about how
1733 // the selection can be made at compile time.
1734 //
1735 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1736 // complete object type other than a variably modified type."
1737 unsigned D = 0;
1738 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1739 D = diag::err_assoc_type_incomplete;
1740 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1741 D = diag::err_assoc_type_nonobject;
1742 else if (Types[i]->getType()->isVariablyModifiedType())
1743 D = diag::err_assoc_type_variably_modified;
1744 else if (ControllingExpr) {
1745 // Because the controlling expression undergoes lvalue conversion,
1746 // array conversion, and function conversion, an association which is
1747 // of array type, function type, or is qualified can never be
1748 // reached. We will warn about this so users are less surprised by
1749 // the unreachable association. However, we don't have to handle
1750 // function types; that's not an object type, so it's handled above.
1751 //
1752 // The logic is somewhat different for C++ because C++ has different
1753 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1754 // If T is a non-class type, the type of the prvalue is the cv-
1755 // unqualified version of T. Otherwise, the type of the prvalue is T.
1756 // The result of these rules is that all qualified types in an
1757 // association in C are unreachable, and in C++, only qualified non-
1758 // class types are unreachable.
1759 //
1760 // NB: this does not apply when the first operand is a type rather
1761 // than an expression, because the type form does not undergo
1762 // conversion.
1763 unsigned Reason = 0;
1764 QualType QT = Types[i]->getType();
1765 if (QT->isArrayType())
1766 Reason = 1;
1767 else if (QT.hasQualifiers() &&
1768 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1769 Reason = 2;
1770
1771 if (Reason)
1772 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1773 diag::warn_unreachable_association)
1774 << QT << (Reason - 1);
1775 }
1776
1777 if (D != 0) {
1778 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1779 << Types[i]->getTypeLoc().getSourceRange()
1780 << Types[i]->getType();
1781 TypeErrorFound = true;
1782 }
1783
1784 // C11 6.5.1.1p2 "No two generic associations in the same generic
1785 // selection shall specify compatible types."
1786 for (unsigned j = i+1; j < NumAssocs; ++j)
1787 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1788 Context.typesAreCompatible(Types[i]->getType(),
1789 Types[j]->getType())) {
1790 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1791 diag::err_assoc_compatible_types)
1792 << Types[j]->getTypeLoc().getSourceRange()
1793 << Types[j]->getType()
1794 << Types[i]->getType();
1795 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1796 diag::note_compat_assoc)
1797 << Types[i]->getTypeLoc().getSourceRange()
1798 << Types[i]->getType();
1799 TypeErrorFound = true;
1800 }
1801 }
1802 }
1803 }
1804 if (TypeErrorFound)
1805 return ExprError();
1806
1807 // If we determined that the generic selection is result-dependent, don't
1808 // try to compute the result expression.
1809 if (IsResultDependent) {
1810 if (ControllingExpr)
1811 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1812 Types, Exprs, DefaultLoc, RParenLoc,
1813 ContainsUnexpandedParameterPack);
1814 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1815 Exprs, DefaultLoc, RParenLoc,
1816 ContainsUnexpandedParameterPack);
1817 }
1818
1819 SmallVector<unsigned, 1> CompatIndices;
1820 unsigned DefaultIndex = -1U;
1821 // Look at the canonical type of the controlling expression in case it was a
1822 // deduced type like __auto_type. However, when issuing diagnostics, use the
1823 // type the user wrote in source rather than the canonical one.
1824 for (unsigned i = 0; i < NumAssocs; ++i) {
1825 if (!Types[i])
1826 DefaultIndex = i;
1827 else if (ControllingExpr &&
1829 ControllingExpr->getType().getCanonicalType(),
1830 Types[i]->getType()))
1831 CompatIndices.push_back(i);
1832 else if (ControllingType &&
1834 ControllingType->getType().getCanonicalType(),
1835 Types[i]->getType()))
1836 CompatIndices.push_back(i);
1837 }
1838
1839 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1840 TypeSourceInfo *ControllingType) {
1841 // We strip parens here because the controlling expression is typically
1842 // parenthesized in macro definitions.
1843 if (ControllingExpr)
1844 ControllingExpr = ControllingExpr->IgnoreParens();
1845
1846 SourceRange SR = ControllingExpr
1847 ? ControllingExpr->getSourceRange()
1848 : ControllingType->getTypeLoc().getSourceRange();
1849 QualType QT = ControllingExpr ? ControllingExpr->getType()
1850 : ControllingType->getType();
1851
1852 return std::make_pair(SR, QT);
1853 };
1854
1855 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1856 // type compatible with at most one of the types named in its generic
1857 // association list."
1858 if (CompatIndices.size() > 1) {
1859 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1860 SourceRange SR = P.first;
1861 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1862 << SR << P.second << (unsigned)CompatIndices.size();
1863 for (unsigned I : CompatIndices) {
1864 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1865 diag::note_compat_assoc)
1866 << Types[I]->getTypeLoc().getSourceRange()
1867 << Types[I]->getType();
1868 }
1869 return ExprError();
1870 }
1871
1872 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1873 // its controlling expression shall have type compatible with exactly one of
1874 // the types named in its generic association list."
1875 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1876 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1877 SourceRange SR = P.first;
1878 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1879 return ExprError();
1880 }
1881
1882 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1883 // type name that is compatible with the type of the controlling expression,
1884 // then the result expression of the generic selection is the expression
1885 // in that generic association. Otherwise, the result expression of the
1886 // generic selection is the expression in the default generic association."
1887 unsigned ResultIndex =
1888 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1889
1890 if (ControllingExpr) {
1892 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1893 ContainsUnexpandedParameterPack, ResultIndex);
1894 }
1896 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1897 ContainsUnexpandedParameterPack, ResultIndex);
1898}
1899
1901 switch (Kind) {
1902 default:
1903 llvm_unreachable("unexpected TokenKind");
1904 case tok::kw___func__:
1905 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
1906 case tok::kw___FUNCTION__:
1908 case tok::kw___FUNCDNAME__:
1909 return PredefinedIdentKind::FuncDName; // [MS]
1910 case tok::kw___FUNCSIG__:
1911 return PredefinedIdentKind::FuncSig; // [MS]
1912 case tok::kw_L__FUNCTION__:
1913 return PredefinedIdentKind::LFunction; // [MS]
1914 case tok::kw_L__FUNCSIG__:
1915 return PredefinedIdentKind::LFuncSig; // [MS]
1916 case tok::kw___PRETTY_FUNCTION__:
1918 }
1919}
1920
1921/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1922/// to determine the value of a PredefinedExpr. This can be either a
1923/// block, lambda, captured statement, function, otherwise a nullptr.
1925 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))
1926 DC = DC->getParent();
1927 return cast_or_null<Decl>(DC);
1928}
1929
1930/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1931/// location of the token and the offset of the ud-suffix within it.
1933 unsigned Offset) {
1934 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1935 S.getLangOpts());
1936}
1937
1938/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1939/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1941 IdentifierInfo *UDSuffix,
1942 SourceLocation UDSuffixLoc,
1943 ArrayRef<Expr*> Args,
1944 SourceLocation LitEndLoc) {
1945 assert(Args.size() <= 2 && "too many arguments for literal operator");
1946
1947 QualType ArgTy[2];
1948 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1949 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1950 if (ArgTy[ArgIdx]->isArrayType())
1951 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1952 }
1953
1954 DeclarationName OpName =
1956 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1957 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1958
1959 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1960 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1961 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1962 /*AllowStringTemplatePack*/ false,
1963 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1964 return ExprError();
1965
1966 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1967}
1968
1970 // StringToks needs backing storage as it doesn't hold array elements itself
1971 std::vector<Token> ExpandedToks;
1972 if (getLangOpts().MicrosoftExt)
1973 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
1974
1975 StringLiteralParser Literal(StringToks, PP,
1977 if (Literal.hadError)
1978 return ExprError();
1979
1980 SmallVector<SourceLocation, 4> StringTokLocs;
1981 for (const Token &Tok : StringToks)
1982 StringTokLocs.push_back(Tok.getLocation());
1983
1985 Context, Literal.GetString(), StringLiteralKind::Unevaluated, false, {},
1986 &StringTokLocs[0], StringTokLocs.size());
1987
1988 if (!Literal.getUDSuffix().empty()) {
1989 SourceLocation UDSuffixLoc =
1990 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1991 Literal.getUDSuffixOffset());
1992 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1993 }
1994
1995 return Lit;
1996}
1997
1998std::vector<Token>
2000 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2001 // local macros that expand to string literals that may be concatenated.
2002 // These macros are expanded here (in Sema), because StringLiteralParser
2003 // (in Lex) doesn't know the enclosing function (because it hasn't been
2004 // parsed yet).
2005 assert(getLangOpts().MicrosoftExt);
2006
2007 // Note: Although function local macros are defined only inside functions,
2008 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2009 // expansion of macros into empty string literals without additional checks.
2010 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2011 if (!CurrentDecl)
2012 CurrentDecl = Context.getTranslationUnitDecl();
2013
2014 std::vector<Token> ExpandedToks;
2015 ExpandedToks.reserve(Toks.size());
2016 for (const Token &Tok : Toks) {
2017 if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
2018 assert(tok::isStringLiteral(Tok.getKind()));
2019 ExpandedToks.emplace_back(Tok);
2020 continue;
2021 }
2022 if (isa<TranslationUnitDecl>(CurrentDecl))
2023 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2024 // Stringify predefined expression
2025 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2026 << Tok.getKind();
2027 SmallString<64> Str;
2028 llvm::raw_svector_ostream OS(Str);
2029 Token &Exp = ExpandedToks.emplace_back();
2030 Exp.startToken();
2031 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2032 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2033 OS << 'L';
2034 Exp.setKind(tok::wide_string_literal);
2035 } else {
2036 Exp.setKind(tok::string_literal);
2037 }
2038 OS << '"'
2040 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2041 << '"';
2042 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2043 }
2044 return ExpandedToks;
2045}
2046
2049 assert(!StringToks.empty() && "Must have at least one string!");
2050
2051 // StringToks needs backing storage as it doesn't hold array elements itself
2052 std::vector<Token> ExpandedToks;
2053 if (getLangOpts().MicrosoftExt)
2054 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2055
2056 StringLiteralParser Literal(StringToks, PP);
2057 if (Literal.hadError)
2058 return ExprError();
2059
2060 SmallVector<SourceLocation, 4> StringTokLocs;
2061 for (const Token &Tok : StringToks)
2062 StringTokLocs.push_back(Tok.getLocation());
2063
2064 QualType CharTy = Context.CharTy;
2066 if (Literal.isWide()) {
2067 CharTy = Context.getWideCharType();
2069 } else if (Literal.isUTF8()) {
2070 if (getLangOpts().Char8)
2071 CharTy = Context.Char8Ty;
2072 else if (getLangOpts().C23)
2073 CharTy = Context.UnsignedCharTy;
2075 } else if (Literal.isUTF16()) {
2076 CharTy = Context.Char16Ty;
2078 } else if (Literal.isUTF32()) {
2079 CharTy = Context.Char32Ty;
2081 } else if (Literal.isPascal()) {
2082 CharTy = Context.UnsignedCharTy;
2083 }
2084
2085 // Warn on u8 string literals before C++20 and C23, whose type
2086 // was an array of char before but becomes an array of char8_t.
2087 // In C++20, it cannot be used where a pointer to char is expected.
2088 // In C23, it might have an unexpected value if char was signed.
2089 if (Kind == StringLiteralKind::UTF8 &&
2091 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2092 : !getLangOpts().C23)) {
2093 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2094 ? diag::warn_cxx20_compat_utf8_string
2095 : diag::warn_c23_compat_utf8_string);
2096
2097 // Create removals for all 'u8' prefixes in the string literal(s). This
2098 // ensures C++20/C23 compatibility (but may change the program behavior when
2099 // built by non-Clang compilers for which the execution character set is
2100 // not always UTF-8).
2101 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2102 SourceLocation RemovalDiagLoc;
2103 for (const Token &Tok : StringToks) {
2104 if (Tok.getKind() == tok::utf8_string_literal) {
2105 if (RemovalDiagLoc.isInvalid())
2106 RemovalDiagLoc = Tok.getLocation();
2108 Tok.getLocation(),
2109 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2111 }
2112 }
2113 Diag(RemovalDiagLoc, RemovalDiag);
2114 }
2115
2116 QualType StrTy =
2117 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2118
2119 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2120 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2121 Kind, Literal.Pascal, StrTy,
2122 &StringTokLocs[0],
2123 StringTokLocs.size());
2124 if (Literal.getUDSuffix().empty())
2125 return Lit;
2126
2127 // We're building a user-defined literal.
2128 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2129 SourceLocation UDSuffixLoc =
2130 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2131 Literal.getUDSuffixOffset());
2132
2133 // Make sure we're allowed user-defined literals here.
2134 if (!UDLScope)
2135 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2136
2137 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2138 // operator "" X (str, len)
2139 QualType SizeType = Context.getSizeType();
2140
2141 DeclarationName OpName =
2143 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2144 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2145
2146 QualType ArgTy[] = {
2147 Context.getArrayDecayedType(StrTy), SizeType
2148 };
2149
2150 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2151 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2152 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2153 /*AllowStringTemplatePack*/ true,
2154 /*DiagnoseMissing*/ true, Lit)) {
2155
2156 case LOLR_Cooked: {
2157 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2158 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2159 StringTokLocs[0]);
2160 Expr *Args[] = { Lit, LenArg };
2161
2162 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2163 }
2164
2165 case LOLR_Template: {
2166 TemplateArgumentListInfo ExplicitArgs;
2167 TemplateArgument Arg(Lit);
2168 TemplateArgumentLocInfo ArgInfo(Lit);
2169 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2170 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2171 &ExplicitArgs);
2172 }
2173
2175 TemplateArgumentListInfo ExplicitArgs;
2176
2177 unsigned CharBits = Context.getIntWidth(CharTy);
2178 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2179 llvm::APSInt Value(CharBits, CharIsUnsigned);
2180
2181 TemplateArgument TypeArg(CharTy);
2183 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2184
2185 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2186 Value = Lit->getCodeUnit(I);
2187 TemplateArgument Arg(Context, Value, CharTy);
2189 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2190 }
2191 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2192 &ExplicitArgs);
2193 }
2194 case LOLR_Raw:
2196 llvm_unreachable("unexpected literal operator lookup result");
2197 case LOLR_Error:
2198 return ExprError();
2199 }
2200 llvm_unreachable("unexpected literal operator lookup result");
2201}
2202
2206 const CXXScopeSpec *SS) {
2207 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2208 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2209}
2210
2213 const DeclarationNameInfo &NameInfo,
2214 const CXXScopeSpec *SS, NamedDecl *FoundD,
2215 SourceLocation TemplateKWLoc,
2216 const TemplateArgumentListInfo *TemplateArgs) {
2219 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2220 TemplateArgs);
2221}
2222
2223// CUDA/HIP: Check whether a captured reference variable is referencing a
2224// host variable in a device or host device lambda.
2226 VarDecl *VD) {
2227 if (!S.getLangOpts().CUDA || !VD->hasInit())
2228 return false;
2229 assert(VD->getType()->isReferenceType());
2230
2231 // Check whether the reference variable is referencing a host variable.
2232 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2233 if (!DRE)
2234 return false;
2235 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2236 if (!Referee || !Referee->hasGlobalStorage() ||
2237 Referee->hasAttr<CUDADeviceAttr>())
2238 return false;
2239
2240 // Check whether the current function is a device or host device lambda.
2241 // Check whether the reference variable is a capture by getDeclContext()
2242 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2243 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2244 if (MD && MD->getParent()->isLambda() &&
2245 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2246 VD->getDeclContext() != MD)
2247 return true;
2248
2249 return false;
2250}
2251
2253 // A declaration named in an unevaluated operand never constitutes an odr-use.
2255 return NOUR_Unevaluated;
2256
2257 // C++2a [basic.def.odr]p4:
2258 // A variable x whose name appears as a potentially-evaluated expression e
2259 // is odr-used by e unless [...] x is a reference that is usable in
2260 // constant expressions.
2261 // CUDA/HIP:
2262 // If a reference variable referencing a host variable is captured in a
2263 // device or host device lambda, the value of the referee must be copied
2264 // to the capture and the reference variable must be treated as odr-use
2265 // since the value of the referee is not known at compile time and must
2266 // be loaded from the captured.
2267 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2268 if (VD->getType()->isReferenceType() &&
2269 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2271 VD->isUsableInConstantExpressions(Context))
2272 return NOUR_Constant;
2273 }
2274
2275 // All remaining non-variable cases constitute an odr-use. For variables, we
2276 // need to wait and see how the expression is used.
2277 return NOUR_None;
2278}
2279
2282 const DeclarationNameInfo &NameInfo,
2283 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2284 SourceLocation TemplateKWLoc,
2285 const TemplateArgumentListInfo *TemplateArgs) {
2286 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2287 NeedToCaptureVariable(D, NameInfo.getLoc());
2288
2290 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2291 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2293
2294 // C++ [except.spec]p17:
2295 // An exception-specification is considered to be needed when:
2296 // - in an expression, the function is the unique lookup result or
2297 // the selected member of a set of overloaded functions.
2298 //
2299 // We delay doing this until after we've built the function reference and
2300 // marked it as used so that:
2301 // a) if the function is defaulted, we get errors from defining it before /
2302 // instead of errors from computing its exception specification, and
2303 // b) if the function is a defaulted comparison, we can use the body we
2304 // build when defining it as input to the exception specification
2305 // computation rather than computing a new body.
2306 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2307 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2308 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2310 }
2311 }
2312
2313 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2315 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2317
2318 const auto *FD = dyn_cast<FieldDecl>(D);
2319 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2320 FD = IFD->getAnonField();
2321 if (FD) {
2322 UnusedPrivateFields.remove(FD);
2323 // Just in case we're building an illegal pointer-to-member.
2324 if (FD->isBitField())
2326 }
2327
2328 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2329 // designates a bit-field.
2330 if (const auto *BD = dyn_cast<BindingDecl>(D))
2331 if (const auto *BE = BD->getBinding())
2332 E->setObjectKind(BE->getObjectKind());
2333
2334 return E;
2335}
2336
2337void
2340 DeclarationNameInfo &NameInfo,
2341 const TemplateArgumentListInfo *&TemplateArgs) {
2342 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2343 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2344 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2345
2346 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2347 Id.TemplateId->NumArgs);
2348 translateTemplateArguments(TemplateArgsPtr, Buffer);
2349
2350 TemplateName TName = Id.TemplateId->Template.get();
2351 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2352 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2353 TemplateArgs = &Buffer;
2354 } else {
2355 NameInfo = GetNameFromUnqualifiedId(Id);
2356 TemplateArgs = nullptr;
2357 }
2358}
2359
2361 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2363 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2364 DeclContext *Ctx =
2365 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2366 if (!TC) {
2367 // Emit a special diagnostic for failed member lookups.
2368 // FIXME: computing the declaration context might fail here (?)
2369 if (Ctx)
2370 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2371 << SS.getRange();
2372 else
2373 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2374 return;
2375 }
2376
2377 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2378 bool DroppedSpecifier =
2379 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2380 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2381 ? diag::note_implicit_param_decl
2382 : diag::note_previous_decl;
2383 if (!Ctx)
2384 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2385 SemaRef.PDiag(NoteID));
2386 else
2387 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2388 << Typo << Ctx << DroppedSpecifier
2389 << SS.getRange(),
2390 SemaRef.PDiag(NoteID));
2391}
2392
2394 // During a default argument instantiation the CurContext points
2395 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2396 // function parameter list, hence add an explicit check.
2397 bool isDefaultArgument =
2398 !CodeSynthesisContexts.empty() &&
2399 CodeSynthesisContexts.back().Kind ==
2401 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2402 bool isInstance = CurMethod && CurMethod->isInstance() &&
2403 R.getNamingClass() == CurMethod->getParent() &&
2404 !isDefaultArgument;
2405
2406 // There are two ways we can find a class-scope declaration during template
2407 // instantiation that we did not find in the template definition: if it is a
2408 // member of a dependent base class, or if it is declared after the point of
2409 // use in the same class. Distinguish these by comparing the class in which
2410 // the member was found to the naming class of the lookup.
2411 unsigned DiagID = diag::err_found_in_dependent_base;
2412 unsigned NoteID = diag::note_member_declared_at;
2414 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2415 : diag::err_found_later_in_class;
2416 } else if (getLangOpts().MSVCCompat) {
2417 DiagID = diag::ext_found_in_dependent_base;
2418 NoteID = diag::note_dependent_member_use;
2419 }
2420
2421 if (isInstance) {
2422 // Give a code modification hint to insert 'this->'.
2423 Diag(R.getNameLoc(), DiagID)
2424 << R.getLookupName()
2425 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2427 } else {
2428 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2429 // they're not shadowed).
2430 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2431 }
2432
2433 for (const NamedDecl *D : R)
2434 Diag(D->getLocation(), NoteID);
2435
2436 // Return true if we are inside a default argument instantiation
2437 // and the found name refers to an instance member function, otherwise
2438 // the caller will try to create an implicit member call and this is wrong
2439 // for default arguments.
2440 //
2441 // FIXME: Is this special case necessary? We could allow the caller to
2442 // diagnose this.
2443 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2444 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2445 return true;
2446 }
2447
2448 // Tell the callee to try to recover.
2449 return false;
2450}
2451
2454 TemplateArgumentListInfo *ExplicitTemplateArgs,
2455 ArrayRef<Expr *> Args, DeclContext *LookupCtx,
2456 TypoExpr **Out) {
2457 DeclarationName Name = R.getLookupName();
2458
2459 unsigned diagnostic = diag::err_undeclared_var_use;
2460 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2461 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2462 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2463 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2464 diagnostic = diag::err_undeclared_use;
2465 diagnostic_suggest = diag::err_undeclared_use_suggest;
2466 }
2467
2468 // If the original lookup was an unqualified lookup, fake an
2469 // unqualified lookup. This is useful when (for example) the
2470 // original lookup would not have found something because it was a
2471 // dependent name.
2472 DeclContext *DC =
2473 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2474 while (DC) {
2475 if (isa<CXXRecordDecl>(DC)) {
2476 if (ExplicitTemplateArgs) {
2478 R, S, SS, Context.getRecordType(cast<CXXRecordDecl>(DC)),
2479 /*EnteringContext*/ false, TemplateNameIsRequired,
2480 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2481 return true;
2482 } else {
2483 LookupQualifiedName(R, DC);
2484 }
2485
2486 if (!R.empty()) {
2487 // Don't give errors about ambiguities in this lookup.
2489
2490 // If there's a best viable function among the results, only mention
2491 // that one in the notes.
2492 OverloadCandidateSet Candidates(R.getNameLoc(),
2494 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2496 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2497 OR_Success) {
2498 R.clear();
2499 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2500 R.resolveKind();
2501 }
2502
2504 }
2505
2506 R.clear();
2507 }
2508
2509 DC = DC->getLookupParent();
2510 }
2511
2512 // We didn't find anything, so try to correct for a typo.
2513 TypoCorrection Corrected;
2514 if (S && Out) {
2515 SourceLocation TypoLoc = R.getNameLoc();
2516 assert(!ExplicitTemplateArgs &&
2517 "Diagnosing an empty lookup with explicit template args!");
2518 *Out = CorrectTypoDelayed(
2519 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2520 [=](const TypoCorrection &TC) {
2521 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2522 diagnostic, diagnostic_suggest);
2523 },
2524 nullptr, CTK_ErrorRecovery, LookupCtx);
2525 if (*Out)
2526 return true;
2527 } else if (S && (Corrected =
2529 &SS, CCC, CTK_ErrorRecovery, LookupCtx))) {
2530 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2531 bool DroppedSpecifier =
2532 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2533 R.setLookupName(Corrected.getCorrection());
2534
2535 bool AcceptableWithRecovery = false;
2536 bool AcceptableWithoutRecovery = false;
2537 NamedDecl *ND = Corrected.getFoundDecl();
2538 if (ND) {
2539 if (Corrected.isOverloaded()) {
2543 for (NamedDecl *CD : Corrected) {
2544 if (FunctionTemplateDecl *FTD =
2545 dyn_cast<FunctionTemplateDecl>(CD))
2547 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2548 Args, OCS);
2549 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2550 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2552 Args, OCS);
2553 }
2554 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2555 case OR_Success:
2556 ND = Best->FoundDecl;
2557 Corrected.setCorrectionDecl(ND);
2558 break;
2559 default:
2560 // FIXME: Arbitrarily pick the first declaration for the note.
2561 Corrected.setCorrectionDecl(ND);
2562 break;
2563 }
2564 }
2565 R.addDecl(ND);
2566 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2567 CXXRecordDecl *Record = nullptr;
2568 if (Corrected.getCorrectionSpecifier()) {
2569 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2570 Record = Ty->getAsCXXRecordDecl();
2571 }
2572 if (!Record)
2573 Record = cast<CXXRecordDecl>(
2576 }
2577
2578 auto *UnderlyingND = ND->getUnderlyingDecl();
2579 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2580 isa<FunctionTemplateDecl>(UnderlyingND);
2581 // FIXME: If we ended up with a typo for a type name or
2582 // Objective-C class name, we're in trouble because the parser
2583 // is in the wrong place to recover. Suggest the typo
2584 // correction, but don't make it a fix-it since we're not going
2585 // to recover well anyway.
2586 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2587 getAsTypeTemplateDecl(UnderlyingND) ||
2588 isa<ObjCInterfaceDecl>(UnderlyingND);
2589 } else {
2590 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2591 // because we aren't able to recover.
2592 AcceptableWithoutRecovery = true;
2593 }
2594
2595 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2596 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2597 ? diag::note_implicit_param_decl
2598 : diag::note_previous_decl;
2599 if (SS.isEmpty())
2600 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2601 PDiag(NoteID), AcceptableWithRecovery);
2602 else
2603 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2604 << Name << computeDeclContext(SS, false)
2605 << DroppedSpecifier << SS.getRange(),
2606 PDiag(NoteID), AcceptableWithRecovery);
2607
2608 // Tell the callee whether to try to recover.
2609 return !AcceptableWithRecovery;
2610 }
2611 }
2612 R.clear();
2613
2614 // Emit a special diagnostic for failed member lookups.
2615 // FIXME: computing the declaration context might fail here (?)
2616 if (!SS.isEmpty()) {
2617 Diag(R.getNameLoc(), diag::err_no_member)
2618 << Name << computeDeclContext(SS, false)
2619 << SS.getRange();
2620 return true;
2621 }
2622
2623 // Give up, we can't recover.
2624 Diag(R.getNameLoc(), diagnostic) << Name;
2625 return true;
2626}
2627
2628/// In Microsoft mode, if we are inside a template class whose parent class has
2629/// dependent base classes, and we can't resolve an unqualified identifier, then
2630/// assume the identifier is a member of a dependent base class. We can only
2631/// recover successfully in static methods, instance methods, and other contexts
2632/// where 'this' is available. This doesn't precisely match MSVC's
2633/// instantiation model, but it's close enough.
2634static Expr *
2636 DeclarationNameInfo &NameInfo,
2637 SourceLocation TemplateKWLoc,
2638 const TemplateArgumentListInfo *TemplateArgs) {
2639 // Only try to recover from lookup into dependent bases in static methods or
2640 // contexts where 'this' is available.
2641 QualType ThisType = S.getCurrentThisType();
2642 const CXXRecordDecl *RD = nullptr;
2643 if (!ThisType.isNull())
2644 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2645 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2646 RD = MD->getParent();
2647 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2648 return nullptr;
2649
2650 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2651 // is available, suggest inserting 'this->' as a fixit.
2652 SourceLocation Loc = NameInfo.getLoc();
2653 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2654 DB << NameInfo.getName() << RD;
2655
2656 if (!ThisType.isNull()) {
2657 DB << FixItHint::CreateInsertion(Loc, "this->");
2659 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2660 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2661 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2662 }
2663
2664 // Synthesize a fake NNS that points to the derived class. This will
2665 // perform name lookup during template instantiation.
2666 CXXScopeSpec SS;
2667 auto *NNS =
2668 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2669 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2671 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2672 TemplateArgs);
2673}
2674
2677 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2678 bool HasTrailingLParen, bool IsAddressOfOperand,
2680 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2681 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2682 "cannot be direct & operand and have a trailing lparen");
2683 if (SS.isInvalid())
2684 return ExprError();
2685
2686 TemplateArgumentListInfo TemplateArgsBuffer;
2687
2688 // Decompose the UnqualifiedId into the following data.
2689 DeclarationNameInfo NameInfo;
2690 const TemplateArgumentListInfo *TemplateArgs;
2691 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2692
2693 DeclarationName Name = NameInfo.getName();
2694 IdentifierInfo *II = Name.getAsIdentifierInfo();
2695 SourceLocation NameLoc = NameInfo.getLoc();
2696
2697 if (II && II->isEditorPlaceholder()) {
2698 // FIXME: When typed placeholders are supported we can create a typed
2699 // placeholder expression node.
2700 return ExprError();
2701 }
2702
2703 // This specially handles arguments of attributes appertains to a type of C
2704 // struct field such that the name lookup within a struct finds the member
2705 // name, which is not the case for other contexts in C.
2706 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2707 // See if this is reference to a field of struct.
2708 LookupResult R(*this, NameInfo, LookupMemberName);
2709 // LookupName handles a name lookup from within anonymous struct.
2710 if (LookupName(R, S)) {
2711 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2712 QualType type = VD->getType().getNonReferenceType();
2713 // This will eventually be translated into MemberExpr upon
2714 // the use of instantiated struct fields.
2715 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2716 }
2717 }
2718 }
2719
2720 // Perform the required lookup.
2721 LookupResult R(*this, NameInfo,
2725 if (TemplateKWLoc.isValid() || TemplateArgs) {
2726 // Lookup the template name again to correctly establish the context in
2727 // which it was found. This is really unfortunate as we already did the
2728 // lookup to determine that it was a template name in the first place. If
2729 // this becomes a performance hit, we can work harder to preserve those
2730 // results until we get here but it's likely not worth it.
2731 AssumedTemplateKind AssumedTemplate;
2732 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2733 /*EnteringContext=*/false, TemplateKWLoc,
2734 &AssumedTemplate))
2735 return ExprError();
2736
2738 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2739 IsAddressOfOperand, TemplateArgs);
2740 } else {
2741 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2742 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2743 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2744
2745 // If the result might be in a dependent base class, this is a dependent
2746 // id-expression.
2748 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2749 IsAddressOfOperand, TemplateArgs);
2750
2751 // If this reference is in an Objective-C method, then we need to do
2752 // some special Objective-C lookup, too.
2753 if (IvarLookupFollowUp) {
2754 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2755 if (E.isInvalid())
2756 return ExprError();
2757
2758 if (Expr *Ex = E.getAs<Expr>())
2759 return Ex;
2760 }
2761 }
2762
2763 if (R.isAmbiguous())
2764 return ExprError();
2765
2766 // This could be an implicitly declared function reference if the language
2767 // mode allows it as a feature.
2768 if (R.empty() && HasTrailingLParen && II &&
2769 getLangOpts().implicitFunctionsAllowed()) {
2770 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2771 if (D) R.addDecl(D);
2772 }
2773
2774 // Determine whether this name might be a candidate for
2775 // argument-dependent lookup.
2776 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2777
2778 if (R.empty() && !ADL) {
2779 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2780 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2781 TemplateKWLoc, TemplateArgs))
2782 return E;
2783 }
2784
2785 // Don't diagnose an empty lookup for inline assembly.
2786 if (IsInlineAsmIdentifier)
2787 return ExprError();
2788
2789 // If this name wasn't predeclared and if this is not a function
2790 // call, diagnose the problem.
2791 TypoExpr *TE = nullptr;
2792 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2793 : nullptr);
2794 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2795 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2796 "Typo correction callback misconfigured");
2797 if (CCC) {
2798 // Make sure the callback knows what the typo being diagnosed is.
2799 CCC->setTypoName(II);
2800 if (SS.isValid())
2801 CCC->setTypoNNS(SS.getScopeRep());
2802 }
2803 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2804 // a template name, but we happen to have always already looked up the name
2805 // before we get here if it must be a template name.
2806 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2807 {}, nullptr, &TE)) {
2808 if (TE && KeywordReplacement) {
2809 auto &State = getTypoExprState(TE);
2810 auto BestTC = State.Consumer->getNextCorrection();
2811 if (BestTC.isKeyword()) {
2812 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2813 if (State.DiagHandler)
2814 State.DiagHandler(BestTC);
2815 KeywordReplacement->startToken();
2816 KeywordReplacement->setKind(II->getTokenID());
2817 KeywordReplacement->setIdentifierInfo(II);
2818 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2819 // Clean up the state associated with the TypoExpr, since it has
2820 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2821 clearDelayedTypo(TE);
2822 // Signal that a correction to a keyword was performed by returning a
2823 // valid-but-null ExprResult.
2824 return (Expr*)nullptr;
2825 }
2826 State.Consumer->resetCorrectionStream();
2827 }
2828 return TE ? TE : ExprError();
2829 }
2830
2831 assert(!R.empty() &&
2832 "DiagnoseEmptyLookup returned false but added no results");
2833
2834 // If we found an Objective-C instance variable, let
2835 // LookupInObjCMethod build the appropriate expression to
2836 // reference the ivar.
2837 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2838 R.clear();
2839 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2840 // In a hopelessly buggy code, Objective-C instance variable
2841 // lookup fails and no expression will be built to reference it.
2842 if (!E.isInvalid() && !E.get())
2843 return ExprError();
2844 return E;
2845 }
2846 }
2847
2848 // This is guaranteed from this point on.
2849 assert(!R.empty() || ADL);
2850
2851 // Check whether this might be a C++ implicit instance member access.
2852 // C++ [class.mfct.non-static]p3:
2853 // When an id-expression that is not part of a class member access
2854 // syntax and not used to form a pointer to member is used in the
2855 // body of a non-static member function of class X, if name lookup
2856 // resolves the name in the id-expression to a non-static non-type
2857 // member of some class C, the id-expression is transformed into a
2858 // class member access expression using (*this) as the
2859 // postfix-expression to the left of the . operator.
2860 //
2861 // But we don't actually need to do this for '&' operands if R
2862 // resolved to a function or overloaded function set, because the
2863 // expression is ill-formed if it actually works out to be a
2864 // non-static member function:
2865 //
2866 // C++ [expr.ref]p4:
2867 // Otherwise, if E1.E2 refers to a non-static member function. . .
2868 // [t]he expression can be used only as the left-hand operand of a
2869 // member function call.
2870 //
2871 // There are other safeguards against such uses, but it's important
2872 // to get this right here so that we don't end up making a
2873 // spuriously dependent expression if we're inside a dependent
2874 // instance method.
2875 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2876 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2877 S);
2878
2879 if (TemplateArgs || TemplateKWLoc.isValid()) {
2880
2881 // In C++1y, if this is a variable template id, then check it
2882 // in BuildTemplateIdExpr().
2883 // The single lookup result must be a variable template declaration.
2884 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2885 Id.TemplateId->Kind == TNK_Var_template) {
2886 assert(R.getAsSingle<VarTemplateDecl>() &&
2887 "There should only be one declaration found.");
2888 }
2889
2890 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2891 }
2892
2893 return BuildDeclarationNameExpr(SS, R, ADL);
2894}
2895
2897 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2898 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
2899 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2900 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
2901
2902 if (R.isAmbiguous())
2903 return ExprError();
2904
2906 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2907 NameInfo, /*TemplateArgs=*/nullptr);
2908
2909 if (R.empty()) {
2910 // Don't diagnose problems with invalid record decl, the secondary no_member
2911 // diagnostic during template instantiation is likely bogus, e.g. if a class
2912 // is invalid because it's derived from an invalid base class, then missing
2913 // members were likely supposed to be inherited.
2915 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2916 if (CD->isInvalidDecl())
2917 return ExprError();
2918 Diag(NameInfo.getLoc(), diag::err_no_member)
2919 << NameInfo.getName() << DC << SS.getRange();
2920 return ExprError();
2921 }
2922
2923 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2924 // Diagnose a missing typename if this resolved unambiguously to a type in
2925 // a dependent context. If we can recover with a type, downgrade this to
2926 // a warning in Microsoft compatibility mode.
2927 unsigned DiagID = diag::err_typename_missing;
2928 if (RecoveryTSI && getLangOpts().MSVCCompat)
2929 DiagID = diag::ext_typename_missing;
2931 auto D = Diag(Loc, DiagID);
2932 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2933 << SourceRange(Loc, NameInfo.getEndLoc());
2934
2935 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2936 // context.
2937 if (!RecoveryTSI)
2938 return ExprError();
2939
2940 // Only issue the fixit if we're prepared to recover.
2941 D << FixItHint::CreateInsertion(Loc, "typename ");
2942
2943 // Recover by pretending this was an elaborated type.
2945 TypeLocBuilder TLB;
2946 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2947
2952
2953 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2954
2955 return ExprEmpty();
2956 }
2957
2958 // If necessary, build an implicit class member access.
2959 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2961 /*TemplateKWLoc=*/SourceLocation(),
2962 R, /*TemplateArgs=*/nullptr,
2963 /*S=*/nullptr);
2964
2965 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
2966}
2967
2970 NestedNameSpecifier *Qualifier,
2971 NamedDecl *FoundDecl,
2972 NamedDecl *Member) {
2973 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2974 if (!RD)
2975 return From;
2976
2977 QualType DestRecordType;
2978 QualType DestType;
2979 QualType FromRecordType;
2980 QualType FromType = From->getType();
2981 bool PointerConversions = false;
2982 if (isa<FieldDecl>(Member)) {
2983 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2984 auto FromPtrType = FromType->getAs<PointerType>();
2985 DestRecordType = Context.getAddrSpaceQualType(
2986 DestRecordType, FromPtrType
2987 ? FromType->getPointeeType().getAddressSpace()
2988 : FromType.getAddressSpace());
2989
2990 if (FromPtrType) {
2991 DestType = Context.getPointerType(DestRecordType);
2992 FromRecordType = FromPtrType->getPointeeType();
2993 PointerConversions = true;
2994 } else {
2995 DestType = DestRecordType;
2996 FromRecordType = FromType;
2997 }
2998 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
2999 if (!Method->isImplicitObjectMemberFunction())
3000 return From;
3001
3002 DestType = Method->getThisType().getNonReferenceType();
3003 DestRecordType = Method->getFunctionObjectParameterType();
3004
3005 if (FromType->getAs<PointerType>()) {
3006 FromRecordType = FromType->getPointeeType();
3007 PointerConversions = true;
3008 } else {
3009 FromRecordType = FromType;
3010 DestType = DestRecordType;
3011 }
3012
3013 LangAS FromAS = FromRecordType.getAddressSpace();
3014 LangAS DestAS = DestRecordType.getAddressSpace();
3015 if (FromAS != DestAS) {
3016 QualType FromRecordTypeWithoutAS =
3017 Context.removeAddrSpaceQualType(FromRecordType);
3018 QualType FromTypeWithDestAS =
3019 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3020 if (PointerConversions)
3021 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3022 From = ImpCastExprToType(From, FromTypeWithDestAS,
3023 CK_AddressSpaceConversion, From->getValueKind())
3024 .get();
3025 }
3026 } else {
3027 // No conversion necessary.
3028 return From;
3029 }
3030
3031 if (DestType->isDependentType() || FromType->isDependentType())
3032 return From;
3033
3034 // If the unqualified types are the same, no conversion is necessary.
3035 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3036 return From;
3037
3038 SourceRange FromRange = From->getSourceRange();
3039 SourceLocation FromLoc = FromRange.getBegin();
3040
3041 ExprValueKind VK = From->getValueKind();
3042
3043 // C++ [class.member.lookup]p8:
3044 // [...] Ambiguities can often be resolved by qualifying a name with its
3045 // class name.
3046 //
3047 // If the member was a qualified name and the qualified referred to a
3048 // specific base subobject type, we'll cast to that intermediate type
3049 // first and then to the object in which the member is declared. That allows
3050 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3051 //
3052 // class Base { public: int x; };
3053 // class Derived1 : public Base { };
3054 // class Derived2 : public Base { };
3055 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3056 //
3057 // void VeryDerived::f() {
3058 // x = 17; // error: ambiguous base subobjects
3059 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3060 // }
3061 if (Qualifier && Qualifier->getAsType()) {
3062 QualType QType = QualType(Qualifier->getAsType(), 0);
3063 assert(QType->isRecordType() && "lookup done with non-record type");
3064
3065 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3066
3067 // In C++98, the qualifier type doesn't actually have to be a base
3068 // type of the object type, in which case we just ignore it.
3069 // Otherwise build the appropriate casts.
3070 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3071 CXXCastPath BasePath;
3072 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3073 FromLoc, FromRange, &BasePath))
3074 return ExprError();
3075
3076 if (PointerConversions)
3077 QType = Context.getPointerType(QType);
3078 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3079 VK, &BasePath).get();
3080
3081 FromType = QType;
3082 FromRecordType = QRecordType;
3083
3084 // If the qualifier type was the same as the destination type,
3085 // we're done.
3086 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3087 return From;
3088 }
3089 }
3090
3091 CXXCastPath BasePath;
3092 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3093 FromLoc, FromRange, &BasePath,
3094 /*IgnoreAccess=*/true))
3095 return ExprError();
3096
3097 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3098 VK, &BasePath);
3099}
3100
3102 const LookupResult &R,
3103 bool HasTrailingLParen) {
3104 // Only when used directly as the postfix-expression of a call.
3105 if (!HasTrailingLParen)
3106 return false;
3107
3108 // Never if a scope specifier was provided.
3109 if (SS.isNotEmpty())
3110 return false;
3111
3112 // Only in C++ or ObjC++.
3113 if (!getLangOpts().CPlusPlus)
3114 return false;
3115
3116 // Turn off ADL when we find certain kinds of declarations during
3117 // normal lookup:
3118 for (const NamedDecl *D : R) {
3119 // C++0x [basic.lookup.argdep]p3:
3120 // -- a declaration of a class member
3121 // Since using decls preserve this property, we check this on the
3122 // original decl.
3123 if (D->isCXXClassMember())
3124 return false;
3125
3126 // C++0x [basic.lookup.argdep]p3:
3127 // -- a block-scope function declaration that is not a
3128 // using-declaration
3129 // NOTE: we also trigger this for function templates (in fact, we
3130 // don't check the decl type at all, since all other decl types
3131 // turn off ADL anyway).
3132 if (isa<UsingShadowDecl>(D))
3133 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3135 return false;
3136
3137 // C++0x [basic.lookup.argdep]p3:
3138 // -- a declaration that is neither a function or a function
3139 // template
3140 // And also for builtin functions.
3141 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3142 // But also builtin functions.
3143 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3144 return false;
3145 } else if (!isa<FunctionTemplateDecl>(D))
3146 return false;
3147 }
3148
3149 return true;
3150}
3151
3152
3153/// Diagnoses obvious problems with the use of the given declaration
3154/// as an expression. This is only actually called for lookups that
3155/// were not overloaded, and it doesn't promise that the declaration
3156/// will in fact be used.
3158 bool AcceptInvalid) {
3159 if (D->isInvalidDecl() && !AcceptInvalid)
3160 return true;
3161
3162 if (isa<TypedefNameDecl>(D)) {
3163 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3164 return true;
3165 }
3166
3167 if (isa<ObjCInterfaceDecl>(D)) {
3168 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3169 return true;
3170 }
3171
3172 if (isa<NamespaceDecl>(D)) {
3173 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3174 return true;
3175 }
3176
3177 return false;
3178}
3179
3180// Certain multiversion types should be treated as overloaded even when there is
3181// only one result.
3183 assert(R.isSingleResult() && "Expected only a single result");
3184 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3185 return FD &&
3186 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3187}
3188
3190 LookupResult &R, bool NeedsADL,
3191 bool AcceptInvalidDecl) {
3192 // If this is a single, fully-resolved result and we don't need ADL,
3193 // just build an ordinary singleton decl ref.
3194 if (!NeedsADL && R.isSingleResult() &&
3198 R.getRepresentativeDecl(), nullptr,
3199 AcceptInvalidDecl);
3200
3201 // We only need to check the declaration if there's exactly one
3202 // result, because in the overloaded case the results can only be
3203 // functions and function templates.
3205 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3206 AcceptInvalidDecl))
3207 return ExprError();
3208
3209 // Otherwise, just build an unresolved lookup expression. Suppress
3210 // any lookup-related diagnostics; we'll hash these out later, when
3211 // we've picked a target.
3213
3216 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3217 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3218
3219 return ULE;
3220}
3221
3223 SourceLocation loc,
3224 ValueDecl *var);
3225
3227 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3228 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3229 bool AcceptInvalidDecl) {
3230 assert(D && "Cannot refer to a NULL declaration");
3231 assert(!isa<FunctionTemplateDecl>(D) &&
3232 "Cannot refer unambiguously to a function template");
3233
3234 SourceLocation Loc = NameInfo.getLoc();
3235 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3236 // Recovery from invalid cases (e.g. D is an invalid Decl).
3237 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3238 // diagnostics, as invalid decls use int as a fallback type.
3239 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3240 }
3241
3242 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3243 // Specifically diagnose references to class templates that are missing
3244 // a template argument list.
3245 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3246 return ExprError();
3247 }
3248
3249 // Make sure that we're referring to a value.
3250 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3251 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3252 Diag(D->getLocation(), diag::note_declared_at);
3253 return ExprError();
3254 }
3255
3256 // Check whether this declaration can be used. Note that we suppress
3257 // this check when we're going to perform argument-dependent lookup
3258 // on this function name, because this might not be the function
3259 // that overload resolution actually selects.
3260 if (DiagnoseUseOfDecl(D, Loc))
3261 return ExprError();
3262
3263 auto *VD = cast<ValueDecl>(D);
3264
3265 // Only create DeclRefExpr's for valid Decl's.
3266 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3267 return ExprError();
3268
3269 // Handle members of anonymous structs and unions. If we got here,
3270 // and the reference is to a class member indirect field, then this
3271 // must be the subject of a pointer-to-member expression.
3272 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3273 IndirectField && !IndirectField->isCXXClassMember())
3275 IndirectField);
3276
3277 QualType type = VD->getType();
3278 if (type.isNull())
3279 return ExprError();
3280 ExprValueKind valueKind = VK_PRValue;
3281
3282 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3283 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3284 // is expanded by some outer '...' in the context of the use.
3285 type = type.getNonPackExpansionType();
3286
3287 switch (D->getKind()) {
3288 // Ignore all the non-ValueDecl kinds.
3289#define ABSTRACT_DECL(kind)
3290#define VALUE(type, base)
3291#define DECL(type, base) case Decl::type:
3292#include "clang/AST/DeclNodes.inc"
3293 llvm_unreachable("invalid value decl kind");
3294
3295 // These shouldn't make it here.
3296 case Decl::ObjCAtDefsField:
3297 llvm_unreachable("forming non-member reference to ivar?");
3298
3299 // Enum constants are always r-values and never references.
3300 // Unresolved using declarations are dependent.
3301 case Decl::EnumConstant:
3302 case Decl::UnresolvedUsingValue:
3303 case Decl::OMPDeclareReduction:
3304 case Decl::OMPDeclareMapper:
3305 valueKind = VK_PRValue;
3306 break;
3307
3308 // Fields and indirect fields that got here must be for
3309 // pointer-to-member expressions; we just call them l-values for
3310 // internal consistency, because this subexpression doesn't really
3311 // exist in the high-level semantics.
3312 case Decl::Field:
3313 case Decl::IndirectField:
3314 case Decl::ObjCIvar:
3315 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3316 "building reference to field in C?");
3317
3318 // These can't have reference type in well-formed programs, but
3319 // for internal consistency we do this anyway.
3320 type = type.getNonReferenceType();
3321 valueKind = VK_LValue;
3322 break;
3323
3324 // Non-type template parameters are either l-values or r-values
3325 // depending on the type.
3326 case Decl::NonTypeTemplateParm: {
3327 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3328 type = reftype->getPointeeType();
3329 valueKind = VK_LValue; // even if the parameter is an r-value reference
3330 break;
3331 }
3332
3333 // [expr.prim.id.unqual]p2:
3334 // If the entity is a template parameter object for a template
3335 // parameter of type T, the type of the expression is const T.
3336 // [...] The expression is an lvalue if the entity is a [...] template
3337 // parameter object.
3338 if (type->isRecordType()) {
3339 type = type.getUnqualifiedType().withConst();
3340 valueKind = VK_LValue;
3341 break;
3342 }
3343
3344 // For non-references, we need to strip qualifiers just in case
3345 // the template parameter was declared as 'const int' or whatever.
3346 valueKind = VK_PRValue;
3347 type = type.getUnqualifiedType();
3348 break;
3349 }
3350
3351 case Decl::Var:
3352 case Decl::VarTemplateSpecialization:
3353 case Decl::VarTemplatePartialSpecialization:
3354 case Decl::Decomposition:
3355 case Decl::Binding:
3356 case Decl::OMPCapturedExpr:
3357 // In C, "extern void blah;" is valid and is an r-value.
3358 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3359 type->isVoidType()) {
3360 valueKind = VK_PRValue;
3361 break;
3362 }
3363 [[fallthrough]];
3364
3365 case Decl::ImplicitParam:
3366 case Decl::ParmVar: {
3367 // These are always l-values.
3368 valueKind = VK_LValue;
3369 type = type.getNonReferenceType();
3370
3371 // FIXME: Does the addition of const really only apply in
3372 // potentially-evaluated contexts? Since the variable isn't actually
3373 // captured in an unevaluated context, it seems that the answer is no.
3374 if (!isUnevaluatedContext()) {
3375 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3376 if (!CapturedType.isNull())
3377 type = CapturedType;
3378 }
3379 break;
3380 }
3381
3382 case Decl::Function: {
3383 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3386 valueKind = VK_PRValue;
3387 break;
3388 }
3389 }
3390
3391 const FunctionType *fty = type->castAs<FunctionType>();
3392
3393 // If we're referring to a function with an __unknown_anytype
3394 // result type, make the entire expression __unknown_anytype.
3395 if (fty->getReturnType() == Context.UnknownAnyTy) {
3397 valueKind = VK_PRValue;
3398 break;
3399 }
3400
3401 // Functions are l-values in C++.
3402 if (getLangOpts().CPlusPlus) {
3403 valueKind = VK_LValue;
3404 break;
3405 }
3406
3407 // C99 DR 316 says that, if a function type comes from a
3408 // function definition (without a prototype), that type is only
3409 // used for checking compatibility. Therefore, when referencing
3410 // the function, we pretend that we don't have the full function
3411 // type.
3412 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3414 fty->getExtInfo());
3415
3416 // Functions are r-values in C.
3417 valueKind = VK_PRValue;
3418 break;
3419 }
3420
3421 case Decl::CXXDeductionGuide:
3422 llvm_unreachable("building reference to deduction guide");
3423
3424 case Decl::MSProperty:
3425 case Decl::MSGuid:
3426 case Decl::TemplateParamObject:
3427 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3428 // capture in OpenMP, or duplicated between host and device?
3429 valueKind = VK_LValue;
3430 break;
3431
3432 case Decl::UnnamedGlobalConstant:
3433 valueKind = VK_LValue;
3434 break;
3435
3436 case Decl::CXXMethod:
3437 // If we're referring to a method with an __unknown_anytype
3438 // result type, make the entire expression __unknown_anytype.
3439 // This should only be possible with a type written directly.
3440 if (const FunctionProtoType *proto =
3441 dyn_cast<FunctionProtoType>(VD->getType()))
3442 if (proto->getReturnType() == Context.UnknownAnyTy) {
3444 valueKind = VK_PRValue;
3445 break;
3446 }
3447
3448 // C++ methods are l-values if static, r-values if non-static.
3449 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3450 valueKind = VK_LValue;
3451 break;
3452 }
3453 [[fallthrough]];
3454
3455 case Decl::CXXConversion:
3456 case Decl::CXXDestructor:
3457 case Decl::CXXConstructor:
3458 valueKind = VK_PRValue;
3459 break;
3460 }
3461
3462 auto *E =
3463 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3464 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3465 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3466 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3467 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3468 // diagnostics).
3469 if (VD->isInvalidDecl() && E)
3470 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3471 return E;
3472}
3473
3474static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3476 Target.resize(CharByteWidth * (Source.size() + 1));
3477 char *ResultPtr = &Target[0];
3478 const llvm::UTF8 *ErrorPtr;
3479 bool success =
3480 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3481 (void)success;
3482 assert(success);
3483 Target.resize(ResultPtr - &Target[0]);
3484}
3485
3488 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3489 if (!currentDecl) {
3490 Diag(Loc, diag::ext_predef_outside_function);
3491 currentDecl = Context.getTranslationUnitDecl();
3492 }
3493
3494 QualType ResTy;
3495 StringLiteral *SL = nullptr;
3496 if (cast<DeclContext>(currentDecl)->isDependentContext())
3497 ResTy = Context.DependentTy;
3498 else {
3499 // Pre-defined identifiers are of type char[x], where x is the length of
3500 // the string.
3501 bool ForceElaboratedPrinting =
3502 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3503 auto Str =
3504 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3505 unsigned Length = Str.length();
3506
3507 llvm::APInt LengthI(32, Length + 1);
3510 ResTy =
3512 SmallString<32> RawChars;
3514 Str, RawChars);
3515 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3517 /*IndexTypeQuals*/ 0);
3519 /*Pascal*/ false, ResTy, Loc);
3520 } else {
3522 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3524 /*IndexTypeQuals*/ 0);
3526 /*Pascal*/ false, ResTy, Loc);
3527 }
3528 }
3529
3530 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3531 SL);
3532}
3533
3536}
3537
3539 SmallString<16> CharBuffer;
3540 bool Invalid = false;
3541 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3542 if (Invalid)
3543 return ExprError();
3544
3545 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3546 PP, Tok.getKind());
3547 if (Literal.hadError())
3548 return ExprError();
3549
3550 QualType Ty;
3551 if (Literal.isWide())
3552 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3553 else if (Literal.isUTF8() && getLangOpts().C23)
3554 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3555 else if (Literal.isUTF8() && getLangOpts().Char8)
3556 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3557 else if (Literal.isUTF16())
3558 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3559 else if (Literal.isUTF32())
3560 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3561 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3562 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3563 else
3564 Ty = Context.CharTy; // 'x' -> char in C++;
3565 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3566
3568 if (Literal.isWide())
3570 else if (Literal.isUTF16())
3572 else if (Literal.isUTF32())
3574 else if (Literal.isUTF8())
3576
3577 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3578 Tok.getLocation());
3579
3580 if (Literal.getUDSuffix().empty())
3581 return Lit;
3582
3583 // We're building a user-defined literal.
3584 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3585 SourceLocation UDSuffixLoc =
3586 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3587
3588 // Make sure we're allowed user-defined literals here.
3589 if (!UDLScope)
3590 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3591
3592 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3593 // operator "" X (ch)
3594 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3595 Lit, Tok.getLocation());
3596}
3597
3599 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3601 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3602 Context.IntTy, Loc);
3603}
3604
3607 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3608
3609 using llvm::APFloat;
3610 APFloat Val(Format);
3611
3612 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3613 if (RM == llvm::RoundingMode::Dynamic)
3614 RM = llvm::RoundingMode::NearestTiesToEven;
3615 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3616
3617 // Overflow is always an error, but underflow is only an error if
3618 // we underflowed to zero (APFloat reports denormals as underflow).
3619 if ((result & APFloat::opOverflow) ||
3620 ((result & APFloat::opUnderflow) && Val.isZero())) {
3621 unsigned diagnostic;
3622 SmallString<20> buffer;
3623 if (result & APFloat::opOverflow) {
3624 diagnostic = diag::warn_float_overflow;
3625 APFloat::getLargest(Format).toString(buffer);
3626 } else {
3627 diagnostic = diag::warn_float_underflow;
3628 APFloat::getSmallest(Format).toString(buffer);
3629 }
3630
3631 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3632 }
3633
3634 bool isExact = (result == APFloat::opOK);
3635 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3636}
3637
3639 assert(E && "Invalid expression");
3640
3641 if (E->isValueDependent())
3642 return false;
3643
3644 QualType QT = E->getType();
3645 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3646 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3647 return true;
3648 }
3649
3650 llvm::APSInt ValueAPS;
3652
3653 if (R.isInvalid())
3654 return true;
3655
3656 // GCC allows the value of unroll count to be 0.
3657 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3658 // "The values of 0 and 1 block any unrolling of the loop."
3659 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3660 // '#pragma unroll' cases.
3661 bool ValueIsPositive =
3662 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3663 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3664 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3665 << toString(ValueAPS, 10) << ValueIsPositive;
3666 return true;
3667 }
3668
3669 return false;
3670}
3671
3673 // Fast path for a single digit (which is quite common). A single digit
3674 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3675 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3676 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3677 return ActOnIntegerConstant(Tok.getLocation(), Val);
3678 }
3679
3680 SmallString<128> SpellingBuffer;
3681 // NumericLiteralParser wants to overread by one character. Add padding to
3682 // the buffer in case the token is copied to the buffer. If getSpelling()
3683 // returns a StringRef to the memory buffer, it should have a null char at
3684 // the EOF, so it is also safe.
3685 SpellingBuffer.resize(Tok.getLength() + 1);
3686
3687 // Get the spelling of the token, which eliminates trigraphs, etc.
3688 bool Invalid = false;
3689 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3690 if (Invalid)
3691 return ExprError();
3692
3693 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3696 if (Literal.hadError)
3697 return ExprError();
3698
3699 if (Literal.hasUDSuffix()) {
3700 // We're building a user-defined literal.
3701 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3702 SourceLocation UDSuffixLoc =
3703 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3704
3705 // Make sure we're allowed user-defined literals here.
3706 if (!UDLScope)
3707 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3708
3709 QualType CookedTy;
3710 if (Literal.isFloatingLiteral()) {
3711 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3712 // long double, the literal is treated as a call of the form
3713 // operator "" X (f L)
3714 CookedTy = Context.LongDoubleTy;
3715 } else {
3716 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3717 // unsigned long long, the literal is treated as a call of the form
3718 // operator "" X (n ULL)
3719 CookedTy = Context.UnsignedLongLongTy;
3720 }
3721
3722 DeclarationName OpName =
3724 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3725 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3726
3727 SourceLocation TokLoc = Tok.getLocation();
3728
3729 // Perform literal operator lookup to determine if we're building a raw
3730 // literal or a cooked one.
3731 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3732 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3733 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3734 /*AllowStringTemplatePack*/ false,
3735 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3737 // Lookup failure for imaginary constants isn't fatal, there's still the
3738 // GNU extension producing _Complex types.
3739 break;
3740 case LOLR_Error:
3741 return ExprError();
3742 case LOLR_Cooked: {
3743 Expr *Lit;
3744 if (Literal.isFloatingLiteral()) {
3745 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3746 } else {
3747 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3748 if (Literal.GetIntegerValue(ResultVal))
3749 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3750 << /* Unsigned */ 1;
3751 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3752 Tok.getLocation());
3753 }
3754 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3755 }
3756
3757 case LOLR_Raw: {
3758 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3759 // literal is treated as a call of the form
3760 // operator "" X ("n")
3761 unsigned Length = Literal.getUDSuffixOffset();
3764 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3765 Expr *Lit =
3766 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3768 /*Pascal*/ false, StrTy, &TokLoc, 1);
3769 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3770 }
3771
3772 case LOLR_Template: {
3773 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3774 // template), L is treated as a call fo the form
3775 // operator "" X <'c1', 'c2', ... 'ck'>()
3776 // where n is the source character sequence c1 c2 ... ck.
3777 TemplateArgumentListInfo ExplicitArgs;
3778 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3779 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3780 llvm::APSInt Value(CharBits, CharIsUnsigned);
3781 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3782 Value = TokSpelling[I];
3785 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3786 }
3787 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
3788 }
3790 llvm_unreachable("unexpected literal operator lookup result");
3791 }
3792 }
3793
3794 Expr *Res;
3795
3796 if (Literal.isFixedPointLiteral()) {
3797 QualType Ty;
3798
3799 if (Literal.isAccum) {
3800 if (Literal.isHalf) {
3801 Ty = Context.ShortAccumTy;
3802 } else if (Literal.isLong) {
3803 Ty = Context.LongAccumTy;
3804 } else {
3805 Ty = Context.AccumTy;
3806 }
3807 } else if (Literal.isFract) {
3808 if (Literal.isHalf) {
3809 Ty = Context.ShortFractTy;
3810 } else if (Literal.isLong) {
3811 Ty = Context.LongFractTy;
3812 } else {
3813 Ty = Context.FractTy;
3814 }
3815 }
3816
3817 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3818
3819 bool isSigned = !Literal.isUnsigned;
3820 unsigned scale = Context.getFixedPointScale(Ty);
3821 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3822
3823 llvm::APInt Val(bit_width, 0, isSigned);
3824 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3825 bool ValIsZero = Val.isZero() && !Overflowed;
3826
3827 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3828 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3829 // Clause 6.4.4 - The value of a constant shall be in the range of
3830 // representable values for its type, with exception for constants of a
3831 // fract type with a value of exactly 1; such a constant shall denote
3832 // the maximal value for the type.
3833 --Val;
3834 else if (Val.ugt(MaxVal) || Overflowed)
3835 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3836
3838 Tok.getLocation(), scale);
3839 } else if (Literal.isFloatingLiteral()) {
3840 QualType Ty;
3841 if (Literal.isHalf){
3842 if (getLangOpts().HLSL ||
3843 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3844 Ty = Context.HalfTy;
3845 else {
3846 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3847 return ExprError();
3848 }
3849 } else if (Literal.isFloat)
3850 Ty = Context.FloatTy;
3851 else if (Literal.isLong)
3853 else if (Literal.isFloat16)
3854 Ty = Context.Float16Ty;
3855 else if (Literal.isFloat128)
3856 Ty = Context.Float128Ty;
3857 else if (getLangOpts().HLSL)
3858 Ty = Context.FloatTy;
3859 else
3860 Ty = Context.DoubleTy;
3861
3862 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3863
3864 if (Ty == Context.DoubleTy) {
3865 if (getLangOpts().SinglePrecisionConstants) {
3866 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3867 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3868 }
3869 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3870 "cl_khr_fp64", getLangOpts())) {
3871 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3872 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3874 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3875 }
3876 }
3877 } else if (!Literal.isIntegerLiteral()) {
3878 return ExprError();
3879 } else {
3880 QualType Ty;
3881
3882 // 'z/uz' literals are a C++23 feature.
3883 if (Literal.isSizeT)
3886 ? diag::warn_cxx20_compat_size_t_suffix
3887 : diag::ext_cxx23_size_t_suffix
3888 : diag::err_cxx23_size_t_suffix);
3889
3890 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
3891 // but we do not currently support the suffix in C++ mode because it's not
3892 // entirely clear whether WG21 will prefer this suffix to return a library
3893 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
3894 // literals are a C++ extension.
3895 if (Literal.isBitInt)
3896 PP.Diag(Tok.getLocation(),
3897 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
3898 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
3899 : diag::ext_c23_bitint_suffix);
3900
3901 // Get the value in the widest-possible width. What is "widest" depends on
3902 // whether the literal is a bit-precise integer or not. For a bit-precise
3903 // integer type, try to scan the source to determine how many bits are
3904 // needed to represent the value. This may seem a bit expensive, but trying
3905 // to get the integer value from an overly-wide APInt is *extremely*
3906 // expensive, so the naive approach of assuming
3907 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3908 unsigned BitsNeeded =
3909 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3910 Literal.getLiteralDigits(), Literal.getRadix())
3912 llvm::APInt ResultVal(BitsNeeded, 0);
3913
3914 if (Literal.GetIntegerValue(ResultVal)) {
3915 // If this value didn't fit into uintmax_t, error and force to ull.
3916 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3917 << /* Unsigned */ 1;
3919 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3920 "long long is not intmax_t?");
3921 } else {
3922 // If this value fits into a ULL, try to figure out what else it fits into
3923 // according to the rules of C99 6.4.4.1p5.
3924
3925 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3926 // be an unsigned int.
3927 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3928
3929 // HLSL doesn't really have `long` or `long long`. We support the `ll`
3930 // suffix for portability of code with C++, but both `l` and `ll` are
3931 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
3932 // same.
3933 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
3934 Literal.isLong = true;
3935 Literal.isLongLong = false;
3936 }
3937
3938 // Check from smallest to largest, picking the smallest type we can.
3939 unsigned Width = 0;
3940
3941 // Microsoft specific integer suffixes are explicitly sized.
3942 if (Literal.MicrosoftInteger) {
3943 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3944 Width = 8;
3945 Ty = Context.CharTy;
3946 } else {
3947 Width = Literal.MicrosoftInteger;
3948 Ty = Context.getIntTypeForBitwidth(Width,
3949 /*Signed=*/!Literal.isUnsigned);
3950 }
3951 }
3952
3953 // Bit-precise integer literals are automagically-sized based on the
3954 // width required by the literal.
3955 if (Literal.isBitInt) {
3956 // The signed version has one more bit for the sign value. There are no
3957 // zero-width bit-precise integers, even if the literal value is 0.
3958 Width = std::max(ResultVal.getActiveBits(), 1u) +
3959 (Literal.isUnsigned ? 0u : 1u);
3960
3961 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
3962 // and reset the type to the largest supported width.
3963 unsigned int MaxBitIntWidth =
3965 if (Width > MaxBitIntWidth) {
3966 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3967 << Literal.isUnsigned;
3968 Width = MaxBitIntWidth;
3969 }
3970
3971 // Reset the result value to the smaller APInt and select the correct
3972 // type to be used. Note, we zext even for signed values because the
3973 // literal itself is always an unsigned value (a preceeding - is a
3974 // unary operator, not part of the literal).
3975 ResultVal = ResultVal.zextOrTrunc(Width);
3976 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
3977 }
3978
3979 // Check C++23 size_t literals.
3980 if (Literal.isSizeT) {
3981 assert(!Literal.MicrosoftInteger &&
3982 "size_t literals can't be Microsoft literals");
3983 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3985
3986 // Does it fit in size_t?
3987 if (ResultVal.isIntN(SizeTSize)) {
3988 // Does it fit in ssize_t?
3989 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3991 else if (AllowUnsigned)
3992 Ty = Context.getSizeType();
3993 Width = SizeTSize;
3994 }
3995 }
3996
3997 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3998 !Literal.isSizeT) {
3999 // Are int/unsigned possibilities?
4000 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4001
4002 // Does it fit in a unsigned int?
4003 if (ResultVal.isIntN(IntSize)) {
4004 // Does it fit in a signed int?
4005 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4006 Ty = Context.IntTy;
4007 else if (AllowUnsigned)
4009 Width = IntSize;
4010 }
4011 }
4012
4013 // Are long/unsigned long possibilities?
4014 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4015 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4016
4017 // Does it fit in a unsigned long?
4018 if (ResultVal.isIntN(LongSize)) {
4019 // Does it fit in a signed long?
4020 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4021 Ty = Context.LongTy;
4022 else if (AllowUnsigned)
4024 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4025 // is compatible.
4026 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4027 const unsigned LongLongSize =
4029 Diag(Tok.getLocation(),
4031 ? Literal.isLong
4032 ? diag::warn_old_implicitly_unsigned_long_cxx
4033 : /*C++98 UB*/ diag::
4034 ext_old_implicitly_unsigned_long_cxx
4035 : diag::warn_old_implicitly_unsigned_long)
4036 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4037 : /*will be ill-formed*/ 1);
4039 }
4040 Width = LongSize;
4041 }
4042 }
4043
4044 // Check long long if needed.
4045 if (Ty.isNull() && !Literal.isSizeT) {
4046 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4047
4048 // Does it fit in a unsigned long long?
4049 if (ResultVal.isIntN(LongLongSize)) {
4050 // Does it fit in a signed long long?
4051 // To be compatible with MSVC, hex integer literals ending with the
4052 // LL or i64 suffix are always signed in Microsoft mode.
4053 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4054 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4055 Ty = Context.LongLongTy;
4056 else if (AllowUnsigned)
4058 Width = LongLongSize;
4059
4060 // 'long long' is a C99 or C++11 feature, whether the literal
4061 // explicitly specified 'long long' or we needed the extra width.
4062 if (getLangOpts().CPlusPlus)
4063 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4064 ? diag::warn_cxx98_compat_longlong
4065 : diag::ext_cxx11_longlong);
4066 else if (!getLangOpts().C99)
4067 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4068 }
4069 }
4070
4071 // If we still couldn't decide a type, we either have 'size_t' literal
4072 // that is out of range, or a decimal literal that does not fit in a
4073 // signed long long and has no U suffix.
4074 if (Ty.isNull()) {
4075 if (Literal.isSizeT)
4076 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4077 << Literal.isUnsigned;
4078 else
4079 Diag(Tok.getLocation(),
4080 diag::ext_integer_literal_too_large_for_signed);
4083 }
4084
4085 if (ResultVal.getBitWidth() != Width)
4086 ResultVal = ResultVal.trunc(Width);
4087 }
4088 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4089 }
4090
4091 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4092 if (Literal.isImaginary) {
4093 Res = new (Context) ImaginaryLiteral(Res,
4095
4096 // In C++, this is a GNU extension. In C, it's a C2y extension.
4097 unsigned DiagId;
4098 if (getLangOpts().CPlusPlus)
4099 DiagId = diag::ext_gnu_imaginary_constant;
4100 else if (getLangOpts().C2y)
4101 DiagId = diag::warn_c23_compat_imaginary_constant;
4102 else
4103 DiagId = diag::ext_c2y_imaginary_constant;
4104 Diag(Tok.getLocation(), DiagId);
4105 }
4106 return Res;
4107}
4108
4110 assert(E && "ActOnParenExpr() missing expr");
4111 QualType ExprTy = E->getType();
4112 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4113 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4114 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4115 return new (Context) ParenExpr(L, R, E);
4116}
4117
4120 SourceRange ArgRange) {
4121 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4122 // scalar or vector data type argument..."
4123 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4124 // type (C99 6.2.5p18) or void.
4125 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4126 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4127 << T << ArgRange;
4128 return true;
4129 }
4130
4131 assert((T->isVoidType() || !T->isIncompleteType()) &&
4132 "Scalar types should always be complete");
4133 return false;
4134}
4135
4138 SourceRange ArgRange) {
4139 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4140 if (!T->isVectorType() && !T->isSizelessVectorType())
4141 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4142 << ""
4143 << "__builtin_vectorelements" << T << ArgRange;
4144
4145 return false;
4146}
4147
4150 SourceRange ArgRange) {
4151 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4152 return true;
4153
4154 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4156 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4157 return true;
4158 }
4159
4160 return false;
4161}
4162
4165 SourceRange ArgRange,
4166 UnaryExprOrTypeTrait TraitKind) {
4167 // Invalid types must be hard errors for SFINAE in C++.
4168 if (S.LangOpts.CPlusPlus)
4169 return true;
4170
4171 // C99 6.5.3.4p1:
4172 if (T->isFunctionType() &&
4173 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4174 TraitKind == UETT_PreferredAlignOf)) {
4175 // sizeof(function)/alignof(function) is allowed as an extension.
4176 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4177 << getTraitSpelling(TraitKind) << ArgRange;
4178 return false;
4179 }
4180
4181 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4182 // this is an error (OpenCL v1.1 s6.3.k)
4183 if (T->isVoidType()) {
4184 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4185 : diag::ext_sizeof_alignof_void_type;
4186 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4187 return false;
4188 }
4189
4190 return true;
4191}
4192
4195 SourceRange ArgRange,
4196 UnaryExprOrTypeTrait TraitKind) {
4197 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4198 // runtime doesn't allow it.
4200 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4201 << T << (TraitKind == UETT_SizeOf)
4202 << ArgRange;
4203 return true;
4204 }
4205
4206 return false;
4207}
4208
4209/// Check whether E is a pointer from a decayed array type (the decayed
4210/// pointer type is equal to T) and emit a warning if it is.
4212 const Expr *E) {
4213 // Don't warn if the operation changed the type.
4214 if (T != E->getType())
4215 return;
4216
4217 // Now look for array decays.
4218 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4219 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4220 return;
4221
4222 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4223 << ICE->getType()
4224 << ICE->getSubExpr()->getType();
4225}
4226
4228 UnaryExprOrTypeTrait ExprKind) {
4229 QualType ExprTy = E->getType();
4230 assert(!ExprTy->isReferenceType());
4231
4232 bool IsUnevaluatedOperand =
4233 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4234 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4235 ExprKind == UETT_VecStep);
4236 if (IsUnevaluatedOperand) {
4238 if (Result.isInvalid())
4239 return true;
4240 E = Result.get();
4241 }
4242
4243 // The operand for sizeof and alignof is in an unevaluated expression context,
4244 // so side effects could result in unintended consequences.
4245 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4246 // used to build SFINAE gadgets.
4247 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4248 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4250 !E->getType()->isVariableArrayType() &&
4251 E->HasSideEffects(Context, false))
4252 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4253
4254 if (ExprKind == UETT_VecStep)
4255 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4256 E->getSourceRange());
4257
4258 if (ExprKind == UETT_VectorElements)
4259 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4260 E->getSourceRange());
4261
4262 // Explicitly list some types as extensions.
4263 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4264 E->getSourceRange(), ExprKind))
4265 return false;
4266
4267 // WebAssembly tables are always illegal operands to unary expressions and
4268 // type traits.
4269 if (Context.getTargetInfo().getTriple().isWasm() &&
4271 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4272 << getTraitSpelling(ExprKind);
4273 return true;
4274 }
4275
4276 // 'alignof' applied to an expression only requires the base element type of
4277 // the expression to be complete. 'sizeof' requires the expression's type to
4278 // be complete (and will attempt to complete it if it's an array of unknown
4279 // bound).
4280 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4283 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4284 getTraitSpelling(ExprKind), E->getSourceRange()))
4285 return true;
4286 } else {
4288 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4289 getTraitSpelling(ExprKind), E->getSourceRange()))
4290 return true;
4291 }
4292
4293 // Completing the expression's type may have changed it.
4294 ExprTy = E->getType();
4295 assert(!ExprTy->isReferenceType());
4296
4297 if (ExprTy->isFunctionType()) {
4298 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4299 << getTraitSpelling(ExprKind) << E->getSourceRange();
4300 return true;
4301 }
4302
4303 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4304 E->getSourceRange(), ExprKind))
4305 return true;
4306
4307 if (ExprKind == UETT_SizeOf) {
4308 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4309 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4310 QualType OType = PVD->getOriginalType();
4311 QualType Type = PVD->getType();
4312 if (Type->isPointerType() && OType->isArrayType()) {
4313 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4314 << Type << OType;
4315 Diag(PVD->getLocation(), diag::note_declared_at);
4316 }
4317 }
4318 }
4319
4320 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4321 // decays into a pointer and returns an unintended result. This is most
4322 // likely a typo for "sizeof(array) op x".
4323 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4324 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4325 BO->getLHS());
4326 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4327 BO->getRHS());
4328 }
4329 }
4330
4331 return false;
4332}
4333
4334static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4335 // Cannot know anything else if the expression is dependent.
4336 if (E->isTypeDependent())
4337 return false;
4338
4339 if (E->getObjectKind() == OK_BitField) {
4340 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4341 << 1 << E->getSourceRange();
4342 return true;
4343 }
4344
4345 ValueDecl *D = nullptr;
4346 Expr *Inner = E->IgnoreParens();
4347 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4348 D = DRE->getDecl();
4349 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4350 D = ME->getMemberDecl();
4351 }
4352
4353 // If it's a field, require the containing struct to have a
4354 // complete definition so that we can compute the layout.
4355 //
4356 // This can happen in C++11 onwards, either by naming the member
4357 // in a way that is not transformed into a member access expression
4358 // (in an unevaluated operand, for instance), or by naming the member
4359 // in a trailing-return-type.
4360 //
4361 // For the record, since __alignof__ on expressions is a GCC
4362 // extension, GCC seems to permit this but always gives the
4363 // nonsensical answer 0.
4364 //
4365 // We don't really need the layout here --- we could instead just
4366 // directly check for all the appropriate alignment-lowing
4367 // attributes --- but that would require duplicating a lot of
4368 // logic that just isn't worth duplicating for such a marginal
4369 // use-case.
4370 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4371 // Fast path this check, since we at least know the record has a
4372 // definition if we can find a member of it.
4373 if (!FD->getParent()->isCompleteDefinition()) {
4374 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4375 << E->getSourceRange();
4376 return true;
4377 }
4378
4379 // Otherwise, if it's a field, and the field doesn't have
4380 // reference type, then it must have a complete type (or be a
4381 // flexible array member, which we explicitly want to
4382 // white-list anyway), which makes the following checks trivial.
4383 if (!FD->getType()->isReferenceType())
4384 return false;
4385 }
4386
4387 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4388}
4389
4391 E = E->IgnoreParens();
4392
4393 // Cannot know anything else if the expression is dependent.
4394 if (E->isTypeDependent())
4395 return false;
4396
4397 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4398}
4399
4401 CapturingScopeInfo *CSI) {
4402 assert(T->isVariablyModifiedType());
4403 assert(CSI != nullptr);
4404
4405 // We're going to walk down into the type and look for VLA expressions.
4406 do {
4407 const Type *Ty = T.getTypePtr();
4408 switch (Ty->getTypeClass()) {
4409#define TYPE(Class, Base)
4410#define ABSTRACT_TYPE(Class, Base)
4411#define NON_CANONICAL_TYPE(Class, Base)
4412#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4413#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4414#include "clang/AST/TypeNodes.inc"
4415 T = QualType();
4416 break;
4417 // These types are never variably-modified.
4418 case Type::Builtin:
4419 case Type::Complex:
4420 case Type::Vector:
4421 case Type::ExtVector:
4422 case Type::ConstantMatrix:
4423 case Type::Record:
4424 case Type::Enum:
4425 case Type::TemplateSpecialization:
4426 case Type::ObjCObject:
4427 case Type::ObjCInterface:
4428 case Type::ObjCObjectPointer:
4429 case Type::ObjCTypeParam:
4430 case Type::Pipe:
4431 case Type::BitInt:
4432 llvm_unreachable("type class is never variably-modified!");
4433 case Type::Elaborated:
4434 T = cast<ElaboratedType>(Ty)->getNamedType();
4435 break;
4436 case Type::Adjusted:
4437 T = cast<AdjustedType>(Ty)->getOriginalType();
4438 break;
4439 case Type::Decayed:
4440 T = cast<DecayedType>(Ty)->getPointeeType();
4441 break;
4442 case Type::ArrayParameter:
4443 T = cast<ArrayParameterType>(Ty)->getElementType();
4444 break;
4445 case Type::Pointer:
4446 T = cast<PointerType>(Ty)->getPointeeType();
4447 break;
4448 case Type::BlockPointer:
4449 T = cast<BlockPointerType>(Ty)->getPointeeType();
4450 break;
4451 case Type::LValueReference:
4452 case Type::RValueReference:
4453 T = cast<ReferenceType>(Ty)->getPointeeType();
4454 break;
4455 case Type::MemberPointer:
4456 T = cast<MemberPointerType>(Ty)->getPointeeType();
4457 break;
4458 case Type::ConstantArray:
4459 case Type::IncompleteArray:
4460 // Losing element qualification here is fine.
4461 T = cast<ArrayType>(Ty)->getElementType();
4462 break;
4463 case Type::VariableArray: {
4464 // Losing element qualification here is fine.
4465 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4466
4467 // Unknown size indication requires no size computation.
4468 // Otherwise, evaluate and record it.
4469 auto Size = VAT->getSizeExpr();
4470 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4471 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4472 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4473
4474 T = VAT->getElementType();
4475 break;
4476 }
4477 case Type::FunctionProto:
4478 case Type::FunctionNoProto:
4479 T = cast<FunctionType>(Ty)->getReturnType();
4480 break;
4481 case Type::Paren:
4482 case Type::TypeOf:
4483 case Type::UnaryTransform:
4484 case Type::Attributed:
4485 case Type::BTFTagAttributed:
4486 case Type::HLSLAttributedResource:
4487 case Type::SubstTemplateTypeParm:
4488 case Type::MacroQualified:
4489 case Type::CountAttributed:
4490 // Keep walking after single level desugaring.
4491 T = T.getSingleStepDesugaredType(Context);
4492 break;
4493 case Type::Typedef:
4494 T = cast<TypedefType>(Ty)->desugar();
4495 break;
4496 case Type::Decltype:
4497 T = cast<DecltypeType>(Ty)->desugar();
4498 break;
4499 case Type::PackIndexing:
4500 T = cast<PackIndexingType>(Ty)->desugar();
4501 break;
4502 case Type::Using:
4503 T = cast<UsingType>(Ty)->desugar();
4504 break;
4505 case Type::Auto:
4506 case Type::DeducedTemplateSpecialization:
4507 T = cast<DeducedType>(Ty)->getDeducedType();
4508 break;
4509 case Type::TypeOfExpr:
4510 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4511 break;
4512 case Type::Atomic:
4513 T = cast<AtomicType>(Ty)->getValueType();
4514 break;
4515 }
4516 } while (!T.isNull() && T->isVariablyModifiedType());
4517}
4518
4520 SourceLocation OpLoc,
4521 SourceRange ExprRange,
4522 UnaryExprOrTypeTrait ExprKind,
4523 StringRef KWName) {
4524 if (ExprType->isDependentType())
4525 return false;
4526
4527 // C++ [expr.sizeof]p2:
4528 // When applied to a reference or a reference type, the result
4529 // is the size of the referenced type.
4530 // C++11 [expr.alignof]p3:
4531 // When alignof is applied to a reference type, the result
4532 // shall be the alignment of the referenced type.
4533 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4534 ExprType = Ref->getPointeeType();
4535
4536 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4537 // When alignof or _Alignof is applied to an array type, the result
4538 // is the alignment of the element type.
4539 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4540 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4541 // If the trait is 'alignof' in C before C2y, the ability to apply the
4542 // trait to an incomplete array is an extension.
4543 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4544 ExprType->isIncompleteArrayType())
4545 Diag(OpLoc, getLangOpts().C2y
4546 ? diag::warn_c2y_compat_alignof_incomplete_array
4547 : diag::ext_c2y_alignof_incomplete_array);
4548 ExprType = Context.getBaseElementType(ExprType);
4549 }
4550
4551 if (ExprKind == UETT_VecStep)
4552 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4553
4554 if (ExprKind == UETT_VectorElements)
4555 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4556 ExprRange);
4557
4558 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4559 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4560 ExprRange);
4561
4562 // Explicitly list some types as extensions.
4563 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4564 ExprKind))
4565 return false;
4566
4568 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4569 KWName, ExprRange))
4570 return true;
4571
4572 if (ExprType->isFunctionType()) {
4573 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4574 return true;
4575 }
4576
4577 // WebAssembly tables are always illegal operands to unary expressions and
4578 // type traits.
4579 if (Context.getTargetInfo().getTriple().isWasm() &&
4580 ExprType->isWebAssemblyTableType()) {
4581 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4582 << getTraitSpelling(ExprKind);
4583 return true;
4584 }
4585
4586 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4587 ExprKind))
4588 return true;
4589
4590 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4591 if (auto *TT = ExprType->getAs<TypedefType>()) {
4592 for (auto I = FunctionScopes.rbegin(),
4593 E = std::prev(FunctionScopes.rend());
4594 I != E; ++I) {
4595 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4596 if (CSI == nullptr)
4597 break;
4598 DeclContext *DC = nullptr;
4599 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4600 DC = LSI->CallOperator;
4601 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4602 DC = CRSI->TheCapturedDecl;
4603 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4604 DC = BSI->TheDecl;
4605 if (DC) {
4606 if (DC->containsDecl(TT->getDecl()))
4607 break;
4608 captureVariablyModifiedType(Context, ExprType, CSI);
4609 }
4610 }
4611 }
4612 }
4613
4614 return false;
4615}
4616
4618 SourceLocation OpLoc,
4619 UnaryExprOrTypeTrait ExprKind,
4620 SourceRange R) {
4621 if (!TInfo)
4622 return ExprError();
4623
4624 QualType T = TInfo->getType();
4625
4626 if (!T->isDependentType() &&
4627 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4628 getTraitSpelling(ExprKind)))
4629 return ExprError();
4630
4631 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4632 // properly deal with VLAs in nested calls of sizeof and typeof.
4633 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4634 TInfo->getType()->isVariablyModifiedType())
4635 TInfo = TransformToPotentiallyEvaluated(TInfo);
4636
4637 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4638 return new (Context) UnaryExprOrTypeTraitExpr(
4639 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4640}
4641
4644 UnaryExprOrTypeTrait ExprKind) {
4646 if (PE.isInvalid())
4647 return ExprError();
4648
4649 E = PE.get();
4650
4651 // Verify that the operand is valid.
4652 bool isInvalid = false;
4653 if (E->isTypeDependent()) {
4654 // Delay type-checking for type-dependent expressions.
4655 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4656 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4657 } else if (ExprKind == UETT_VecStep) {
4659 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4660 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4661 isInvalid = true;
4662 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4663 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4664 isInvalid = true;
4665 } else if (ExprKind == UETT_VectorElements) {
4666 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements);
4667 } else {
4669 }
4670
4671 if (isInvalid)
4672 return ExprError();
4673
4674 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4676 if (PE.isInvalid()) return ExprError();
4677 E = PE.get();
4678 }
4679
4680 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4681 return new (Context) UnaryExprOrTypeTraitExpr(
4682 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4683}
4684
4687 UnaryExprOrTypeTrait ExprKind, bool IsType,
4688 void *TyOrEx, SourceRange ArgRange) {
4689 // If error parsing type, ignore.
4690 if (!TyOrEx) return ExprError();
4691
4692 if (IsType) {
4693 TypeSourceInfo *TInfo;
4694 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4695 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4696 }
4697
4698 Expr *ArgEx = (Expr *)TyOrEx;
4699 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4700 return Result;
4701}
4702
4704 SourceLocation OpLoc, SourceRange R) {
4705 if (!TInfo)
4706 return true;
4707 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4708 UETT_AlignOf, KWName);
4709}
4710
4712 SourceLocation OpLoc, SourceRange R) {
4713 TypeSourceInfo *TInfo;
4715 &TInfo);
4716 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4717}
4718
4720 bool IsReal) {
4721 if (V.get()->isTypeDependent())
4722 return S.Context.DependentTy;
4723
4724 // _Real and _Imag are only l-values for normal l-values.
4725 if (V.get()->getObjectKind() != OK_Ordinary) {
4726 V = S.DefaultLvalueConversion(V.get());
4727 if (V.isInvalid())
4728 return QualType();
4729 }
4730
4731 // These operators return the element type of a complex type.
4732 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4733 return CT->getElementType();
4734
4735 // Otherwise they pass through real integer and floating point types here.
4736 if (V.get()->getType()->isArithmeticType())
4737 return V.get()->getType();
4738
4739 // Test for placeholders.
4740 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4741 if (PR.isInvalid()) return QualType();
4742 if (PR.get() != V.get()) {
4743 V = PR;
4744 return CheckRealImagOperand(S, V, Loc, IsReal);
4745 }
4746
4747 // Reject anything else.
4748 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4749 << (IsReal ? "__real" : "__imag");
4750 return QualType();
4751}
4752
4753
4754
4757 tok::TokenKind Kind, Expr *Input) {
4759 switch (Kind) {
4760 default: llvm_unreachable("Unknown unary op!");
4761 case tok::plusplus: Opc = UO_PostInc; break;
4762 case tok::minusminus: Opc = UO_PostDec; break;
4763 }
4764
4765 // Since this might is a postfix expression, get rid of ParenListExprs.
4767 if (Result.isInvalid()) return ExprError();
4768 Input = Result.get();
4769
4770 return BuildUnaryOp(S, OpLoc, Opc, Input);
4771}
4772
4773/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4774///
4775/// \return true on error
4777 SourceLocation opLoc,
4778 Expr *op) {
4779 assert(op->getType()->isObjCObjectPointerType());
4781 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4782 return false;
4783
4784 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4786 << op->getSourceRange();
4787 return true;
4788}
4789
4791 auto *BaseNoParens = Base->IgnoreParens();
4792 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4793 return MSProp->getPropertyDecl()->getType()->isArrayType();
4794 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4795}
4796
4797// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4798// Typically this is DependentTy, but can sometimes be more precise.
4799//
4800// There are cases when we could determine a non-dependent type:
4801// - LHS and RHS may have non-dependent types despite being type-dependent
4802// (e.g. unbounded array static members of the current instantiation)
4803// - one may be a dependent-sized array with known element type
4804// - one may be a dependent-typed valid index (enum in current instantiation)
4805//
4806// We *always* return a dependent type, in such cases it is DependentTy.
4807// This avoids creating type-dependent expressions with non-dependent types.
4808// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4810 const ASTContext &Ctx) {
4811 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4812 QualType LTy = LHS->getType(), RTy = RHS->getType();
4814 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4815 if (const PointerType *PT = LTy->getAs<PointerType>())
4816 Result = PT->getPointeeType();
4817 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4818 Result = AT->getElementType();
4819 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4820 if (const PointerType *PT = RTy->getAs<PointerType>())
4821 Result = PT->getPointeeType();
4822 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4823 Result = AT->getElementType();
4824 }
4825 // Ensure we return a dependent type.
4826 return Result->isDependentType() ? Result : Ctx.DependentTy;
4827}
4828
4830 SourceLocation lbLoc,
4831 MultiExprArg ArgExprs,
4832 SourceLocation rbLoc) {
4833
4834 if (base && !base->getType().isNull() &&
4835 base->hasPlaceholderType(BuiltinType::ArraySection)) {
4836 auto *AS = cast<ArraySectionExpr>(base);
4837 if (AS->isOMPArraySection())
4839 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
4840 /*Length*/ nullptr,
4841 /*Stride=*/nullptr, rbLoc);
4842
4843 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
4844 SourceLocation(), /*Length*/ nullptr,
4845 rbLoc);
4846 }
4847
4848 // Since this might be a postfix expression, get rid of ParenListExprs.
4849 if (isa<ParenListExpr>(base)) {
4851 if (result.isInvalid())
4852 return ExprError();
4853 base = result.get();
4854 }
4855
4856 // Check if base and idx form a MatrixSubscriptExpr.
4857 //
4858 // Helper to check for comma expressions, which are not allowed as indices for
4859 // matrix subscript expressions.
4860 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4861 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4862 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4863 << SourceRange(base->getBeginLoc(), rbLoc);
4864 return true;
4865 }
4866 return false;
4867 };
4868 // The matrix subscript operator ([][])is considered a single operator.
4869 // Separating the index expressions by parenthesis is not allowed.
4870 if (base && !base->getType().isNull() &&
4871 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4872 !isa<MatrixSubscriptExpr>(base)) {
4873 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4874 << SourceRange(base->getBeginLoc(), rbLoc);
4875 return ExprError();
4876 }
4877 // If the base is a MatrixSubscriptExpr, try to create a new
4878 // MatrixSubscriptExpr.
4879 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4880 if (matSubscriptE) {
4881 assert(ArgExprs.size() == 1);
4882 if (CheckAndReportCommaError(ArgExprs.front()))
4883 return ExprError();
4884
4885 assert(matSubscriptE->isIncomplete() &&
4886 "base has to be an incomplete matrix subscript");
4887 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4888 matSubscriptE->getRowIdx(),
4889 ArgExprs.front(), rbLoc);
4890 }
4891 if (base->getType()->isWebAssemblyTableType()) {
4892 Diag(base->getExprLoc(), diag::err_wasm_table_art)
4893 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
4894 return ExprError();
4895 }
4896
4897 CheckInvalidBuiltinCountedByRef(base, ArraySubscriptKind);
4898
4899 // Handle any non-overload placeholder types in the base and index
4900 // expressions. We can't handle overloads here because the other
4901 // operand might be an overloadable type, in which case the overload
4902 // resolution for the operator overload should get the first crack
4903 // at the overload.
4904 bool IsMSPropertySubscript = false;
4905 if (base->getType()->isNonOverloadPlaceholderType()) {
4906 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4907 if (!IsMSPropertySubscript) {
4908 ExprResult result = CheckPlaceholderExpr(base);
4909 if (result.isInvalid())
4910 return ExprError();
4911 base = result.get();
4912 }
4913 }
4914
4915 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4916 if (base->getType()->isMatrixType()) {
4917 assert(ArgExprs.size() == 1);
4918 if (CheckAndReportCommaError(ArgExprs.front()))
4919 return ExprError();
4920
4921 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4922 rbLoc);
4923 }
4924
4925 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4926 Expr *idx = ArgExprs[0];
4927 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4928 (isa<CXXOperatorCallExpr>(idx) &&
4929 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4930 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4931 << SourceRange(base->getBeginLoc(), rbLoc);
4932 }
4933 }
4934
4935 if (ArgExprs.size() == 1 &&
4936 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4937 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4938 if (result.isInvalid())
4939 return ExprError();
4940 ArgExprs[0] = result.get();
4941 } else {
4942 if (CheckArgsForPlaceholders(ArgExprs))
4943 return ExprError();
4944 }
4945
4946 // Build an unanalyzed expression if either operand is type-dependent.
4947 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4948 (base->isTypeDependent() ||
4950 !isa<PackExpansionExpr>(ArgExprs[0])) {
4951 return new (Context) ArraySubscriptExpr(
4952 base, ArgExprs.front(),
4953 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4954 VK_LValue, OK_Ordinary, rbLoc);
4955 }
4956
4957 // MSDN, property (C++)
4958 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4959 // This attribute can also be used in the declaration of an empty array in a
4960 // class or structure definition. For example:
4961 // __declspec(property(get=GetX, put=PutX)) int x[];
4962 // The above statement indicates that x[] can be used with one or more array
4963 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4964 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4965 if (IsMSPropertySubscript) {
4966 assert(ArgExprs.size() == 1);
4967 // Build MS property subscript expression if base is MS property reference
4968 // or MS property subscript.
4969 return new (Context)
4970 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4971 VK_LValue, OK_Ordinary, rbLoc);
4972 }
4973
4974 // Use C++ overloaded-operator rules if either operand has record
4975 // type. The spec says to do this if either type is *overloadable*,
4976 // but enum types can't declare subscript operators or conversion
4977 // operators, so there's nothing interesting for overload resolution
4978 // to do if there aren't any record types involved.
4979 //
4980 // ObjC pointers have their own subscripting logic that is not tied
4981 // to overload resolution and so should not take this path.
4982 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4983 ((base->getType()->isRecordType() ||
4984 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
4985 ArgExprs[0]->getType()->isRecordType())))) {
4986 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4987 }
4988
4989 ExprResult Res =
4990 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4991
4992 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4993 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4994
4995 return Res;
4996}
4997
5000 InitializationKind Kind =
5002 InitializationSequence InitSeq(*this, Entity, Kind, E);
5003 return InitSeq.Perform(*this, Entity, Kind, E);
5004}
5005
5007 Expr *ColumnIdx,
5008 SourceLocation RBLoc) {
5010 if (BaseR.isInvalid())
5011 return BaseR;
5012 Base = BaseR.get();
5013
5014 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5015 if (RowR.isInvalid())
5016 return RowR;
5017 RowIdx = RowR.get();
5018
5019 if (!ColumnIdx)
5020 return new (Context) MatrixSubscriptExpr(
5021 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5022
5023 // Build an unanalyzed expression if any of the operands is type-dependent.
5024 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5025 ColumnIdx->isTypeDependent())
5026 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5027 Context.DependentTy, RBLoc);
5028
5029 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5030 if (ColumnR.isInvalid())
5031 return ColumnR;
5032 ColumnIdx = ColumnR.get();
5033
5034 // Check that IndexExpr is an integer expression. If it is a constant
5035 // expression, check that it is less than Dim (= the number of elements in the
5036 // corresponding dimension).
5037 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5038 bool IsColumnIdx) -> Expr * {
5039 if (!IndexExpr->getType()->isIntegerType() &&
5040 !IndexExpr->isTypeDependent()) {
5041 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5042 << IsColumnIdx;
5043 return nullptr;
5044 }
5045
5046 if (std::optional<llvm::APSInt> Idx =
5047 IndexExpr->getIntegerConstantExpr(Context)) {
5048 if ((*Idx < 0 || *Idx >= Dim)) {
5049 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5050 << IsColumnIdx << Dim;
5051 return nullptr;
5052 }
5053 }
5054
5055 ExprResult ConvExpr = IndexExpr;
5056 assert(!ConvExpr.isInvalid() &&
5057 "should be able to convert any integer type to size type");
5058 return ConvExpr.get();
5059 };
5060
5061 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5062 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5063 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5064 if (!RowIdx || !ColumnIdx)
5065 return ExprError();
5066
5067 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5068 MTy->getElementType(), RBLoc);
5069}
5070
5071void Sema::CheckAddressOfNoDeref(const Expr *E) {
5072 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5073 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5074
5075 // For expressions like `&(*s).b`, the base is recorded and what should be
5076 // checked.
5077 const MemberExpr *Member = nullptr;
5078 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5079 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5080
5081 LastRecord.PossibleDerefs.erase(StrippedExpr);
5082}
5083
5084void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5086 return;
5087
5088 QualType ResultTy = E->getType();
5089 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5090
5091 // Bail if the element is an array since it is not memory access.
5092 if (isa<ArrayType>(ResultTy))
5093 return;
5094
5095 if (ResultTy->hasAttr(attr::NoDeref)) {
5096 LastRecord.PossibleDerefs.insert(E);
5097 return;
5098 }
5099
5100 // Check if the base type is a pointer to a member access of a struct
5101 // marked with noderef.
5102 const Expr *Base = E->getBase();
5103 QualType BaseTy = Base->getType();
5104 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5105 // Not a pointer access
5106 return;
5107
5108 const MemberExpr *Member = nullptr;
5109 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5110 Member->isArrow())
5111 Base = Member->getBase();
5112
5113 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5114 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5115 LastRecord.PossibleDerefs.insert(E);
5116 }
5117}
5118
5121 Expr *Idx, SourceLocation RLoc) {
5122 Expr *LHSExp = Base;
5123 Expr *RHSExp = Idx;
5124
5127
5128 // Per C++ core issue 1213, the result is an xvalue if either operand is
5129 // a non-lvalue array, and an lvalue otherwise.
5130 if (getLangOpts().CPlusPlus11) {
5131 for (auto *Op : {LHSExp, RHSExp}) {
5132 Op = Op->IgnoreImplicit();
5133 if (Op->getType()->isArrayType() && !Op->isLValue())
5134 VK = VK_XValue;
5135 }
5136 }
5137
5138 // Perform default conversions.
5139 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5141 if (Result.isInvalid())
5142 return ExprError();
5143 LHSExp = Result.get();
5144 }
5146 if (Result.isInvalid())
5147 return ExprError();
5148 RHSExp = Result.get();
5149
5150 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5151
5152 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5153 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5154 // in the subscript position. As a result, we need to derive the array base
5155 // and index from the expression types.
5156 Expr *BaseExpr, *IndexExpr;
5157 QualType ResultType;
5158 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5159 BaseExpr = LHSExp;
5160 IndexExpr = RHSExp;
5161 ResultType =
5163 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5164 BaseExpr = LHSExp;
5165 IndexExpr = RHSExp;
5166 ResultType = PTy->getPointeeType();
5167 } else if (const ObjCObjectPointerType *PTy =
5168 LHSTy->getAs<ObjCObjectPointerType>()) {
5169 BaseExpr = LHSExp;
5170 IndexExpr = RHSExp;
5171
5172 // Use custom logic if this should be the pseudo-object subscript
5173 // expression.
5175 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5176 nullptr, nullptr);
5177
5178 ResultType = PTy->getPointeeType();
5179 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5180 // Handle the uncommon case of "123[Ptr]".
5181 BaseExpr = RHSExp;
5182 IndexExpr = LHSExp;
5183 ResultType = PTy->getPointeeType();
5184 } else if (const ObjCObjectPointerType *PTy =
5185 RHSTy->getAs<ObjCObjectPointerType>()) {
5186 // Handle the uncommon case of "123[Ptr]".
5187 BaseExpr = RHSExp;
5188 IndexExpr = LHSExp;
5189 ResultType = PTy->getPointeeType();
5191 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5192 << ResultType << BaseExpr->getSourceRange();
5193 return ExprError();
5194 }
5195 } else if (LHSTy->isSubscriptableVectorType()) {
5196 if (LHSTy->isBuiltinType() &&
5197 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5198 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5199 if (BTy->isSVEBool())
5200 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5201 << LHSExp->getSourceRange()
5202 << RHSExp->getSourceRange());
5203 ResultType = BTy->getSveEltType(Context);
5204 } else {
5205 const VectorType *VTy = LHSTy->getAs<VectorType>();
5206 ResultType = VTy->getElementType();
5207 }
5208 BaseExpr = LHSExp; // vectors: V[123]
5209 IndexExpr = RHSExp;
5210 // We apply C++ DR1213 to vector subscripting too.
5211 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5212 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5213 if (Materialized.isInvalid())
5214 return ExprError();
5215 LHSExp = Materialized.get();
5216 }
5217 VK = LHSExp->getValueKind();
5218 if (VK != VK_PRValue)
5219 OK = OK_VectorComponent;
5220
5221 QualType BaseType = BaseExpr->getType();
5222 Qualifiers BaseQuals = BaseType.getQualifiers();
5223 Qualifiers MemberQuals = ResultType.getQualifiers();
5224 Qualifiers Combined = BaseQuals + MemberQuals;
5225 if (Combined != MemberQuals)
5226 ResultType = Context.getQualifiedType(ResultType, Combined);
5227 } else if (LHSTy->isArrayType()) {
5228 // If we see an array that wasn't promoted by
5229 // DefaultFunctionArrayLvalueConversion, it must be an array that
5230 // wasn't promoted because of the C90 rule that doesn't
5231 // allow promoting non-lvalue arrays. Warn, then
5232 // force the promotion here.
5233 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5234 << LHSExp->getSourceRange();
5235 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5236 CK_ArrayToPointerDecay).get();
5237 LHSTy = LHSExp->getType();
5238
5239 BaseExpr = LHSExp;
5240 IndexExpr = RHSExp;
5241 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5242 } else if (RHSTy->isArrayType()) {
5243 // Same as previous, except for 123[f().a] case
5244 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5245 << RHSExp->getSourceRange();
5246 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5247 CK_ArrayToPointerDecay).get();
5248 RHSTy = RHSExp->getType();
5249
5250 BaseExpr = RHSExp;
5251 IndexExpr = LHSExp;
5252 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5253 } else {
5254 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5255 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5256 }
5257 // C99 6.5.2.1p1
5258 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5259 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5260 << IndexExpr->getSourceRange());
5261
5262 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5263 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5264 !IndexExpr->isTypeDependent()) {
5265 std::optional<llvm::APSInt> IntegerContantExpr =
5267 if (!IntegerContantExpr.has_value() ||
5268 IntegerContantExpr.value().isNegative())
5269 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5270 }
5271
5272 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5273 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5274 // type. Note that Functions are not objects, and that (in C99 parlance)
5275 // incomplete types are not object types.
5276 if (ResultType->isFunctionType()) {
5277 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5278 << ResultType << BaseExpr->getSourceRange();
5279 return ExprError();
5280 }
5281
5282 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5283 // GNU extension: subscripting on pointer to void
5284 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5285 << BaseExpr->getSourceRange();
5286
5287 // C forbids expressions of unqualified void type from being l-values.
5288 // See IsCForbiddenLValueType.
5289 if (!ResultType.hasQualifiers())
5290 VK = VK_PRValue;
5291 } else if (!ResultType->isDependentType() &&
5292 !ResultType.isWebAssemblyReferenceType() &&
5294 LLoc, ResultType,
5295 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5296 return ExprError();
5297
5298 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5299 !ResultType.isCForbiddenLValueType());
5300
5302 FunctionScopes.size() > 1) {
5303 if (auto *TT =
5304 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5305 for (auto I = FunctionScopes.rbegin(),
5306 E = std::prev(FunctionScopes.rend());
5307 I != E; ++I) {
5308 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5309 if (CSI == nullptr)
5310 break;
5311 DeclContext *DC = nullptr;
5312 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5313 DC = LSI->CallOperator;
5314 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5315 DC = CRSI->TheCapturedDecl;
5316 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5317 DC = BSI->TheDecl;
5318 if (DC) {
5319 if (DC->containsDecl(TT->getDecl()))
5320 break;
5322 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5323 }
5324 }
5325 }
5326 }
5327
5328 return new (Context)
5329 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5330}
5331
5333 ParmVarDecl *Param, Expr *RewrittenInit,
5334 bool SkipImmediateInvocations) {
5335 if (Param->hasUnparsedDefaultArg()) {
5336 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5337 // If we've already cleared out the location for the default argument,
5338 // that means we're parsing it right now.
5339 if (!UnparsedDefaultArgLocs.count(Param)) {
5340 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5341 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5342 Param->setInvalidDecl();
5343 return true;
5344 }
5345
5346 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5347 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5349 diag::note_default_argument_declared_here);
5350 return true;
5351 }
5352
5353 if (Param->hasUninstantiatedDefaultArg()) {
5354 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5355 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5356 return true;
5357 }
5358
5359 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5360 assert(Init && "default argument but no initializer?");
5361
5362 // If the default expression creates temporaries, we need to
5363 // push them to the current stack of expression temporaries so they'll
5364 // be properly destroyed.
5365 // FIXME: We should really be rebuilding the default argument with new
5366 // bound temporaries; see the comment in PR5810.
5367 // We don't need to do that with block decls, though, because
5368 // blocks in default argument expression can never capture anything.
5369 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5370 // Set the "needs cleanups" bit regardless of whether there are
5371 // any explicit objects.
5372 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5373 // Append all the objects to the cleanup list. Right now, this
5374 // should always be a no-op, because blocks in default argument
5375 // expressions should never be able to capture anything.
5376 assert(!InitWithCleanup->getNumObjects() &&
5377 "default argument expression has capturing blocks?");
5378 }
5379 // C++ [expr.const]p15.1:
5380 // An expression or conversion is in an immediate function context if it is
5381 // potentially evaluated and [...] its innermost enclosing non-block scope
5382 // is a function parameter scope of an immediate function.
5384 *this,
5388 Param);
5389 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5390 SkipImmediateInvocations;
5391 runWithSufficientStackSpace(CallLoc, [&] {
5392 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5393 });
5394 return false;
5395}
5396
5399 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {
5400 ShouldVisitImplicitCode = true;
5401 }
5402
5403 bool HasImmediateCalls = false;
5404
5405 bool VisitCallExpr(CallExpr *E) override {
5406 if (const FunctionDecl *FD = E->getDirectCallee())
5407 HasImmediateCalls |= FD->isImmediateFunction();
5409 }
5410
5412 if (const FunctionDecl *FD = E->getConstructor())
5413 HasImmediateCalls |= FD->isImmediateFunction();
5415 }
5416
5417 // SourceLocExpr are not immediate invocations
5418 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5419 // need to be rebuilt so that they refer to the correct SourceLocation and
5420 // DeclContext.
5422 HasImmediateCalls = true;
5424 }
5425
5426 // A nested lambda might have parameters with immediate invocations
5427 // in their default arguments.
5428 // The compound statement is not visited (as it does not constitute a
5429 // subexpression).
5430 // FIXME: We should consider visiting and transforming captures
5431 // with init expressions.
5432 bool VisitLambdaExpr(LambdaExpr *E) override {
5433 return VisitCXXMethodDecl(E->getCallOperator());
5434 }
5435
5437 return TraverseStmt(E->getExpr());
5438 }
5439
5441 return TraverseStmt(E->getExpr());
5442 }
5443};
5444
5446 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5448 : TreeTransform(SemaRef) {}
5449
5450 bool AlwaysRebuild() { return true; }
5451
5452 // Lambda can only have immediate invocations in the default
5453 // args of their parameters, which is transformed upon calling the closure.
5454 // The body is not a subexpression, so we have nothing to do.
5455 // FIXME: Immediate calls in capture initializers should be transformed.
5458
5459 // Make sure we don't rebuild the this pointer as it would
5460 // cause it to incorrectly point it to the outermost class
5461 // in the case of nested struct initialization.
5463
5464 // Rewrite to source location to refer to the context in which they are used.
5466 DeclContext *DC = E->getParentContext();
5467 if (DC == SemaRef.CurContext)
5468 return E;
5469
5470 // FIXME: During instantiation, because the rebuild of defaults arguments
5471 // is not always done in the context of the template instantiator,
5472 // we run the risk of producing a dependent source location
5473 // that would never be rebuilt.
5474 // This usually happens during overload resolution, or in contexts
5475 // where the value of the source location does not matter.
5476 // However, we should find a better way to deal with source location
5477 // of function templates.
5478 if (!SemaRef.CurrentInstantiationScope ||
5479 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5480 DC = SemaRef.CurContext;
5481
5482 return getDerived().RebuildSourceLocExpr(
5483 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5484 }
5485};
5486
5488 FunctionDecl *FD, ParmVarDecl *Param,
5489 Expr *Init) {
5490 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5491
5492 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5493 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5494 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5495 InitializationContext =
5497 if (!InitializationContext.has_value())
5498 InitializationContext.emplace(CallLoc, Param, CurContext);
5499
5500 if (!Init && !Param->hasUnparsedDefaultArg()) {
5501 // Mark that we are replacing a default argument first.
5502 // If we are instantiating a template we won't have to
5503 // retransform immediate calls.
5504 // C++ [expr.const]p15.1:
5505 // An expression or conversion is in an immediate function context if it
5506 // is potentially evaluated and [...] its innermost enclosing non-block
5507 // scope is a function parameter scope of an immediate function.
5509 *this,
5513 Param);
5514
5515 if (Param->hasUninstantiatedDefaultArg()) {
5516 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5517 return ExprError();
5518 }
5519 // CWG2631
5520 // An immediate invocation that is not evaluated where it appears is
5521 // evaluated and checked for whether it is a constant expression at the
5522 // point where the enclosing initializer is used in a function call.
5524 if (!NestedDefaultChecking)
5525 V.TraverseDecl(Param);
5526
5527 // Rewrite the call argument that was created from the corresponding
5528 // parameter's default argument.
5529 if (V.HasImmediateCalls ||
5530 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5531 if (V.HasImmediateCalls)
5532 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5533 CallLoc, Param, CurContext};
5534 // Pass down lifetime extending flag, and collect temporaries in
5535 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5539 ExprResult Res;
5540 runWithSufficientStackSpace(CallLoc, [&] {
5541 Res = Immediate.TransformInitializer(Param->getInit(),
5542 /*NotCopy=*/false);
5543 });
5544 if (Res.isInvalid())
5545 return ExprError();
5546 Res = ConvertParamDefaultArgument(Param, Res.get(),
5547 Res.get()->getBeginLoc());
5548 if (Res.isInvalid())
5549 return ExprError();
5550 Init = Res.get();
5551 }
5552 }
5553
5555 CallLoc, FD, Param, Init,
5556 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5557 return ExprError();
5558
5559 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5560 Init, InitializationContext->Context);
5561}
5562
5564 FieldDecl *Field) {
5565 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5566 return Pattern;
5567 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5568 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5570 ClassPattern->lookup(Field->getDeclName());
5571 auto Rng = llvm::make_filter_range(
5572 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5573 if (Rng.empty())
5574 return nullptr;
5575 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5576 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5577 // && "Duplicated instantiation pattern for field decl");
5578 return cast<FieldDecl>(*Rng.begin());
5579}
5580
5582 assert(Field->hasInClassInitializer());
5583
5584 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5585
5586 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5587
5588 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5589 InitializationContext =
5591 if (!InitializationContext.has_value())
5592 InitializationContext.emplace(Loc, Field, CurContext);
5593
5594 Expr *Init = nullptr;
5595
5596 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5597 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5600
5601 if (!Field->getInClassInitializer()) {
5602 // Maybe we haven't instantiated the in-class initializer. Go check the
5603 // pattern FieldDecl to see if it has one.
5604 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5605 FieldDecl *Pattern =
5607 assert(Pattern && "We must have set the Pattern!");
5608 if (!Pattern->hasInClassInitializer() ||
5609 InstantiateInClassInitializer(Loc, Field, Pattern,
5611 Field->setInvalidDecl();
5612 return ExprError();
5613 }
5614 }
5615 }
5616
5617 // CWG2631
5618 // An immediate invocation that is not evaluated where it appears is
5619 // evaluated and checked for whether it is a constant expression at the
5620 // point where the enclosing initializer is used in a [...] a constructor
5621 // definition, or an aggregate initialization.
5623 if (!NestedDefaultChecking)
5624 V.TraverseDecl(Field);
5625
5626 // CWG1815
5627 // Support lifetime extension of temporary created by aggregate
5628 // initialization using a default member initializer. We should rebuild
5629 // the initializer in a lifetime extension context if the initializer
5630 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5631 // extension code recurses into the default initializer and does lifetime
5632 // extension when warranted.
5633 bool ContainsAnyTemporaries =
5634 isa_and_present<ExprWithCleanups>(Field->getInClassInitializer());
5635 if (Field->getInClassInitializer() &&
5636 !Field->getInClassInitializer()->containsErrors() &&
5637 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5638 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5639 CurContext};
5640 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5641 NestedDefaultChecking;
5642 // Pass down lifetime extending flag, and collect temporaries in
5643 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5647 ExprResult Res;
5649 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5650 /*CXXDirectInit=*/false);
5651 });
5652 if (!Res.isInvalid())
5653 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5654 if (Res.isInvalid()) {
5655 Field->setInvalidDecl();
5656 return ExprError();
5657 }
5658 Init = Res.get();
5659 }
5660
5661 if (Field->getInClassInitializer()) {
5662 Expr *E = Init ? Init : Field->getInClassInitializer();
5663 if (!NestedDefaultChecking)
5665 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5666 });
5669 // C++11 [class.base.init]p7:
5670 // The initialization of each base and member constitutes a
5671 // full-expression.
5672 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5673 if (Res.isInvalid()) {
5674 Field->setInvalidDecl();
5675 return ExprError();
5676 }
5677 Init = Res.get();
5678
5679 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5680 Field, InitializationContext->Context,
5681 Init);
5682 }
5683
5684 // DR1351:
5685 // If the brace-or-equal-initializer of a non-static data member
5686 // invokes a defaulted default constructor of its class or of an
5687 // enclosing class in a potentially evaluated subexpression, the
5688 // program is ill-formed.
5689 //
5690 // This resolution is unworkable: the exception specification of the
5691 // default constructor can be needed in an unevaluated context, in
5692 // particular, in the operand of a noexcept-expression, and we can be
5693 // unable to compute an exception specification for an enclosed class.
5694 //
5695 // Any attempt to resolve the exception specification of a defaulted default
5696 // constructor before the initializer is lexically complete will ultimately
5697 // come here at which point we can diagnose it.
5698 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5699 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5700 << OutermostClass << Field;
5701 Diag(Field->getEndLoc(),
5702 diag::note_default_member_initializer_not_yet_parsed);
5703 // Recover by marking the field invalid, unless we're in a SFINAE context.
5704 if (!isSFINAEContext())
5705 Field->setInvalidDecl();
5706 return ExprError();
5707}
5708
5711 Expr *Fn) {
5712 if (Proto && Proto->isVariadic()) {
5713 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5714 return VariadicConstructor;
5715 else if (Fn && Fn->getType()->isBlockPointerType())
5716 return VariadicBlock;
5717 else if (FDecl) {
5718 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5719 if (Method->isInstance())
5720 return VariadicMethod;
5721 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5722 return VariadicMethod;
5723 return VariadicFunction;
5724 }
5725 return VariadicDoesNotApply;
5726}
5727
5728namespace {
5729class FunctionCallCCC final : public FunctionCallFilterCCC {
5730public:
5731 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5732 unsigned NumArgs, MemberExpr *ME)
5733 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5734 FunctionName(FuncName) {}
5735
5736 bool ValidateCandidate(const TypoCorrection &candidate) override {
5737 if (!candidate.getCorrectionSpecifier() ||
5738 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5739 return false;
5740 }
5741
5743 }
5744
5745 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5746 return std::make_unique<FunctionCallCCC>(*this);
5747 }
5748
5749private:
5750 const IdentifierInfo *const FunctionName;
5751};
5752}
5753
5755 FunctionDecl *FDecl,
5756 ArrayRef<Expr *> Args) {
5757 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5758 DeclarationName FuncName = FDecl->getDeclName();
5759 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5760
5761 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5762 if (TypoCorrection Corrected = S.CorrectTypo(
5764 S.getScopeForContext(S.CurContext), nullptr, CCC,
5766 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5767 if (Corrected.isOverloaded()) {
5770 for (NamedDecl *CD : Corrected) {
5771 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5773 OCS);
5774 }
5775 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5776 case OR_Success:
5777 ND = Best->FoundDecl;
5778 Corrected.setCorrectionDecl(ND);
5779 break;
5780 default:
5781 break;
5782 }
5783 }
5784 ND = ND->getUnderlyingDecl();
5785 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5786 return Corrected;
5787 }
5788 }
5789 return TypoCorrection();
5790}
5791
5792// [C++26][[expr.unary.op]/p4
5793// A pointer to member is only formed when an explicit &
5794// is used and its operand is a qualified-id not enclosed in parentheses.
5796 if (!isa<ParenExpr>(Fn))
5797 return false;
5798
5799 Fn = Fn->IgnoreParens();
5800
5801 auto *UO = dyn_cast<UnaryOperator>(Fn);
5802 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
5803 return false;
5804 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
5805 return DRE->hasQualifier();
5806 }
5807 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
5808 return OVL->getQualifier();
5809 return false;
5810}
5811
5812bool
5814 FunctionDecl *FDecl,
5815 const FunctionProtoType *Proto,
5816 ArrayRef<Expr *> Args,
5817 SourceLocation RParenLoc,
5818 bool IsExecConfig) {
5819 // Bail out early if calling a builtin with custom typechecking.
5820 if (FDecl)
5821 if (unsigned ID = FDecl->getBuiltinID())
5823 return false;
5824
5825 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5826 // assignment, to the types of the corresponding parameter, ...
5827
5828 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
5829 bool HasExplicitObjectParameter =
5830 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
5831 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
5832 unsigned NumParams = Proto->getNumParams();
5833 bool Invalid = false;
5834 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5835 unsigned FnKind = Fn->getType()->isBlockPointerType()
5836 ? 1 /* block */
5837 : (IsExecConfig ? 3 /* kernel function (exec config) */
5838 : 0 /* function */);
5839
5840 // If too few arguments are available (and we don't have default
5841 // arguments for the remaining parameters), don't make the call.
5842 if (Args.size() < NumParams) {
5843 if (Args.size() < MinArgs) {
5844 TypoCorrection TC;
5845 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5846 unsigned diag_id =
5847 MinArgs == NumParams && !Proto->isVariadic()
5848 ? diag::err_typecheck_call_too_few_args_suggest
5849 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5851 TC, PDiag(diag_id)
5852 << FnKind << MinArgs - ExplicitObjectParameterOffset
5853 << static_cast<unsigned>(Args.size()) -
5854 ExplicitObjectParameterOffset
5855 << HasExplicitObjectParameter << TC.getCorrectionRange());
5856 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
5857 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5858 ->getDeclName())
5859 Diag(RParenLoc,
5860 MinArgs == NumParams && !Proto->isVariadic()
5861 ? diag::err_typecheck_call_too_few_args_one
5862 : diag::err_typecheck_call_too_few_args_at_least_one)
5863 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5864 << HasExplicitObjectParameter << Fn->getSourceRange();
5865 else
5866 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5867 ? diag::err_typecheck_call_too_few_args
5868 : diag::err_typecheck_call_too_few_args_at_least)
5869 << FnKind << MinArgs - ExplicitObjectParameterOffset
5870 << static_cast<unsigned>(Args.size()) -
5871 ExplicitObjectParameterOffset
5872 << HasExplicitObjectParameter << Fn->getSourceRange();
5873
5874 // Emit the location of the prototype.
5875 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5876 Diag(FDecl->getLocation(), diag::note_callee_decl)
5877 << FDecl << FDecl->getParametersSourceRange();
5878
5879 return true;
5880 }
5881 // We reserve space for the default arguments when we create
5882 // the call expression, before calling ConvertArgumentsForCall.
5883 assert((Call->getNumArgs() == NumParams) &&
5884 "We should have reserved space for the default arguments before!");
5885 }
5886
5887 // If too many are passed and not variadic, error on the extras and drop
5888 // them.
5889 if (Args.size() > NumParams) {
5890 if (!Proto->isVariadic()) {
5891 TypoCorrection TC;
5892 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5893 unsigned diag_id =
5894 MinArgs == NumParams && !Proto->isVariadic()
5895 ? diag::err_typecheck_call_too_many_args_suggest
5896 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5898 TC, PDiag(diag_id)
5899 << FnKind << NumParams - ExplicitObjectParameterOffset
5900 << static_cast<unsigned>(Args.size()) -
5901 ExplicitObjectParameterOffset
5902 << HasExplicitObjectParameter << TC.getCorrectionRange());
5903 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
5904 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5905 ->getDeclName())
5906 Diag(Args[NumParams]->getBeginLoc(),
5907 MinArgs == NumParams
5908 ? diag::err_typecheck_call_too_many_args_one
5909 : diag::err_typecheck_call_too_many_args_at_most_one)
5910 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5911 << static_cast<unsigned>(Args.size()) -
5912 ExplicitObjectParameterOffset
5913 << HasExplicitObjectParameter << Fn->getSourceRange()
5914 << SourceRange(Args[NumParams]->getBeginLoc(),
5915 Args.back()->getEndLoc());
5916 else
5917 Diag(Args[NumParams]->getBeginLoc(),
5918 MinArgs == NumParams
5919 ? diag::err_typecheck_call_too_many_args
5920 : diag::err_typecheck_call_too_many_args_at_most)
5921 << FnKind << NumParams - ExplicitObjectParameterOffset
5922 << static_cast<unsigned>(Args.size()) -
5923 ExplicitObjectParameterOffset
5924 << HasExplicitObjectParameter << Fn->getSourceRange()
5925 << SourceRange(Args[NumParams]->getBeginLoc(),
5926 Args.back()->getEndLoc());
5927
5928 // Emit the location of the prototype.
5929 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5930 Diag(FDecl->getLocation(), diag::note_callee_decl)
5931 << FDecl << FDecl->getParametersSourceRange();
5932
5933 // This deletes the extra arguments.
5934 Call->shrinkNumArgs(NumParams);
5935 return true;
5936 }
5937 }
5938 SmallVector<Expr *, 8> AllArgs;
5939 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5940
5941 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
5942 AllArgs, CallType);
5943 if (Invalid)
5944 return true;
5945 unsigned TotalNumArgs = AllArgs.size();
5946 for (unsigned i = 0; i < TotalNumArgs; ++i)
5947 Call->setArg(i, AllArgs[i]);
5948
5949 Call->computeDependence();
5950 return false;
5951}
5952
5954 const FunctionProtoType *Proto,
5955 unsigned FirstParam, ArrayRef<Expr *> Args,
5956 SmallVectorImpl<Expr *> &AllArgs,
5957 VariadicCallType CallType, bool AllowExplicit,
5958 bool IsListInitialization) {
5959 unsigned NumParams = Proto->getNumParams();
5960 bool Invalid = false;
5961 size_t ArgIx = 0;
5962 // Continue to check argument types (even if we have too few/many args).
5963 for (unsigned i = FirstParam; i < NumParams; i++) {
5964 QualType ProtoArgType = Proto->getParamType(i);
5965
5966 Expr *Arg;
5967 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5968 if (ArgIx < Args.size()) {
5969 Arg = Args[ArgIx++];
5970
5971 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5972 diag::err_call_incomplete_argument, Arg))
5973 return true;
5974
5975 // Strip the unbridged-cast placeholder expression off, if applicable.
5976 bool CFAudited = false;
5977 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5978 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5979 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5980 Arg = ObjC().stripARCUnbridgedCast(Arg);
5981 else if (getLangOpts().ObjCAutoRefCount &&
5982 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5983 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5984 CFAudited = true;
5985
5986 if (Proto->getExtParameterInfo(i).isNoEscape() &&
5987 ProtoArgType->isBlockPointerType())
5988 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5989 BE->getBlockDecl()->setDoesNotEscape();
5990 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
5992 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
5993 if (ArgExpr.isInvalid())
5994 return true;
5995 Arg = ArgExpr.getAs<Expr>();
5996 }
5997
5998 InitializedEntity Entity =
6000 ProtoArgType)
6002 Context, ProtoArgType, Proto->isParamConsumed(i));
6003
6004 // Remember that parameter belongs to a CF audited API.
6005 if (CFAudited)
6006 Entity.setParameterCFAudited();
6007
6009 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6010 if (ArgE.isInvalid())
6011 return true;
6012
6013 Arg = ArgE.getAs<Expr>();
6014 } else {
6015 assert(Param && "can't use default arguments without a known callee");
6016
6017 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6018 if (ArgExpr.isInvalid())
6019 return true;
6020
6021 Arg = ArgExpr.getAs<Expr>();
6022 }
6023
6024 // Check for array bounds violations for each argument to the call. This
6025 // check only triggers warnings when the argument isn't a more complex Expr
6026 // with its own checking, such as a BinaryOperator.
6027 CheckArrayAccess(Arg);
6028
6029 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6030 CheckStaticArrayArgument(CallLoc, Param, Arg);
6031
6032 AllArgs.push_back(Arg);
6033 }
6034
6035 // If this is a variadic call, handle args passed through "...".
6036 if (CallType != VariadicDoesNotApply) {
6037 // Assume that extern "C" functions with variadic arguments that
6038 // return __unknown_anytype aren't *really* variadic.
6039 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6040 FDecl->isExternC()) {
6041 for (Expr *A : Args.slice(ArgIx)) {
6042 QualType paramType; // ignored
6043 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6044 Invalid |= arg.isInvalid();
6045 AllArgs.push_back(arg.get());
6046 }
6047
6048 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6049 } else {
6050 for (Expr *A : Args.slice(ArgIx)) {
6051 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6052 Invalid |= Arg.isInvalid();
6053 AllArgs.push_back(Arg.get());
6054 }
6055 }
6056
6057 // Check for array bounds violations.
6058 for (Expr *A : Args.slice(ArgIx))
6059 CheckArrayAccess(A);
6060 }
6061 return Invalid;
6062}
6063
6065 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6066 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6067 TL = DTL.getOriginalLoc();
6068 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6069 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6070 << ATL.getLocalSourceRange();
6071}
6072
6073void
6075 ParmVarDecl *Param,
6076 const Expr *ArgExpr) {
6077 // Static array parameters are not supported in C++.
6078 if (!Param || getLangOpts().CPlusPlus)
6079 return;
6080
6081 QualType OrigTy = Param->getOriginalType();
6082
6083 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6084 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6085 return;
6086
6087 if (ArgExpr->isNullPointerConstant(Context,
6089 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6090 DiagnoseCalleeStaticArrayParam(*this, Param);
6091 return;
6092 }
6093
6094 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6095 if (!CAT)
6096 return;
6097
6098 const ConstantArrayType *ArgCAT =
6100 if (!ArgCAT)
6101 return;
6102
6103 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6104 ArgCAT->getElementType())) {
6105 if (ArgCAT->getSize().ult(CAT->getSize())) {
6106 Diag(CallLoc, diag::warn_static_array_too_small)
6107 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6108 << (unsigned)CAT->getZExtSize() << 0;
6109 DiagnoseCalleeStaticArrayParam(*this, Param);
6110 }
6111 return;
6112 }
6113
6114 std::optional<CharUnits> ArgSize =
6116 std::optional<CharUnits> ParmSize =
6118 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6119 Diag(CallLoc, diag::warn_static_array_too_small)
6120 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6121 << (unsigned)ParmSize->getQuantity() << 1;
6122 DiagnoseCalleeStaticArrayParam(*this, Param);
6123 }
6124}
6125
6126/// Given a function expression of unknown-any type, try to rebuild it
6127/// to have a function type.
6129
6130/// Is the given type a placeholder that we need to lower out
6131/// immediately during argument processing?
6133 // Placeholders are never sugared.
6134 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6135 if (!placeholder) return false;
6136
6137 switch (placeholder->getKind()) {
6138 // Ignore all the non-placeholder types.
6139#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6140 case BuiltinType::Id:
6141#include "clang/Basic/OpenCLImageTypes.def"
6142#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6143 case BuiltinType::Id:
6144#include "clang/Basic/OpenCLExtensionTypes.def"
6145 // In practice we'll never use this, since all SVE types are sugared
6146 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6147#define SVE_TYPE(Name, Id, SingletonId) \
6148 case BuiltinType::Id:
6149#include "clang/Basic/AArch64SVEACLETypes.def"
6150#define PPC_VECTOR_TYPE(Name, Id, Size) \
6151 case BuiltinType::Id:
6152#include "clang/Basic/PPCTypes.def"
6153#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6154#include "clang/Basic/RISCVVTypes.def"
6155#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6156#include "clang/Basic/WebAssemblyReferenceTypes.def"
6157#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6158#include "clang/Basic/AMDGPUTypes.def"
6159#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6160#include "clang/Basic/HLSLIntangibleTypes.def"
6161#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6162#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6163#include "clang/AST/BuiltinTypes.def"
6164 return false;
6165
6166 case BuiltinType::UnresolvedTemplate:
6167 // We cannot lower out overload sets; they might validly be resolved
6168 // by the call machinery.
6169 case BuiltinType::Overload:
6170 return false;
6171
6172 // Unbridged casts in ARC can be handled in some call positions and
6173 // should be left in place.
6174 case BuiltinType::ARCUnbridgedCast:
6175 return false;
6176
6177 // Pseudo-objects should be converted as soon as possible.
6178 case BuiltinType::PseudoObject:
6179 return true;
6180
6181 // The debugger mode could theoretically but currently does not try
6182 // to resolve unknown-typed arguments based on known parameter types.
6183 case BuiltinType::UnknownAny:
6184 return true;
6185
6186 // These are always invalid as call arguments and should be reported.
6187 case BuiltinType::BoundMember:
6188 case BuiltinType::BuiltinFn:
6189 case BuiltinType::IncompleteMatrixIdx:
6190 case BuiltinType::ArraySection:
6191 case BuiltinType::OMPArrayShaping:
6192 case BuiltinType::OMPIterator:
6193 return true;
6194
6195 }
6196 llvm_unreachable("bad builtin type kind");
6197}
6198
6200 // Apply this processing to all the arguments at once instead of
6201 // dying at the first failure.
6202 bool hasInvalid = false;
6203 for (size_t i = 0, e = args.size(); i != e; i++) {
6204 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6205 ExprResult result = CheckPlaceholderExpr(args[i]);
6206 if (result.isInvalid()) hasInvalid = true;
6207 else args[i] = result.get();
6208 }
6209 }
6210 return hasInvalid;
6211}
6212
6213/// If a builtin function has a pointer argument with no explicit address
6214/// space, then it should be able to accept a pointer to any address
6215/// space as input. In order to do this, we need to replace the
6216/// standard builtin declaration with one that uses the same address space
6217/// as the call.
6218///
6219/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6220/// it does not contain any pointer arguments without
6221/// an address space qualifer. Otherwise the rewritten
6222/// FunctionDecl is returned.
6223/// TODO: Handle pointer return types.
6225 FunctionDecl *FDecl,
6226 MultiExprArg ArgExprs) {
6227
6228 QualType DeclType = FDecl->getType();
6229 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6230
6231 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6232 ArgExprs.size() < FT->getNumParams())
6233 return nullptr;
6234
6235 bool NeedsNewDecl = false;
6236 unsigned i = 0;
6237 SmallVector<QualType, 8> OverloadParams;
6238
6239 for (QualType ParamType : FT->param_types()) {
6240
6241 // Convert array arguments to pointer to simplify type lookup.
6242 ExprResult ArgRes =
6244 if (ArgRes.isInvalid())
6245 return nullptr;
6246 Expr *Arg = ArgRes.get();
6247 QualType ArgType = Arg->getType();
6248 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6249 !ArgType->isPointerType() ||
6250 !ArgType->getPointeeType().hasAddressSpace() ||
6252 OverloadParams.push_back(ParamType);
6253 continue;
6254 }
6255
6256 QualType PointeeType = ParamType->getPointeeType();
6257 if (PointeeType.hasAddressSpace())
6258 continue;
6259
6260 NeedsNewDecl = true;
6261 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6262
6263 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6264 OverloadParams.push_back(Context.getPointerType(PointeeType));
6265 }
6266
6267 if (!NeedsNewDecl)
6268 return nullptr;
6269
6271 EPI.Variadic = FT->isVariadic();
6272 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6273 OverloadParams, EPI);
6274 DeclContext *Parent = FDecl->getParent();
6275 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6276 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6277 FDecl->getIdentifier(), OverloadTy,
6278 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6279 false,
6280 /*hasPrototype=*/true);
6282 FT = cast<FunctionProtoType>(OverloadTy);
6283 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6284 QualType ParamType = FT->getParamType(i);
6285 ParmVarDecl *Parm =
6286 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6287 SourceLocation(), nullptr, ParamType,
6288 /*TInfo=*/nullptr, SC_None, nullptr);
6289 Parm->setScopeInfo(0, i);
6290 Params.push_back(Parm);
6291 }
6292 OverloadDecl->setParams(Params);
6293 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6294 return OverloadDecl;
6295}
6296
6297static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6298 FunctionDecl *Callee,
6299 MultiExprArg ArgExprs) {
6300 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6301 // similar attributes) really don't like it when functions are called with an
6302 // invalid number of args.
6303 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6304 /*PartialOverloading=*/false) &&
6305 !Callee->isVariadic())
6306 return;
6307 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6308 return;
6309
6310 if (const EnableIfAttr *Attr =
6311 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6312 S.Diag(Fn->getBeginLoc(),
6313 isa<CXXMethodDecl>(Callee)
6314 ? diag::err_ovl_no_viable_member_function_in_call
6315 : diag::err_ovl_no_viable_function_in_call)
6316 << Callee << Callee->getSourceRange();
6317 S.Diag(Callee->getLocation(),
6318 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6319 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6320 return;
6321 }
6322}
6323
6325 const UnresolvedMemberExpr *const UME, Sema &S) {
6326
6327 const auto GetFunctionLevelDCIfCXXClass =
6328 [](Sema &S) -> const CXXRecordDecl * {
6329 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6330 if (!DC || !DC->getParent())
6331 return nullptr;
6332
6333 // If the call to some member function was made from within a member
6334 // function body 'M' return return 'M's parent.
6335 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6336 return MD->getParent()->getCanonicalDecl();
6337 // else the call was made from within a default member initializer of a
6338 // class, so return the class.
6339 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6340 return RD->getCanonicalDecl();
6341 return nullptr;
6342 };
6343 // If our DeclContext is neither a member function nor a class (in the
6344 // case of a lambda in a default member initializer), we can't have an
6345 // enclosing 'this'.
6346
6347 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6348 if (!CurParentClass)
6349 return false;
6350
6351 // The naming class for implicit member functions call is the class in which
6352 // name lookup starts.
6353 const CXXRecordDecl *const NamingClass =
6355 assert(NamingClass && "Must have naming class even for implicit access");
6356
6357 // If the unresolved member functions were found in a 'naming class' that is
6358 // related (either the same or derived from) to the class that contains the
6359 // member function that itself contained the implicit member access.
6360
6361 return CurParentClass == NamingClass ||
6362 CurParentClass->isDerivedFrom(NamingClass);
6363}
6364
6365static void
6367 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6368
6369 if (!UME)
6370 return;
6371
6372 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6373 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6374 // already been captured, or if this is an implicit member function call (if
6375 // it isn't, an attempt to capture 'this' should already have been made).
6376 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6377 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6378 return;
6379
6380 // Check if the naming class in which the unresolved members were found is
6381 // related (same as or is a base of) to the enclosing class.
6382
6384 return;
6385
6386
6387 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6388 // If the enclosing function is not dependent, then this lambda is
6389 // capture ready, so if we can capture this, do so.
6390 if (!EnclosingFunctionCtx->isDependentContext()) {
6391 // If the current lambda and all enclosing lambdas can capture 'this' -
6392 // then go ahead and capture 'this' (since our unresolved overload set
6393 // contains at least one non-static member function).
6394 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6395 S.CheckCXXThisCapture(CallLoc);
6396 } else if (S.CurContext->isDependentContext()) {
6397 // ... since this is an implicit member reference, that might potentially
6398 // involve a 'this' capture, mark 'this' for potential capture in
6399 // enclosing lambdas.
6400 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6401 CurLSI->addPotentialThisCapture(CallLoc);
6402 }
6403}
6404
6405// Once a call is fully resolved, warn for unqualified calls to specific
6406// C++ standard functions, like move and forward.
6408 const CallExpr *Call) {
6409 // We are only checking unary move and forward so exit early here.
6410 if (Call->getNumArgs() != 1)
6411 return;
6412
6413 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6414 if (!E || isa<UnresolvedLookupExpr>(E))
6415 return;
6416 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6417 if (!DRE || !DRE->getLocation().isValid())
6418 return;
6419
6420 if (DRE->getQualifier())
6421 return;
6422
6423 const FunctionDecl *FD = Call->getDirectCallee();
6424 if (!FD)
6425 return;
6426
6427 // Only warn for some functions deemed more frequent or problematic.
6428 unsigned BuiltinID = FD->getBuiltinID();
6429 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6430 return;
6431
6432 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6434 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6435}
6436
6438 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6439 Expr *ExecConfig) {
6441 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6442 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6443 if (Call.isInvalid())
6444 return Call;
6445
6446 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6447 // language modes.
6448 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6449 ULE && ULE->hasExplicitTemplateArgs() &&
6450 ULE->decls_begin() == ULE->decls_end()) {
6451 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6452 ? diag::warn_cxx17_compat_adl_only_template_id
6453 : diag::ext_adl_only_template_id)
6454 << ULE->getName();
6455 }
6456
6457 if (LangOpts.OpenMP)
6458 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6459 ExecConfig);
6460 if (LangOpts.CPlusPlus) {
6461 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6463
6464 // If we previously found that the id-expression of this call refers to a
6465 // consteval function but the call is dependent, we should not treat is an
6466 // an invalid immediate call.
6467 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6468 DRE && Call.get()->isValueDependent()) {
6470 }
6471 }
6472 return Call;
6473}
6474
6476 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6477 Expr *ExecConfig, bool IsExecConfig,
6478 bool AllowRecovery) {
6479 // Since this might be a postfix expression, get rid of ParenListExprs.
6481 if (Result.isInvalid()) return ExprError();
6482 Fn = Result.get();
6483
6484 if (CheckArgsForPlaceholders(ArgExprs))
6485 return ExprError();
6486
6487 // The result of __builtin_counted_by_ref cannot be used as a function
6488 // argument. It allows leaking and modification of bounds safety information.
6489 for (const Expr *Arg : ArgExprs)
6490 if (CheckInvalidBuiltinCountedByRef(Arg, FunctionArgKind))
6491 return ExprError();
6492
6493 if (getLangOpts().CPlusPlus) {
6494 // If this is a pseudo-destructor expression, build the call immediately.
6495 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6496 if (!ArgExprs.empty()) {
6497 // Pseudo-destructor calls should not have any arguments.
6498 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6500 SourceRange(ArgExprs.front()->getBeginLoc(),
6501 ArgExprs.back()->getEndLoc()));
6502 }
6503
6504 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6505 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6506 }
6507 if (Fn->getType() == Context.PseudoObjectTy) {
6508 ExprResult result = CheckPlaceholderExpr(Fn);
6509 if (result.isInvalid()) return ExprError();
6510 Fn = result.get();
6511 }
6512
6513 // Determine whether this is a dependent call inside a C++ template,
6514 // in which case we won't do any semantic analysis now.
6515 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6516 if (ExecConfig) {
6518 cast<CallExpr>(ExecConfig), ArgExprs,
6520 RParenLoc, CurFPFeatureOverrides());
6521 } else {
6522
6524 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6525 Fn->getBeginLoc());
6526
6527 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6528 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6529 }
6530 }
6531
6532 // Determine whether this is a call to an object (C++ [over.call.object]).
6533 if (Fn->getType()->isRecordType())
6534 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6535 RParenLoc);
6536
6537 if (Fn->getType() == Context.UnknownAnyTy) {
6538 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6539 if (result.isInvalid()) return ExprError();
6540 Fn = result.get();
6541 }
6542
6543 if (Fn->getType() == Context.BoundMemberTy) {
6544 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6545 RParenLoc, ExecConfig, IsExecConfig,
6546 AllowRecovery);
6547 }
6548 }
6549
6550 // Check for overloaded calls. This can happen even in C due to extensions.
6551 if (Fn->getType() == Context.OverloadTy) {
6553
6554 // We aren't supposed to apply this logic if there's an '&' involved.
6557 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6558 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6559 OverloadExpr *ovl = find.Expression;
6560 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6562 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6563 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6564 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6565 RParenLoc, ExecConfig, IsExecConfig,
6566 AllowRecovery);
6567 }
6568 }
6569
6570 // If we're directly calling a function, get the appropriate declaration.
6571 if (Fn->getType() == Context.UnknownAnyTy) {
6572 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6573 if (result.isInvalid()) return ExprError();
6574 Fn = result.get();
6575 }
6576
6577 Expr *NakedFn = Fn->IgnoreParens();
6578
6579 bool CallingNDeclIndirectly = false;
6580 NamedDecl *NDecl = nullptr;
6581 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6582 if (UnOp->getOpcode() == UO_AddrOf) {
6583 CallingNDeclIndirectly = true;
6584 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6585 }
6586 }
6587
6588 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6589 NDecl = DRE->getDecl();
6590
6591 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6592 if (FDecl && FDecl->getBuiltinID()) {
6593 // Rewrite the function decl for this builtin by replacing parameters
6594 // with no explicit address space with the address space of the arguments
6595 // in ArgExprs.
6596 if ((FDecl =
6597 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6598 NDecl = FDecl;
6600 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6601 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6602 nullptr, DRE->isNonOdrUse());
6603 }
6604 }
6605 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6606 NDecl = ME->getMemberDecl();
6607
6608 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6609 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6610 FD, /*Complain=*/true, Fn->getBeginLoc()))
6611 return ExprError();
6612
6613 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6614
6615 // If this expression is a call to a builtin function in HIP device
6616 // compilation, allow a pointer-type argument to default address space to be
6617 // passed as a pointer-type parameter to a non-default address space.
6618 // If Arg is declared in the default address space and Param is declared
6619 // in a non-default address space, perform an implicit address space cast to
6620 // the parameter type.
6621 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6622 FD->getBuiltinID()) {
6623 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6624 ++Idx) {
6625 ParmVarDecl *Param = FD->getParamDecl(Idx);
6626 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6627 !ArgExprs[Idx]->getType()->isPointerType())
6628 continue;
6629
6630 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6631 auto ArgTy = ArgExprs[Idx]->getType();
6632 auto ArgPtTy = ArgTy->getPointeeType();
6633 auto ArgAS = ArgPtTy.getAddressSpace();
6634
6635 // Add address space cast if target address spaces are different
6636 bool NeedImplicitASC =
6637 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6638 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6639 // or from specific AS which has target AS matching that of Param.
6641 if (!NeedImplicitASC)
6642 continue;
6643
6644 // First, ensure that the Arg is an RValue.
6645 if (ArgExprs[Idx]->isGLValue()) {
6646 ArgExprs[Idx] = ImplicitCastExpr::Create(
6647 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6648 nullptr, VK_PRValue, FPOptionsOverride());
6649 }
6650
6651 // Construct a new arg type with address space of Param
6652 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6653 ArgPtQuals.setAddressSpace(ParamAS);
6654 auto NewArgPtTy =
6655 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6656 auto NewArgTy =
6658 ArgTy.getQualifiers());
6659
6660 // Finally perform an implicit address space cast
6661 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6662 CK_AddressSpaceConversion)
6663 .get();
6664 }
6665 }
6666 }
6667
6669 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6670 assert(!getLangOpts().CPlusPlus);
6671 assert((Fn->containsErrors() ||
6672 llvm::any_of(ArgExprs,
6673 [](clang::Expr *E) { return E->containsErrors(); })) &&
6674 "should only occur in error-recovery path.");
6675 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6676 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6677 }
6678 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6679 ExecConfig, IsExecConfig);
6680}
6681
6683 MultiExprArg CallArgs) {
6684 StringRef Name = Context.BuiltinInfo.getName(Id);
6685 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6687 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6688
6689 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6690 assert(BuiltInDecl && "failed to find builtin declaration");
6691
6692 ExprResult DeclRef =
6693 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6694 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6695
6697 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6698
6699 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6700 return Call.get();
6701}
6702
6704 SourceLocation BuiltinLoc,
6705 SourceLocation RParenLoc) {
6706 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6707 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6708}
6709
6711 SourceLocation BuiltinLoc,
6712 SourceLocation RParenLoc) {
6715 QualType SrcTy = E->getType();
6716 if (!SrcTy->isDependentType() &&
6717 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6718 return ExprError(
6719 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6720 << DestTy << SrcTy << E->getSourceRange());
6721 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6722}
6723
6725 SourceLocation BuiltinLoc,
6726 SourceLocation RParenLoc) {
6727 TypeSourceInfo *TInfo;
6728 GetTypeFromParser(ParsedDestTy, &TInfo);
6729 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6730}
6731
6733 SourceLocation LParenLoc,
6734 ArrayRef<Expr *> Args,
6735 SourceLocation RParenLoc, Expr *Config,
6736 bool IsExecConfig, ADLCallKind UsesADL) {
6737 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6738 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6739
6740 // Functions with 'interrupt' attribute cannot be called directly.
6741 if (FDecl) {
6742 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
6743 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6744 return ExprError();
6745 }
6746 if (FDecl->hasAttr<ARMInterruptAttr>()) {
6747 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
6748 return ExprError();
6749 }
6750 }
6751
6752 // X86 interrupt handlers may only call routines with attribute
6753 // no_caller_saved_registers since there is no efficient way to
6754 // save and restore the non-GPR state.
6755 if (auto *Caller = getCurFunctionDecl()) {
6756 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6757 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6758 const TargetInfo &TI = Context.getTargetInfo();
6759 bool HasNonGPRRegisters =
6760 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
6761 if (HasNonGPRRegisters &&
6762 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6763 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
6764 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6765 if (FDecl)
6766 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6767 }
6768 }
6769 }
6770
6771 // Promote the function operand.
6772 // We special-case function promotion here because we only allow promoting
6773 // builtin functions to function pointers in the callee of a call.
6775 QualType ResultTy;
6776 if (BuiltinID &&
6777 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6778 // Extract the return type from the (builtin) function pointer type.
6779 // FIXME Several builtins still have setType in
6780 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6781 // Builtins.td to ensure they are correct before removing setType calls.
6782 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6783 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6784 ResultTy = FDecl->getCallResultType();
6785 } else {
6787 ResultTy = Context.BoolTy;
6788 }
6789 if (Result.isInvalid())
6790 return ExprError();
6791 Fn = Result.get();
6792
6793 // Check for a valid function type, but only if it is not a builtin which
6794 // requires custom type checking. These will be handled by
6795 // CheckBuiltinFunctionCall below just after creation of the call expression.
6796 const FunctionType *FuncT = nullptr;
6797 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6798 retry:
6799 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6800 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6801 // have type pointer to function".
6802 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6803 if (!FuncT)
6804 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6805 << Fn->getType() << Fn->getSourceRange());
6806 } else if (const BlockPointerType *BPT =
6807 Fn->getType()->getAs<BlockPointerType>()) {
6808 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6809 } else {
6810 // Handle calls to expressions of unknown-any type.
6811 if (Fn->getType() == Context.UnknownAnyTy) {
6812 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6813 if (rewrite.isInvalid())
6814 return ExprError();
6815 Fn = rewrite.get();
6816 goto retry;
6817 }
6818
6819 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6820 << Fn->getType() << Fn->getSourceRange());
6821 }
6822 }
6823
6824 // Get the number of parameters in the function prototype, if any.
6825 // We will allocate space for max(Args.size(), NumParams) arguments
6826 // in the call expression.
6827 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6828 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6829
6830 CallExpr *TheCall;
6831 if (Config) {
6832 assert(UsesADL == ADLCallKind::NotADL &&
6833 "CUDAKernelCallExpr should not use ADL");
6834 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6835 Args, ResultTy, VK_PRValue, RParenLoc,
6836 CurFPFeatureOverrides(), NumParams);
6837 } else {
6838 TheCall =
6839 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6840 CurFPFeatureOverrides(), NumParams, UsesADL);
6841 }
6842
6844 // Forget about the nulled arguments since typo correction
6845 // do not handle them well.
6846 TheCall->shrinkNumArgs(Args.size());
6847 // C cannot always handle TypoExpr nodes in builtin calls and direct
6848 // function calls as their argument checking don't necessarily handle
6849 // dependent types properly, so make sure any TypoExprs have been
6850 // dealt with.
6852 if (!Result.isUsable()) return ExprError();
6853 CallExpr *TheOldCall = TheCall;
6854 TheCall = dyn_cast<CallExpr>(Result.get());
6855 bool CorrectedTypos = TheCall != TheOldCall;
6856 if (!TheCall) return Result;
6857 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6858
6859 // A new call expression node was created if some typos were corrected.
6860 // However it may not have been constructed with enough storage. In this
6861 // case, rebuild the node with enough storage. The waste of space is
6862 // immaterial since this only happens when some typos were corrected.
6863 if (CorrectedTypos && Args.size() < NumParams) {
6864 if (Config)
6866 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6867 RParenLoc, CurFPFeatureOverrides(), NumParams);
6868 else
6869 TheCall =
6870 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6871 CurFPFeatureOverrides(), NumParams, UsesADL);
6872 }
6873 // We can now handle the nulled arguments for the default arguments.
6874 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6875 }
6876
6877 // Bail out early if calling a builtin with custom type checking.
6878 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6879 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6880 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
6882 return E;
6883 }
6884
6885 if (getLangOpts().CUDA) {
6886 if (Config) {
6887 // CUDA: Kernel calls must be to global functions
6888 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6889 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6890 << FDecl << Fn->getSourceRange());
6891
6892 // CUDA: Kernel function must have 'void' return type
6893 if (!FuncT->getReturnType()->isVoidType() &&
6894 !FuncT->getReturnType()->getAs<AutoType>() &&
6896 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6897 << Fn->getType() << Fn->getSourceRange());
6898 } else {
6899 // CUDA: Calls to global functions must be configured
6900 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6901 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6902 << FDecl << Fn->getSourceRange());
6903 }
6904 }
6905
6906 // Check for a valid return type
6907 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6908 FDecl))
6909 return ExprError();
6910
6911 // We know the result type of the call, set it.
6912 TheCall->setType(FuncT->getCallResultType(Context));
6914
6915 // WebAssembly tables can't be used as arguments.
6916 if (Context.getTargetInfo().getTriple().isWasm()) {
6917 for (const Expr *Arg : Args) {
6918 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
6919 return ExprError(Diag(Arg->getExprLoc(),
6920 diag::err_wasm_table_as_function_parameter));
6921 }
6922 }
6923 }
6924
6925 if (Proto) {
6926 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6927 IsExecConfig))
6928 return ExprError();
6929 } else {
6930 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6931
6932 if (FDecl) {
6933 // Check if we have too few/too many template arguments, based
6934 // on our knowledge of the function definition.
6935 const FunctionDecl *Def = nullptr;
6936 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6937 Proto = Def->getType()->getAs<FunctionProtoType>();
6938 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6939 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6940 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6941 }
6942
6943 // If the function we're calling isn't a function prototype, but we have
6944 // a function prototype from a prior declaratiom, use that prototype.
6945 if (!FDecl->hasPrototype())
6946 Proto = FDecl->getType()->getAs<FunctionProtoType>();
6947 }
6948
6949 // If we still haven't found a prototype to use but there are arguments to
6950 // the call, diagnose this as calling a function without a prototype.
6951 // However, if we found a function declaration, check to see if
6952 // -Wdeprecated-non-prototype was disabled where the function was declared.
6953 // If so, we will silence the diagnostic here on the assumption that this
6954 // interface is intentional and the user knows what they're doing. We will
6955 // also silence the diagnostic if there is a function declaration but it
6956 // was implicitly defined (the user already gets diagnostics about the
6957 // creation of the implicit function declaration, so the additional warning
6958 // is not helpful).
6959 if (!Proto && !Args.empty() &&
6960 (!FDecl || (!FDecl->isImplicit() &&
6961 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
6962 FDecl->getLocation()))))
6963 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
6964 << (FDecl != nullptr) << FDecl;
6965
6966 // Promote the arguments (C99 6.5.2.2p6).
6967 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6968 Expr *Arg = Args[i];
6969
6970 if (Proto && i < Proto->getNumParams()) {
6972 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6973 ExprResult ArgE =
6975 if (ArgE.isInvalid())
6976 return true;
6977
6978 Arg = ArgE.getAs<Expr>();
6979
6980 } else {
6982
6983 if (ArgE.isInvalid())
6984 return true;
6985
6986 Arg = ArgE.getAs<Expr>();
6987 }
6988
6989 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6990 diag::err_call_incomplete_argument, Arg))
6991 return ExprError();
6992
6993 TheCall->setArg(i, Arg);
6994 }
6995 TheCall->computeDependence();
6996 }
6997
6998 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
6999 if (Method->isImplicitObjectMemberFunction())
7000 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7001 << Fn->getSourceRange() << 0);
7002
7003 // Check for sentinels
7004 if (NDecl)
7005 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7006
7007 // Warn for unions passing across security boundary (CMSE).
7008 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7009 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7010 if (const auto *RT =
7011 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7012 if (RT->getDecl()->isOrContainsUnion())
7013 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7014 << 0 << i;
7015 }
7016 }
7017 }
7018
7019 // Do special checking on direct calls to functions.
7020 if (FDecl) {
7021 if (CheckFunctionCall(FDecl, TheCall, Proto))
7022 return ExprError();
7023
7024 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7025
7026 if (BuiltinID)
7027 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7028 } else if (NDecl) {
7029 if (CheckPointerCall(NDecl, TheCall, Proto))
7030 return ExprError();
7031 } else {
7032 if (CheckOtherCall(TheCall, Proto))
7033 return ExprError();
7034 }
7035
7036 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7037}
7038
7041 SourceLocation RParenLoc, Expr *InitExpr) {
7042 assert(Ty && "ActOnCompoundLiteral(): missing type");
7043 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7044
7045 TypeSourceInfo *TInfo;
7046 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7047 if (!TInfo)
7048 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7049
7050 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7051}
7052
7055 SourceLocation RParenLoc, Expr *LiteralExpr) {
7056 QualType literalType = TInfo->getType();
7057
7058 if (literalType->isArrayType()) {
7060 LParenLoc, Context.getBaseElementType(literalType),
7061 diag::err_array_incomplete_or_sizeless_type,
7062 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7063 return ExprError();
7064 if (literalType->isVariableArrayType()) {
7065 // C23 6.7.10p4: An entity of variable length array type shall not be
7066 // initialized except by an empty initializer.
7067 //
7068 // The C extension warnings are issued from ParseBraceInitializer() and
7069 // do not need to be issued here. However, we continue to issue an error
7070 // in the case there are initializers or we are compiling C++. We allow
7071 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7072 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7073 // FIXME: should we allow this construct in C++ when it makes sense to do
7074 // so?
7075 //
7076 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7077 // shall specify an object type or an array of unknown size, but not a
7078 // variable length array type. This seems odd, as it allows 'int a[size] =
7079 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7080 // says, this is what's implemented here for C (except for the extension
7081 // that permits constant foldable size arrays)
7082
7083 auto diagID = LangOpts.CPlusPlus
7084 ? diag::err_variable_object_no_init
7085 : diag::err_compound_literal_with_vla_type;
7086 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7087 diagID))
7088 return ExprError();
7089 }
7090 } else if (!literalType->isDependentType() &&
7091 RequireCompleteType(LParenLoc, literalType,
7092 diag::err_typecheck_decl_incomplete_type,
7093 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7094 return ExprError();
7095
7096 InitializedEntity Entity
7100 SourceRange(LParenLoc, RParenLoc),
7101 /*InitList=*/true);
7102 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7103 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7104 &literalType);
7105 if (Result.isInvalid())
7106 return ExprError();
7107 LiteralExpr = Result.get();
7108
7109 bool isFileScope = !CurContext->isFunctionOrMethod();
7110
7111 // In C, compound literals are l-values for some reason.
7112 // For GCC compatibility, in C++, file-scope array compound literals with
7113 // constant initializers are also l-values, and compound literals are
7114 // otherwise prvalues.
7115 //
7116 // (GCC also treats C++ list-initialized file-scope array prvalues with
7117 // constant initializers as l-values, but that's non-conforming, so we don't
7118 // follow it there.)
7119 //
7120 // FIXME: It would be better to handle the lvalue cases as materializing and
7121 // lifetime-extending a temporary object, but our materialized temporaries
7122 // representation only supports lifetime extension from a variable, not "out
7123 // of thin air".
7124 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7125 // is bound to the result of applying array-to-pointer decay to the compound
7126 // literal.
7127 // FIXME: GCC supports compound literals of reference type, which should
7128 // obviously have a value kind derived from the kind of reference involved.
7129 ExprValueKind VK =
7130 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7131 ? VK_PRValue
7132 : VK_LValue;
7133
7134 if (isFileScope)
7135 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7136 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7137 Expr *Init = ILE->getInit(i);
7138 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7139 }
7140
7141 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7142 VK, LiteralExpr, isFileScope);
7143 if (isFileScope) {
7144 if (!LiteralExpr->isTypeDependent() &&
7145 !LiteralExpr->isValueDependent() &&
7146 !literalType->isDependentType()) // C99 6.5.2.5p3
7147 if (CheckForConstantInitializer(LiteralExpr))
7148 return ExprError();
7149 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7150 literalType.getAddressSpace() != LangAS::Default) {
7151 // Embedded-C extensions to C99 6.5.2.5:
7152 // "If the compound literal occurs inside the body of a function, the
7153 // type name shall not be qualified by an address-space qualifier."
7154 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7155 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7156 return ExprError();
7157 }
7158
7159 if (!isFileScope && !getLangOpts().CPlusPlus) {
7160 // Compound literals that have automatic storage duration are destroyed at
7161 // the end of the scope in C; in C++, they're just temporaries.
7162
7163 // Emit diagnostics if it is or contains a C union type that is non-trivial
7164 // to destruct.
7168
7169 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7170 if (literalType.isDestructedType()) {
7172 ExprCleanupObjects.push_back(E);
7174 }
7175 }
7176
7179 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7180 E->getInitializer()->getExprLoc());
7181
7182 return MaybeBindToTemporary(E);
7183}
7184
7187 SourceLocation RBraceLoc) {
7188 // Only produce each kind of designated initialization diagnostic once.
7189 SourceLocation FirstDesignator;
7190 bool DiagnosedArrayDesignator = false;
7191 bool DiagnosedNestedDesignator = false;
7192 bool DiagnosedMixedDesignator = false;
7193
7194 // Check that any designated initializers are syntactically valid in the
7195 // current language mode.
7196 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7197 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7198 if (FirstDesignator.isInvalid())
7199 FirstDesignator = DIE->getBeginLoc();
7200
7201 if (!getLangOpts().CPlusPlus)
7202 break;
7203
7204 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7205 DiagnosedNestedDesignator = true;
7206 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7207 << DIE->getDesignatorsSourceRange();
7208 }
7209
7210 for (auto &Desig : DIE->designators()) {
7211 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7212 DiagnosedArrayDesignator = true;
7213 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7214 << Desig.getSourceRange();
7215 }
7216 }
7217
7218 if (!DiagnosedMixedDesignator &&
7219 !isa<DesignatedInitExpr>(InitArgList[0])) {
7220 DiagnosedMixedDesignator = true;
7221 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7222 << DIE->getSourceRange();
7223 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7224 << InitArgList[0]->getSourceRange();
7225 }
7226 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7227 isa<DesignatedInitExpr>(InitArgList[0])) {
7228 DiagnosedMixedDesignator = true;
7229 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7230 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7231 << DIE->getSourceRange();
7232 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7233 << InitArgList[I]->getSourceRange();
7234 }
7235 }
7236
7237 if (FirstDesignator.isValid()) {
7238 // Only diagnose designated initiaization as a C++20 extension if we didn't
7239 // already diagnose use of (non-C++20) C99 designator syntax.
7240 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7241 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7242 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7243 ? diag::warn_cxx17_compat_designated_init
7244 : diag::ext_cxx_designated_init);
7245 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7246 Diag(FirstDesignator, diag::ext_designated_init);
7247 }
7248 }
7249
7250 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7251}
7252
7255 SourceLocation RBraceLoc) {
7256 // Semantic analysis for initializers is done by ActOnDeclarator() and
7257 // CheckInitializer() - it requires knowledge of the object being initialized.
7258
7259 // Immediately handle non-overload placeholders. Overloads can be
7260 // resolved contextually, but everything else here can't.
7261 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7262 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7263 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7264
7265 // Ignore failures; dropping the entire initializer list because
7266 // of one failure would be terrible for indexing/etc.
7267 if (result.isInvalid()) continue;
7268
7269 InitArgList[I] = result.get();
7270 }
7271 }
7272
7273 InitListExpr *E =
7274 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7275 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7276 return E;
7277}
7278
7280 assert(E.get()->getType()->isBlockPointerType());
7281 assert(E.get()->isPRValue());
7282
7283 // Only do this in an r-value context.
7284 if (!getLangOpts().ObjCAutoRefCount) return;
7285
7287 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7288 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7290}
7291
7293 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7294 // Also, callers should have filtered out the invalid cases with
7295 // pointers. Everything else should be possible.
7296
7297 QualType SrcTy = Src.get()->getType();
7298 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7299 return CK_NoOp;
7300
7301 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7303 llvm_unreachable("member pointer type in C");
7304
7305 case Type::STK_CPointer:
7308 switch (DestTy->getScalarTypeKind()) {
7309 case Type::STK_CPointer: {
7310 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7311 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7312 if (SrcAS != DestAS)
7313 return CK_AddressSpaceConversion;
7314 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7315 return CK_NoOp;
7316 return CK_BitCast;
7317 }
7319 return (SrcKind == Type::STK_BlockPointer
7320 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7322 if (SrcKind == Type::STK_ObjCObjectPointer)
7323 return CK_BitCast;
7324 if (SrcKind == Type::STK_CPointer)
7325 return CK_CPointerToObjCPointerCast;
7327 return CK_BlockPointerToObjCPointerCast;
7328 case Type::STK_Bool:
7329 return CK_PointerToBoolean;
7330 case Type::STK_Integral:
7331 return CK_PointerToIntegral;
7332 case Type::STK_Floating:
7337 llvm_unreachable("illegal cast from pointer");
7338 }
7339 llvm_unreachable("Should have returned before this");
7340
7342 switch (DestTy->getScalarTypeKind()) {
7344 return CK_FixedPointCast;
7345 case Type::STK_Bool:
7346 return CK_FixedPointToBoolean;
7347 case Type::STK_Integral:
7348 return CK_FixedPointToIntegral;
7349 case Type::STK_Floating:
7350 return CK_FixedPointToFloating;
7353 Diag(Src.get()->getExprLoc(),
7354 diag::err_unimplemented_conversion_with_fixed_point_type)
7355 << DestTy;
7356 return CK_IntegralCast;
7357 case Type::STK_CPointer:
7361 llvm_unreachable("illegal cast to pointer type");
7362 }
7363 llvm_unreachable("Should have returned before this");
7364
7365 case Type::STK_Bool: // casting from bool is like casting from an integer
7366 case Type::STK_Integral:
7367 switch (DestTy->getScalarTypeKind()) {
7368 case Type::STK_CPointer:
7373 return CK_NullToPointer;
7374 return CK_IntegralToPointer;
7375 case Type::STK_Bool:
7376 return CK_IntegralToBoolean;
7377 case Type::STK_Integral:
7378 return CK_IntegralCast;
7379 case Type::STK_Floating:
7380 return CK_IntegralToFloating;
7382 Src = ImpCastExprToType(Src.get(),
7383 DestTy->castAs<ComplexType>()->getElementType(),
7384 CK_IntegralCast);
7385 return CK_IntegralRealToComplex;
7387 Src = ImpCastExprToType(Src.get(),
7388 DestTy->castAs<ComplexType>()->getElementType(),
7389 CK_IntegralToFloating);
7390 return CK_FloatingRealToComplex;
7392 llvm_unreachable("member pointer type in C");
7394 return CK_IntegralToFixedPoint;
7395 }
7396 llvm_unreachable("Should have returned before this");
7397
7398 case Type::STK_Floating:
7399 switch (DestTy->getScalarTypeKind()) {
7400 case Type::STK_Floating:
7401 return CK_FloatingCast;
7402 case Type::STK_Bool:
7403 return CK_FloatingToBoolean;
7404 case Type::STK_Integral:
7405 return CK_FloatingToIntegral;
7407 Src = ImpCastExprToType(Src.get(),
7408 DestTy->castAs<ComplexType>()->getElementType(),
7409 CK_FloatingCast);
7410 return CK_FloatingRealToComplex;
7412 Src = ImpCastExprToType(Src.get(),
7413 DestTy->castAs<ComplexType>()->getElementType(),
7414 CK_FloatingToIntegral);
7415 return CK_IntegralRealToComplex;
7416 case Type::STK_CPointer:
7419 llvm_unreachable("valid float->pointer cast?");
7421 llvm_unreachable("member pointer type in C");
7423 return CK_FloatingToFixedPoint;
7424 }
7425 llvm_unreachable("Should have returned before this");
7426
7428 switch (DestTy->getScalarTypeKind()) {
7430 return CK_FloatingComplexCast;
7432 return CK_FloatingComplexToIntegralComplex;
7433 case Type::STK_Floating: {
7434 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7435 if (Context.hasSameType(ET, DestTy))
7436 return CK_FloatingComplexToReal;
7437 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7438 return CK_FloatingCast;
7439 }
7440 case Type::STK_Bool:
7441 return CK_FloatingComplexToBoolean;
7442 case Type::STK_Integral:
7443 Src = ImpCastExprToType(Src.get(),
7444 SrcTy->castAs<ComplexType>()->getElementType(),
7445 CK_FloatingComplexToReal);
7446 return CK_FloatingToIntegral;
7447 case Type::STK_CPointer:
7450 llvm_unreachable("valid complex float->pointer cast?");
7452 llvm_unreachable("member pointer type in C");
7454 Diag(Src.get()->getExprLoc(),
7455 diag::err_unimplemented_conversion_with_fixed_point_type)
7456 << SrcTy;
7457 return CK_IntegralCast;
7458 }
7459 llvm_unreachable("Should have returned before this");
7460
7462 switch (DestTy->getScalarTypeKind()) {
7464 return CK_IntegralComplexToFloatingComplex;
7466 return CK_IntegralComplexCast;
7467 case Type::STK_Integral: {
7468 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7469 if (Context.hasSameType(ET, DestTy))
7470 return CK_IntegralComplexToReal;
7471 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7472 return CK_IntegralCast;
7473 }
7474 case Type::STK_Bool:
7475 return CK_IntegralComplexToBoolean;
7476 case Type::STK_Floating:
7477 Src = ImpCastExprToType(Src.get(),
7478 SrcTy->castAs<ComplexType>()->getElementType(),
7479 CK_IntegralComplexToReal);
7480 return CK_IntegralToFloating;
7481 case Type::STK_CPointer:
7484 llvm_unreachable("valid complex int->pointer cast?");
7486 llvm_unreachable("member pointer type in C");
7488 Diag(Src.get()->getExprLoc(),
7489 diag::err_unimplemented_conversion_with_fixed_point_type)
7490 << SrcTy;
7491 return CK_IntegralCast;
7492 }
7493 llvm_unreachable("Should have returned before this");
7494 }
7495
7496 llvm_unreachable("Unhandled scalar cast");
7497}
7498
7499static bool breakDownVectorType(QualType type, uint64_t &len,
7500 QualType &eltType) {
7501 // Vectors are simple.
7502 if (const VectorType *vecType = type->getAs<VectorType>()) {
7503 len = vecType->getNumElements();
7504 eltType = vecType->getElementType();
7505 assert(eltType->isScalarType());
7506 return true;
7507 }
7508
7509 // We allow lax conversion to and from non-vector types, but only if
7510 // they're real types (i.e. non-complex, non-pointer scalar types).
7511 if (!type->isRealType()) return false;
7512
7513 len = 1;
7514 eltType = type;
7515 return true;
7516}
7517
7519 assert(srcTy->isVectorType() || destTy->isVectorType());
7520
7521 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7522 if (!FirstType->isSVESizelessBuiltinType())
7523 return false;
7524
7525 const auto *VecTy = SecondType->getAs<VectorType>();
7526 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7527 };
7528
7529 return ValidScalableConversion(srcTy, destTy) ||
7530 ValidScalableConversion(destTy, srcTy);
7531}
7532
7534 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7535 return false;
7536
7537 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7538 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7539
7540 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7541 matSrcType->getNumColumns() == matDestType->getNumColumns();
7542}
7543
7545 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7546
7547 uint64_t SrcLen, DestLen;
7548 QualType SrcEltTy, DestEltTy;
7549 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7550 return false;
7551 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7552 return false;
7553
7554 // ASTContext::getTypeSize will return the size rounded up to a
7555 // power of 2, so instead of using that, we need to use the raw
7556 // element size multiplied by the element count.
7557 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7558 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7559
7560 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7561}
7562
7564 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7565 "expected at least one type to be a vector here");
7566
7567 bool IsSrcTyAltivec =
7568 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7570 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7572 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7574
7575 bool IsDestTyAltivec = DestTy->isVectorType() &&
7576 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7578 (DestTy->castAs<VectorType>()->getVectorKind() ==
7580 (DestTy->castAs<VectorType>()->getVectorKind() ==
7582
7583 return (IsSrcTyAltivec || IsDestTyAltivec);
7584}
7585
7587 assert(destTy->isVectorType() || srcTy->isVectorType());
7588
7589 // Disallow lax conversions between scalars and ExtVectors (these
7590 // conversions are allowed for other vector types because common headers
7591 // depend on them). Most scalar OP ExtVector cases are handled by the
7592 // splat path anyway, which does what we want (convert, not bitcast).
7593 // What this rules out for ExtVectors is crazy things like char4*float.
7594 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7595 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7596
7597 return areVectorTypesSameSize(srcTy, destTy);
7598}
7599
7601 assert(destTy->isVectorType() || srcTy->isVectorType());
7602
7603 switch (Context.getLangOpts().getLaxVectorConversions()) {
7605 return false;
7606
7608 if (!srcTy->isIntegralOrEnumerationType()) {
7609 auto *Vec = srcTy->getAs<VectorType>();
7610 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7611 return false;
7612 }
7613 if (!destTy->isIntegralOrEnumerationType()) {
7614 auto *Vec = destTy->getAs<VectorType>();
7615 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7616 return false;
7617 }
7618 // OK, integer (vector) -> integer (vector) bitcast.
7619 break;
7620
7622 break;
7623 }
7624
7625 return areLaxCompatibleVectorTypes(srcTy, destTy);
7626}
7627
7629 CastKind &Kind) {
7630 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7631 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7632 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7633 << DestTy << SrcTy << R;
7634 }
7635 } else if (SrcTy->isMatrixType()) {
7636 return Diag(R.getBegin(),
7637 diag::err_invalid_conversion_between_matrix_and_type)
7638 << SrcTy << DestTy << R;
7639 } else if (DestTy->isMatrixType()) {
7640 return Diag(R.getBegin(),
7641 diag::err_invalid_conversion_between_matrix_and_type)
7642 << DestTy << SrcTy << R;
7643 }
7644
7645 Kind = CK_MatrixCast;
7646 return false;
7647}
7648
7650 CastKind &Kind) {
7651 assert(VectorTy->isVectorType() && "Not a vector type!");
7652
7653 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7654 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7655 return Diag(R.getBegin(),
7656 Ty->isVectorType() ?
7657 diag::err_invalid_conversion_between_vectors :
7658 diag::err_invalid_conversion_between_vector_and_integer)
7659 << VectorTy << Ty << R;
7660 } else
7661 return Diag(R.getBegin(),
7662 diag::err_invalid_conversion_between_vector_and_scalar)
7663 << VectorTy << Ty << R;
7664
7665 Kind = CK_BitCast;
7666 return false;
7667}
7668
7670 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7671
7672 if (DestElemTy == SplattedExpr->getType())
7673 return SplattedExpr;
7674
7675 assert(DestElemTy->isFloatingType() ||
7676 DestElemTy->isIntegralOrEnumerationType());
7677
7678 CastKind CK;
7679 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7680 // OpenCL requires that we convert `true` boolean expressions to -1, but
7681 // only when splatting vectors.
7682 if (DestElemTy->isFloatingType()) {
7683 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7684 // in two steps: boolean to signed integral, then to floating.
7685 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7686 CK_BooleanToSignedIntegral);
7687 SplattedExpr = CastExprRes.get();
7688 CK = CK_IntegralToFloating;
7689 } else {
7690 CK = CK_BooleanToSignedIntegral;
7691 }
7692 } else {
7693 ExprResult CastExprRes = SplattedExpr;
7694 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7695 if (CastExprRes.isInvalid())
7696 return ExprError();
7697 SplattedExpr = CastExprRes.get();
7698 }
7699 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7700}
7701
7703 Expr *CastExpr, CastKind &Kind) {
7704 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7705
7706 QualType SrcTy = CastExpr->getType();
7707
7708 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7709 // an ExtVectorType.
7710 // In OpenCL, casts between vectors of different types are not allowed.
7711 // (See OpenCL 6.2).
7712 if (SrcTy->isVectorType()) {
7713 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7714 (getLangOpts().OpenCL &&
7715 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7716 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7717 << DestTy << SrcTy << R;
7718 return ExprError();
7719 }
7720 Kind = CK_BitCast;
7721 return CastExpr;
7722 }
7723
7724 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7725 // conversion will take place first from scalar to elt type, and then
7726 // splat from elt type to vector.
7727 if (SrcTy->isPointerType())
7728 return Diag(R.getBegin(),
7729 diag::err_invalid_conversion_between_vector_and_scalar)
7730 << DestTy << SrcTy << R;
7731
7732 Kind = CK_VectorSplat;
7733 return prepareVectorSplat(DestTy, CastExpr);
7734}
7735
7738 Declarator &D, ParsedType &Ty,
7739 SourceLocation RParenLoc, Expr *CastExpr) {
7740 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7741 "ActOnCastExpr(): missing type or expr");
7742
7744 if (D.isInvalidType())
7745 return ExprError();
7746
7747 if (getLangOpts().CPlusPlus) {
7748 // Check that there are no default arguments (C++ only).
7750 } else {
7751 // Make sure any TypoExprs have been dealt with.
7753 if (!Res.isUsable())
7754 return ExprError();
7755 CastExpr = Res.get();
7756 }
7757
7759
7760 QualType castType = castTInfo->getType();
7761 Ty = CreateParsedType(castType, castTInfo);
7762
7763 bool isVectorLiteral = false;
7764
7765 // Check for an altivec or OpenCL literal,
7766 // i.e. all the elements are integer constants.
7767 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7768 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7769 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7770 && castType->isVectorType() && (PE || PLE)) {
7771 if (PLE && PLE->getNumExprs() == 0) {
7772 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7773 return ExprError();
7774 }
7775 if (PE || PLE->getNumExprs() == 1) {
7776 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7777 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7778 isVectorLiteral = true;
7779 }
7780 else
7781 isVectorLiteral = true;
7782 }
7783
7784 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7785 // then handle it as such.
7786 if (isVectorLiteral)
7787 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7788
7789 // If the Expr being casted is a ParenListExpr, handle it specially.
7790 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7791 // sequence of BinOp comma operators.
7792 if (isa<ParenListExpr>(CastExpr)) {
7794 if (Result.isInvalid()) return ExprError();
7795 CastExpr = Result.get();
7796 }
7797
7798 if (getLangOpts().CPlusPlus && !castType->isVoidType())
7799 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7800
7802
7804
7806
7807 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7808}
7809
7811 SourceLocation RParenLoc, Expr *E,
7812 TypeSourceInfo *TInfo) {
7813 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7814 "Expected paren or paren list expression");
7815
7816 Expr **exprs;
7817 unsigned numExprs;
7818 Expr *subExpr;
7819 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7820 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7821 LiteralLParenLoc = PE->getLParenLoc();
7822 LiteralRParenLoc = PE->getRParenLoc();
7823 exprs = PE->getExprs();
7824 numExprs = PE->getNumExprs();
7825 } else { // isa<ParenExpr> by assertion at function entrance
7826 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7827 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7828 subExpr = cast<ParenExpr>(E)->getSubExpr();
7829 exprs = &subExpr;
7830 numExprs = 1;
7831 }
7832
7833 QualType Ty = TInfo->getType();
7834 assert(Ty->isVectorType() && "Expected vector type");
7835
7836 SmallVector<Expr *, 8> initExprs;
7837 const VectorType *VTy = Ty->castAs<VectorType>();
7838 unsigned numElems = VTy->getNumElements();
7839
7840 // '(...)' form of vector initialization in AltiVec: the number of
7841 // initializers must be one or must match the size of the vector.
7842 // If a single value is specified in the initializer then it will be
7843 // replicated to all the components of the vector
7845 VTy->getElementType()))
7846 return ExprError();
7848 // The number of initializers must be one or must match the size of the
7849 // vector. If a single value is specified in the initializer then it will
7850 // be replicated to all the components of the vector
7851 if (numExprs == 1) {
7852 QualType ElemTy = VTy->getElementType();
7853 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7854 if (Literal.isInvalid())
7855 return ExprError();
7856 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7857 PrepareScalarCast(Literal, ElemTy));
7858 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7859 }
7860 else if (numExprs < numElems) {
7861 Diag(E->getExprLoc(),
7862 diag::err_incorrect_number_of_vector_initializers);
7863 return ExprError();
7864 }
7865 else
7866 initExprs.append(exprs, exprs + numExprs);
7867 }
7868 else {
7869 // For OpenCL, when the number of initializers is a single value,
7870 // it will be replicated to all components of the vector.
7872 numExprs == 1) {
7873 QualType ElemTy = VTy->getElementType();
7874 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7875 if (Literal.isInvalid())
7876 return ExprError();
7877 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7878 PrepareScalarCast(Literal, ElemTy));
7879 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7880 }
7881
7882 initExprs.append(exprs, exprs + numExprs);
7883 }
7884 // FIXME: This means that pretty-printing the final AST will produce curly
7885 // braces instead of the original commas.
7886 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7887 initExprs, LiteralRParenLoc);
7888 initE->setType(Ty);
7889 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7890}
7891
7894 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7895 if (!E)
7896 return OrigExpr;
7897
7898 ExprResult Result(E->getExpr(0));
7899
7900 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7901 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7902 E->getExpr(i));
7903
7904 if (Result.isInvalid()) return ExprError();
7905
7906 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7907}
7908
7911 MultiExprArg Val) {
7912 return ParenListExpr::Create(Context, L, Val, R);
7913}
7914
7915bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7916 SourceLocation QuestionLoc) {
7917 const Expr *NullExpr = LHSExpr;
7918 const Expr *NonPointerExpr = RHSExpr;
7922
7923 if (NullKind == Expr::NPCK_NotNull) {
7924 NullExpr = RHSExpr;
7925 NonPointerExpr = LHSExpr;
7926 NullKind =
7929 }
7930
7931 if (NullKind == Expr::NPCK_NotNull)
7932 return false;
7933
7934 if (NullKind == Expr::NPCK_ZeroExpression)
7935 return false;
7936
7937 if (NullKind == Expr::NPCK_ZeroLiteral) {
7938 // In this case, check to make sure that we got here from a "NULL"
7939 // string in the source code.
7940 NullExpr = NullExpr->IgnoreParenImpCasts();
7941 SourceLocation loc = NullExpr->getExprLoc();
7942 if (!findMacroSpelling(loc, "NULL"))
7943 return false;
7944 }
7945
7946 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7947 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7948 << NonPointerExpr->getType() << DiagType
7949 << NonPointerExpr->getSourceRange();
7950 return true;
7951}
7952
7953/// Return false if the condition expression is valid, true otherwise.
7954static bool checkCondition(Sema &S, const Expr *Cond,
7955 SourceLocation QuestionLoc) {
7956 QualType CondTy = Cond->getType();
7957
7958 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7959 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7960 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7961 << CondTy << Cond->getSourceRange();
7962 return true;
7963 }
7964
7965 // C99 6.5.15p2
7966 if (CondTy->isScalarType()) return false;
7967
7968 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7969 << CondTy << Cond->getSourceRange();
7970 return true;
7971}
7972
7973/// Return false if the NullExpr can be promoted to PointerTy,
7974/// true otherwise.
7976 QualType PointerTy) {
7977 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7978 !NullExpr.get()->isNullPointerConstant(S.Context,
7980 return true;
7981
7982 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7983 return false;
7984}
7985
7986/// Checks compatibility between two pointers and return the resulting
7987/// type.
7989 ExprResult &RHS,
7991 QualType LHSTy = LHS.get()->getType();
7992 QualType RHSTy = RHS.get()->getType();
7993
7994 if (S.Context.hasSameType(LHSTy, RHSTy)) {
7995 // Two identical pointers types are always compatible.
7996 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
7997 }
7998
7999 QualType lhptee, rhptee;
8000
8001 // Get the pointee types.
8002 bool IsBlockPointer = false;
8003 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8004 lhptee = LHSBTy->getPointeeType();
8005 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8006 IsBlockPointer = true;
8007 } else {
8008 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8009 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8010 }
8011
8012 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8013 // differently qualified versions of compatible types, the result type is
8014 // a pointer to an appropriately qualified version of the composite
8015 // type.
8016
8017 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8018 // clause doesn't make sense for our extensions. E.g. address space 2 should
8019 // be incompatible with address space 3: they may live on different devices or
8020 // anything.
8021 Qualifiers lhQual = lhptee.getQualifiers();
8022 Qualifiers rhQual = rhptee.getQualifiers();
8023
8024 LangAS ResultAddrSpace = LangAS::Default;
8025 LangAS LAddrSpace = lhQual.getAddressSpace();
8026 LangAS RAddrSpace = rhQual.getAddressSpace();
8027
8028 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8029 // spaces is disallowed.
8030 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8031 ResultAddrSpace = LAddrSpace;
8032 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8033 ResultAddrSpace = RAddrSpace;
8034 else {
8035 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8036 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8037 << RHS.get()->getSourceRange();
8038 return QualType();
8039 }
8040
8041 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8042 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8043 lhQual.removeCVRQualifiers();
8044 rhQual.removeCVRQualifiers();
8045
8046 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8047 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8048 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8049 // qual types are compatible iff
8050 // * corresponded types are compatible
8051 // * CVR qualifiers are equal
8052 // * address spaces are equal
8053 // Thus for conditional operator we merge CVR and address space unqualified
8054 // pointees and if there is a composite type we return a pointer to it with
8055 // merged qualifiers.
8056 LHSCastKind =
8057 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8058 RHSCastKind =
8059 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8060 lhQual.removeAddressSpace();
8061 rhQual.removeAddressSpace();
8062
8063 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8064 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8065
8066 QualType CompositeTy = S.Context.mergeTypes(
8067 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8068 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8069
8070 if (CompositeTy.isNull()) {
8071 // In this situation, we assume void* type. No especially good
8072 // reason, but this is what gcc does, and we do have to pick
8073 // to get a consistent AST.
8074 QualType incompatTy;
8075 incompatTy = S.Context.getPointerType(
8076 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8077 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8078 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8079
8080 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8081 // for casts between types with incompatible address space qualifiers.
8082 // For the following code the compiler produces casts between global and
8083 // local address spaces of the corresponded innermost pointees:
8084 // local int *global *a;
8085 // global int *global *b;
8086 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8087 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8088 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8089 << RHS.get()->getSourceRange();
8090
8091 return incompatTy;
8092 }
8093
8094 // The pointer types are compatible.
8095 // In case of OpenCL ResultTy should have the address space qualifier
8096 // which is a superset of address spaces of both the 2nd and the 3rd
8097 // operands of the conditional operator.
8098 QualType ResultTy = [&, ResultAddrSpace]() {
8099 if (S.getLangOpts().OpenCL) {
8100 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8101 CompositeQuals.setAddressSpace(ResultAddrSpace);
8102 return S.Context
8103 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8104 .withCVRQualifiers(MergedCVRQual);
8105 }
8106 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8107 }();
8108 if (IsBlockPointer)
8109 ResultTy = S.Context.getBlockPointerType(ResultTy);
8110 else
8111 ResultTy = S.Context.getPointerType(ResultTy);
8112
8113 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8114 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8115 return ResultTy;
8116}
8117
8118/// Return the resulting type when the operands are both block pointers.
8120 ExprResult &LHS,
8121 ExprResult &RHS,
8123 QualType LHSTy = LHS.get()->getType();
8124 QualType RHSTy = RHS.get()->getType();
8125
8126 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8127 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8129 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8130 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8131 return destType;
8132 }
8133 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8134 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8135 << RHS.get()->getSourceRange();
8136 return QualType();
8137 }
8138
8139 // We have 2 block pointer types.
8140 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8141}
8142
8143/// Return the resulting type when the operands are both pointers.
8144static QualType
8146 ExprResult &RHS,
8148 // get the pointer types
8149 QualType LHSTy = LHS.get()->getType();
8150 QualType RHSTy = RHS.get()->getType();
8151
8152 // get the "pointed to" types
8153 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8154 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8155
8156 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8157 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8158 // Figure out necessary qualifiers (C99 6.5.15p6)
8159 QualType destPointee
8160 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8161 QualType destType = S.Context.getPointerType(destPointee);
8162 // Add qualifiers if necessary.
8163 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8164 // Promote to void*.
8165 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8166 return destType;
8167 }
8168 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8169 QualType destPointee
8170 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8171 QualType destType = S.Context.getPointerType(destPointee);
8172 // Add qualifiers if necessary.
8173 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8174 // Promote to void*.
8175 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8176 return destType;
8177 }
8178
8179 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8180}
8181
8182/// Return false if the first expression is not an integer and the second
8183/// expression is not a pointer, true otherwise.
8185 Expr* PointerExpr, SourceLocation Loc,
8186 bool IsIntFirstExpr) {
8187 if (!PointerExpr->getType()->isPointerType() ||
8188 !Int.get()->getType()->isIntegerType())
8189 return false;
8190
8191 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8192 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8193
8194 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8195 << Expr1->getType() << Expr2->getType()
8196 << Expr1->getSourceRange() << Expr2->getSourceRange();
8197 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8198 CK_IntegralToPointer);
8199 return true;
8200}
8201
8202/// Simple conversion between integer and floating point types.
8203///
8204/// Used when handling the OpenCL conditional operator where the
8205/// condition is a vector while the other operands are scalar.
8206///
8207/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8208/// types are either integer or floating type. Between the two
8209/// operands, the type with the higher rank is defined as the "result
8210/// type". The other operand needs to be promoted to the same type. No
8211/// other type promotion is allowed. We cannot use
8212/// UsualArithmeticConversions() for this purpose, since it always
8213/// promotes promotable types.
8215 ExprResult &RHS,
8216 SourceLocation QuestionLoc) {
8218 if (LHS.isInvalid())
8219 return QualType();
8221 if (RHS.isInvalid())
8222 return QualType();
8223
8224 // For conversion purposes, we ignore any qualifiers.
8225 // For example, "const float" and "float" are equivalent.
8226 QualType LHSType =
8228 QualType RHSType =
8230
8231 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8232 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8233 << LHSType << LHS.get()->getSourceRange();
8234 return QualType();
8235 }
8236
8237 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8238 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8239 << RHSType << RHS.get()->getSourceRange();
8240 return QualType();
8241 }
8242
8243 // If both types are identical, no conversion is needed.
8244 if (LHSType == RHSType)
8245 return LHSType;
8246
8247 // Now handle "real" floating types (i.e. float, double, long double).
8248 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8249 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8250 /*IsCompAssign = */ false);
8251
8252 // Finally, we have two differing integer types.
8253 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8254 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8255}
8256
8257/// Convert scalar operands to a vector that matches the
8258/// condition in length.
8259///
8260/// Used when handling the OpenCL conditional operator where the
8261/// condition is a vector while the other operands are scalar.
8262///
8263/// We first compute the "result type" for the scalar operands
8264/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8265/// into a vector of that type where the length matches the condition
8266/// vector type. s6.11.6 requires that the element types of the result
8267/// and the condition must have the same number of bits.
8268static QualType
8270 QualType CondTy, SourceLocation QuestionLoc) {
8271 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8272 if (ResTy.isNull()) return QualType();
8273
8274 const VectorType *CV = CondTy->getAs<VectorType>();
8275 assert(CV);
8276
8277 // Determine the vector result type
8278 unsigned NumElements = CV->getNumElements();
8279 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8280
8281 // Ensure that all types have the same number of bits
8283 != S.Context.getTypeSize(ResTy)) {
8284 // Since VectorTy is created internally, it does not pretty print
8285 // with an OpenCL name. Instead, we just print a description.
8286 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8287 SmallString<64> Str;
8288 llvm::raw_svector_ostream OS(Str);
8289 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8290 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8291 << CondTy << OS.str();
8292 return QualType();
8293 }
8294
8295 // Convert operands to the vector result type
8296 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8297 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8298
8299 return VectorTy;
8300}
8301
8302/// Return false if this is a valid OpenCL condition vector
8304 SourceLocation QuestionLoc) {
8305 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8306 // integral type.
8307 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8308 assert(CondTy);
8309 QualType EleTy = CondTy->getElementType();
8310 if (EleTy->isIntegerType()) return false;
8311
8312 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8313 << Cond->getType() << Cond->getSourceRange();
8314 return true;
8315}
8316
8317/// Return false if the vector condition type and the vector
8318/// result type are compatible.
8319///
8320/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8321/// number of elements, and their element types have the same number
8322/// of bits.
8323static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8324 SourceLocation QuestionLoc) {
8325 const VectorType *CV = CondTy->getAs<VectorType>();
8326 const VectorType *RV = VecResTy->getAs<VectorType>();
8327 assert(CV && RV);
8328
8329 if (CV->getNumElements() != RV->getNumElements()) {
8330 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8331 << CondTy << VecResTy;
8332 return true;
8333 }
8334
8335 QualType CVE = CV->getElementType();
8336 QualType RVE = RV->getElementType();
8337
8338 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8339 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8340 << CondTy << VecResTy;
8341 return true;
8342 }
8343
8344 return false;
8345}
8346
8347/// Return the resulting type for the conditional operator in
8348/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8349/// s6.3.i) when the condition is a vector type.
8350static QualType
8352 ExprResult &LHS, ExprResult &RHS,
8353 SourceLocation QuestionLoc) {
8355 if (Cond.isInvalid())
8356 return QualType();
8357 QualType CondTy = Cond.get()->getType();
8358
8359 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8360 return QualType();
8361
8362 // If either operand is a vector then find the vector type of the
8363 // result as specified in OpenCL v1.1 s6.3.i.
8364 if (LHS.get()->getType()->isVectorType() ||
8365 RHS.get()->getType()->isVectorType()) {
8366 bool IsBoolVecLang =
8367 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8368 QualType VecResTy =
8369 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8370 /*isCompAssign*/ false,
8371 /*AllowBothBool*/ true,
8372 /*AllowBoolConversions*/ false,
8373 /*AllowBooleanOperation*/ IsBoolVecLang,
8374 /*ReportInvalid*/ true);
8375 if (VecResTy.isNull())
8376 return QualType();
8377 // The result type must match the condition type as specified in
8378 // OpenCL v1.1 s6.11.6.
8379 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8380 return QualType();
8381 return VecResTy;
8382 }
8383
8384 // Both operands are scalar.
8385 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8386}
8387
8388/// Return true if the Expr is block type
8389static bool checkBlockType(Sema &S, const Expr *E) {
8390 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8391 QualType Ty = CE->getCallee()->getType();
8392 if (Ty->isBlockPointerType()) {
8393 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8394 return true;
8395 }
8396 }
8397 return false;
8398}
8399
8400/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8401/// In that case, LHS = cond.
8402/// C99 6.5.15
8404 ExprResult &RHS, ExprValueKind &VK,
8405 ExprObjectKind &OK,
8406 SourceLocation QuestionLoc) {
8407
8408 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8409 if (!LHSResult.isUsable()) return QualType();
8410 LHS = LHSResult;
8411
8412 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8413 if (!RHSResult.isUsable()) return QualType();
8414 RHS = RHSResult;
8415
8416 // C++ is sufficiently different to merit its own checker.
8417 if (getLangOpts().CPlusPlus)
8418 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8419
8420 VK = VK_PRValue;
8421 OK = OK_Ordinary;
8422
8424 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8425 RHS.get()->isTypeDependent())) {
8426 assert(!getLangOpts().CPlusPlus);
8427 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8428 RHS.get()->containsErrors()) &&
8429 "should only occur in error-recovery path.");
8430 return Context.DependentTy;
8431 }
8432
8433 // The OpenCL operator with a vector condition is sufficiently
8434 // different to merit its own checker.
8435 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8436 Cond.get()->getType()->isExtVectorType())
8437 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8438
8439 // First, check the condition.
8440 Cond = UsualUnaryConversions(Cond.get());
8441 if (Cond.isInvalid())
8442 return QualType();
8443 if (checkCondition(*this, Cond.get(), QuestionLoc))
8444 return QualType();
8445
8446 // Handle vectors.
8447 if (LHS.get()->getType()->isVectorType() ||
8448 RHS.get()->getType()->isVectorType())
8449 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8450 /*AllowBothBool*/ true,
8451 /*AllowBoolConversions*/ false,
8452 /*AllowBooleanOperation*/ false,
8453 /*ReportInvalid*/ true);
8454
8455 QualType ResTy =
8456 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8457 if (LHS.isInvalid() || RHS.isInvalid())
8458 return QualType();
8459
8460 // WebAssembly tables are not allowed as conditional LHS or RHS.
8461 QualType LHSTy = LHS.get()->getType();
8462 QualType RHSTy = RHS.get()->getType();
8463 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8464 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8465 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8466 return QualType();
8467 }
8468
8469 // Diagnose attempts to convert between __ibm128, __float128 and long double
8470 // where such conversions currently can't be handled.
8471 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8472 Diag(QuestionLoc,
8473 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8474 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8475 return QualType();
8476 }
8477
8478 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8479 // selection operator (?:).
8480 if (getLangOpts().OpenCL &&
8481 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8482 return QualType();
8483 }
8484
8485 // If both operands have arithmetic type, do the usual arithmetic conversions
8486 // to find a common type: C99 6.5.15p3,5.
8487 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8488 // Disallow invalid arithmetic conversions, such as those between bit-
8489 // precise integers types of different sizes, or between a bit-precise
8490 // integer and another type.
8491 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8492 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8493 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8494 << RHS.get()->getSourceRange();
8495 return QualType();
8496 }
8497
8498 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8499 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8500
8501 return ResTy;
8502 }
8503
8504 // If both operands are the same structure or union type, the result is that
8505 // type.
8506 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8507 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8508 if (LHSRT->getDecl() == RHSRT->getDecl())
8509 // "If both the operands have structure or union type, the result has
8510 // that type." This implies that CV qualifiers are dropped.
8512 RHSTy.getUnqualifiedType());
8513 // FIXME: Type of conditional expression must be complete in C mode.
8514 }
8515
8516 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8517 // The following || allows only one side to be void (a GCC-ism).
8518 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8519 QualType ResTy;
8520 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8521 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8522 } else if (RHSTy->isVoidType()) {
8523 ResTy = RHSTy;
8524 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8525 << RHS.get()->getSourceRange();
8526 } else {
8527 ResTy = LHSTy;
8528 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8529 << LHS.get()->getSourceRange();
8530 }
8531 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8532 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8533 return ResTy;
8534 }
8535
8536 // C23 6.5.15p7:
8537 // ... if both the second and third operands have nullptr_t type, the
8538 // result also has that type.
8539 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8540 return ResTy;
8541
8542 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8543 // the type of the other operand."
8544 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8545 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8546
8547 // All objective-c pointer type analysis is done here.
8548 QualType compositeType =
8549 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8550 if (LHS.isInvalid() || RHS.isInvalid())
8551 return QualType();
8552 if (!compositeType.isNull())
8553 return compositeType;
8554
8555
8556 // Handle block pointer types.
8557 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8558 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8559 QuestionLoc);
8560
8561 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8562 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8563 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8564 QuestionLoc);
8565
8566 // GCC compatibility: soften pointer/integer mismatch. Note that
8567 // null pointers have been filtered out by this point.
8568 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8569 /*IsIntFirstExpr=*/true))
8570 return RHSTy;
8571 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8572 /*IsIntFirstExpr=*/false))
8573 return LHSTy;
8574
8575 // Emit a better diagnostic if one of the expressions is a null pointer
8576 // constant and the other is not a pointer type. In this case, the user most
8577 // likely forgot to take the address of the other expression.
8578 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8579 return QualType();
8580
8581 // Finally, if the LHS and RHS types are canonically the same type, we can
8582 // use the common sugared type.
8583 if (Context.hasSameType(LHSTy, RHSTy))
8584 return Context.getCommonSugaredType(LHSTy, RHSTy);
8585
8586 // Otherwise, the operands are not compatible.
8587 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8588 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8589 << RHS.get()->getSourceRange();
8590 return QualType();
8591}
8592
8593/// SuggestParentheses - Emit a note with a fixit hint that wraps
8594/// ParenRange in parentheses.
8596 const PartialDiagnostic &Note,
8597 SourceRange ParenRange) {
8598 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8599 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8600 EndLoc.isValid()) {
8601 Self.Diag(Loc, Note)
8602 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8603 << FixItHint::CreateInsertion(EndLoc, ")");
8604 } else {
8605 // We can't display the parentheses, so just show the bare note.
8606 Self.Diag(Loc, Note) << ParenRange;
8607 }
8608}
8609
8611 return BinaryOperator::isAdditiveOp(Opc) ||
8613 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8614 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8615 // not any of the logical operators. Bitwise-xor is commonly used as a
8616 // logical-xor because there is no logical-xor operator. The logical
8617 // operators, including uses of xor, have a high false positive rate for
8618 // precedence warnings.
8619}
8620
8621/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8622/// expression, either using a built-in or overloaded operator,
8623/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8624/// expression.
8626 const Expr **RHSExprs) {
8627 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8628 E = E->IgnoreImpCasts();
8630 E = E->IgnoreImpCasts();
8631 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8632 E = MTE->getSubExpr();
8633 E = E->IgnoreImpCasts();
8634 }
8635
8636 // Built-in binary operator.
8637 if (const auto *OP = dyn_cast<BinaryOperator>(E);
8638 OP && IsArithmeticOp(OP->getOpcode())) {
8639 *Opcode = OP->getOpcode();
8640 *RHSExprs = OP->getRHS();
8641 return true;
8642 }
8643
8644 // Overloaded operator.
8645 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8646 if (Call->getNumArgs() != 2)
8647 return false;
8648
8649 // Make sure this is really a binary operator that is safe to pass into
8650 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8651 OverloadedOperatorKind OO = Call->getOperator();
8652 if (OO < OO_Plus || OO > OO_Arrow ||
8653 OO == OO_PlusPlus || OO == OO_MinusMinus)
8654 return false;
8655
8657 if (IsArithmeticOp(OpKind)) {
8658 *Opcode = OpKind;
8659 *RHSExprs = Call->getArg(1);
8660 return true;
8661 }
8662 }
8663
8664 return false;
8665}
8666
8667/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8668/// or is a logical expression such as (x==y) which has int type, but is
8669/// commonly interpreted as boolean.
8670static bool ExprLooksBoolean(const Expr *E) {
8671 E = E->IgnoreParenImpCasts();
8672
8673 if (E->getType()->isBooleanType())
8674 return true;
8675 if (const auto *OP = dyn_cast<BinaryOperator>(E))
8676 return OP->isComparisonOp() || OP->isLogicalOp();
8677 if (const auto *OP = dyn_cast<UnaryOperator>(E))
8678 return OP->getOpcode() == UO_LNot;
8679 if (E->getType()->isPointerType())
8680 return true;
8681 // FIXME: What about overloaded operator calls returning "unspecified boolean
8682 // type"s (commonly pointer-to-members)?
8683
8684 return false;
8685}
8686
8687/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8688/// and binary operator are mixed in a way that suggests the programmer assumed
8689/// the conditional operator has higher precedence, for example:
8690/// "int x = a + someBinaryCondition ? 1 : 2".
8692 Expr *Condition, const Expr *LHSExpr,
8693 const Expr *RHSExpr) {
8694 BinaryOperatorKind CondOpcode;
8695 const Expr *CondRHS;
8696
8697 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8698 return;
8699 if (!ExprLooksBoolean(CondRHS))
8700 return;
8701
8702 // The condition is an arithmetic binary expression, with a right-
8703 // hand side that looks boolean, so warn.
8704
8705 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8706 ? diag::warn_precedence_bitwise_conditional
8707 : diag::warn_precedence_conditional;
8708
8709 Self.Diag(OpLoc, DiagID)
8710 << Condition->getSourceRange()
8711 << BinaryOperator::getOpcodeStr(CondOpcode);
8712
8714 Self, OpLoc,
8715 Self.PDiag(diag::note_precedence_silence)
8716 << BinaryOperator::getOpcodeStr(CondOpcode),
8717 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8718
8719 SuggestParentheses(Self, OpLoc,
8720 Self.PDiag(diag::note_precedence_conditional_first),
8721 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8722}
8723
8724/// Compute the nullability of a conditional expression.
8726 QualType LHSTy, QualType RHSTy,
8727 ASTContext &Ctx) {
8728 if (!ResTy->isAnyPointerType())
8729 return ResTy;
8730
8731 auto GetNullability = [](QualType Ty) {
8732 std::optional<NullabilityKind> Kind = Ty->getNullability();
8733 if (Kind) {
8734 // For our purposes, treat _Nullable_result as _Nullable.
8737 return *Kind;
8738 }
8740 };
8741
8742 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8743 NullabilityKind MergedKind;
8744
8745 // Compute nullability of a binary conditional expression.
8746 if (IsBin) {
8747 if (LHSKind == NullabilityKind::NonNull)
8748 MergedKind = NullabilityKind::NonNull;
8749 else
8750 MergedKind = RHSKind;
8751 // Compute nullability of a normal conditional expression.
8752 } else {
8753 if (LHSKind == NullabilityKind::Nullable ||
8754 RHSKind == NullabilityKind::Nullable)
8755 MergedKind = NullabilityKind::Nullable;
8756 else if (LHSKind == NullabilityKind::NonNull)
8757 MergedKind = RHSKind;
8758 else if (RHSKind == NullabilityKind::NonNull)
8759 MergedKind = LHSKind;
8760 else
8761 MergedKind = NullabilityKind::Unspecified;
8762 }
8763
8764 // Return if ResTy already has the correct nullability.
8765 if (GetNullability(ResTy) == MergedKind)
8766 return ResTy;
8767
8768 // Strip all nullability from ResTy.
8769 while (ResTy->getNullability())
8770 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8771
8772 // Create a new AttributedType with the new nullability kind.
8773 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
8774}
8775
8777 SourceLocation ColonLoc,
8778 Expr *CondExpr, Expr *LHSExpr,
8779 Expr *RHSExpr) {
8781 // C cannot handle TypoExpr nodes in the condition because it
8782 // doesn't handle dependent types properly, so make sure any TypoExprs have
8783 // been dealt with before checking the operands.
8784 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8785 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8786 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8787
8788 if (!CondResult.isUsable())
8789 return ExprError();
8790
8791 if (LHSExpr) {
8792 if (!LHSResult.isUsable())
8793 return ExprError();
8794 }
8795
8796 if (!RHSResult.isUsable())
8797 return ExprError();
8798
8799 CondExpr = CondResult.get();
8800 LHSExpr = LHSResult.get();
8801 RHSExpr = RHSResult.get();
8802 }
8803
8804 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8805 // was the condition.
8806 OpaqueValueExpr *opaqueValue = nullptr;
8807 Expr *commonExpr = nullptr;
8808 if (!LHSExpr) {
8809 commonExpr = CondExpr;
8810 // Lower out placeholder types first. This is important so that we don't
8811 // try to capture a placeholder. This happens in few cases in C++; such
8812 // as Objective-C++'s dictionary subscripting syntax.
8813 if (commonExpr->hasPlaceholderType()) {
8814 ExprResult result = CheckPlaceholderExpr(commonExpr);
8815 if (!result.isUsable()) return ExprError();
8816 commonExpr = result.get();
8817 }
8818 // We usually want to apply unary conversions *before* saving, except
8819 // in the special case of a C++ l-value conditional.
8820 if (!(getLangOpts().CPlusPlus
8821 && !commonExpr->isTypeDependent()
8822 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8823 && commonExpr->isGLValue()
8824 && commonExpr->isOrdinaryOrBitFieldObject()
8825 && RHSExpr->isOrdinaryOrBitFieldObject()
8826 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8827 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8828 if (commonRes.isInvalid())
8829 return ExprError();
8830 commonExpr = commonRes.get();
8831 }
8832
8833 // If the common expression is a class or array prvalue, materialize it
8834 // so that we can safely refer to it multiple times.
8835 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8836 commonExpr->getType()->isArrayType())) {
8837 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8838 if (MatExpr.isInvalid())
8839 return ExprError();
8840 commonExpr = MatExpr.get();
8841 }
8842
8843 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8844 commonExpr->getType(),
8845 commonExpr->getValueKind(),
8846 commonExpr->getObjectKind(),
8847 commonExpr);
8848 LHSExpr = CondExpr = opaqueValue;
8849 }
8850
8851 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8854 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8855 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8856 VK, OK, QuestionLoc);
8857 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8858 RHS.isInvalid())
8859 return ExprError();
8860
8861 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8862 RHS.get());
8863
8864 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8865
8866 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8867 Context);
8868
8869 if (!commonExpr)
8870 return new (Context)
8871 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8872 RHS.get(), result, VK, OK);
8873
8875 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8876 ColonLoc, result, VK, OK);
8877}
8878
8880 unsigned FromAttributes = 0, ToAttributes = 0;
8881 if (const auto *FromFn =
8882 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
8883 FromAttributes =
8884 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8885 if (const auto *ToFn =
8886 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
8887 ToAttributes =
8888 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8889
8890 return FromAttributes != ToAttributes;
8891}
8892
8893// Check if we have a conversion between incompatible cmse function pointer
8894// types, that is, a conversion between a function pointer with the
8895// cmse_nonsecure_call attribute and one without.
8897 QualType ToType) {
8898 if (const auto *ToFn =
8899 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8900 if (const auto *FromFn =
8901 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8902 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8903 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8904
8905 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8906 }
8907 }
8908 return false;
8909}
8910
8911// checkPointerTypesForAssignment - This is a very tricky routine (despite
8912// being closely modeled after the C99 spec:-). The odd characteristic of this
8913// routine is it effectively iqnores the qualifiers on the top level pointee.
8914// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8915// FIXME: add a couple examples in this comment.
8919 assert(LHSType.isCanonical() && "LHS not canonicalized!");
8920 assert(RHSType.isCanonical() && "RHS not canonicalized!");
8921
8922 // get the "pointed to" type (ignoring qualifiers at the top level)
8923 const Type *lhptee, *rhptee;
8924 Qualifiers lhq, rhq;
8925 std::tie(lhptee, lhq) =
8926 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8927 std::tie(rhptee, rhq) =
8928 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8929
8931
8932 // C99 6.5.16.1p1: This following citation is common to constraints
8933 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8934 // qualifiers of the type *pointed to* by the right;
8935
8936 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8937 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8939 // Ignore lifetime for further calculation.
8940 lhq.removeObjCLifetime();
8941 rhq.removeObjCLifetime();
8942 }
8943
8944 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
8945 // Treat address-space mismatches as fatal.
8946 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
8948
8949 // It's okay to add or remove GC or lifetime qualifiers when converting to
8950 // and from void*.
8953 S.getASTContext()) &&
8954 (lhptee->isVoidType() || rhptee->isVoidType()))
8955 ; // keep old
8956
8957 // Treat lifetime mismatches as fatal.
8958 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8960
8961 // For GCC/MS compatibility, other qualifier mismatches are treated
8962 // as still compatible in C.
8964 }
8965
8966 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8967 // incomplete type and the other is a pointer to a qualified or unqualified
8968 // version of void...
8969 if (lhptee->isVoidType()) {
8970 if (rhptee->isIncompleteOrObjectType())
8971 return ConvTy;
8972
8973 // As an extension, we allow cast to/from void* to function pointer.
8974 assert(rhptee->isFunctionType());
8976 }
8977
8978 if (rhptee->isVoidType()) {
8979 if (lhptee->isIncompleteOrObjectType())
8980 return ConvTy;
8981
8982 // As an extension, we allow cast to/from void* to function pointer.
8983 assert(lhptee->isFunctionType());
8985 }
8986
8987 if (!S.Diags.isIgnored(
8988 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
8989 Loc) &&
8990 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
8991 !S.IsFunctionConversion(RHSType, LHSType, RHSType))
8993
8994 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
8995 // unqualified versions of compatible types, ...
8996 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
8997 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
8998 // Check if the pointee types are compatible ignoring the sign.
8999 // We explicitly check for char so that we catch "char" vs
9000 // "unsigned char" on systems where "char" is unsigned.
9001 if (lhptee->isCharType())
9002 ltrans = S.Context.UnsignedCharTy;
9003 else if (lhptee->hasSignedIntegerRepresentation())
9004 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9005
9006 if (rhptee->isCharType())
9007 rtrans = S.Context.UnsignedCharTy;
9008 else if (rhptee->hasSignedIntegerRepresentation())
9009 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9010
9011 if (ltrans == rtrans) {
9012 // Types are compatible ignoring the sign. Qualifier incompatibility
9013 // takes priority over sign incompatibility because the sign
9014 // warning can be disabled.
9015 if (ConvTy != Sema::Compatible)
9016 return ConvTy;
9017
9019 }
9020
9021 // If we are a multi-level pointer, it's possible that our issue is simply
9022 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9023 // the eventual target type is the same and the pointers have the same
9024 // level of indirection, this must be the issue.
9025 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9026 do {
9027 std::tie(lhptee, lhq) =
9028 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9029 std::tie(rhptee, rhq) =
9030 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9031
9032 // Inconsistent address spaces at this point is invalid, even if the
9033 // address spaces would be compatible.
9034 // FIXME: This doesn't catch address space mismatches for pointers of
9035 // different nesting levels, like:
9036 // __local int *** a;
9037 // int ** b = a;
9038 // It's not clear how to actually determine when such pointers are
9039 // invalidly incompatible.
9040 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9042
9043 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9044
9045 if (lhptee == rhptee)
9047 }
9048
9049 // General pointer incompatibility takes priority over qualifiers.
9050 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9053 }
9054 if (!S.getLangOpts().CPlusPlus &&
9055 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9057 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9059 if (S.IsInvalidSMECallConversion(rtrans, ltrans))
9061 return ConvTy;
9062}
9063
9064/// checkBlockPointerTypesForAssignment - This routine determines whether two
9065/// block pointer types are compatible or whether a block and normal pointer
9066/// are compatible. It is more restrict than comparing two function pointer
9067// types.
9070 QualType RHSType) {
9071 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9072 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9073
9074 QualType lhptee, rhptee;
9075
9076 // get the "pointed to" type (ignoring qualifiers at the top level)
9077 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9078 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9079
9080 // In C++, the types have to match exactly.
9081 if (S.getLangOpts().CPlusPlus)
9083
9085
9086 // For blocks we enforce that qualifiers are identical.
9087 Qualifiers LQuals = lhptee.getLocalQualifiers();
9088 Qualifiers RQuals = rhptee.getLocalQualifiers();
9089 if (S.getLangOpts().OpenCL) {
9090 LQuals.removeAddressSpace();
9091 RQuals.removeAddressSpace();
9092 }
9093 if (LQuals != RQuals)
9095
9096 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9097 // assignment.
9098 // The current behavior is similar to C++ lambdas. A block might be
9099 // assigned to a variable iff its return type and parameters are compatible
9100 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9101 // an assignment. Presumably it should behave in way that a function pointer
9102 // assignment does in C, so for each parameter and return type:
9103 // * CVR and address space of LHS should be a superset of CVR and address
9104 // space of RHS.
9105 // * unqualified types should be compatible.
9106 if (S.getLangOpts().OpenCL) {
9108 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9109 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9111 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9113
9114 return ConvTy;
9115}
9116
9117/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9118/// for assignment compatibility.
9121 QualType RHSType) {
9122 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9123 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9124
9125 if (LHSType->isObjCBuiltinType()) {
9126 // Class is not compatible with ObjC object pointers.
9127 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9128 !RHSType->isObjCQualifiedClassType())
9130 return Sema::Compatible;
9131 }
9132 if (RHSType->isObjCBuiltinType()) {
9133 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9134 !LHSType->isObjCQualifiedClassType())
9136 return Sema::Compatible;
9137 }
9138 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9139 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9140
9141 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9142 // make an exception for id<P>
9143 !LHSType->isObjCQualifiedIdType())
9145
9146 if (S.Context.typesAreCompatible(LHSType, RHSType))
9147 return Sema::Compatible;
9148 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9151}
9152
9155 QualType LHSType, QualType RHSType) {
9156 // Fake up an opaque expression. We don't actually care about what
9157 // cast operations are required, so if CheckAssignmentConstraints
9158 // adds casts to this they'll be wasted, but fortunately that doesn't
9159 // usually happen on valid code.
9160 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9161 ExprResult RHSPtr = &RHSExpr;
9162 CastKind K;
9163
9164 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9165}
9166
9167/// This helper function returns true if QT is a vector type that has element
9168/// type ElementType.
9169static bool isVector(QualType QT, QualType ElementType) {
9170 if (const VectorType *VT = QT->getAs<VectorType>())
9171 return VT->getElementType().getCanonicalType() == ElementType;
9172 return false;
9173}
9174
9175/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9176/// has code to accommodate several GCC extensions when type checking
9177/// pointers. Here are some objectionable examples that GCC considers warnings:
9178///
9179/// int a, *pint;
9180/// short *pshort;
9181/// struct foo *pfoo;
9182///
9183/// pint = pshort; // warning: assignment from incompatible pointer type
9184/// a = pint; // warning: assignment makes integer from pointer without a cast
9185/// pint = a; // warning: assignment makes pointer from integer without a cast
9186/// pint = pfoo; // warning: assignment from incompatible pointer type
9187///
9188/// As a result, the code for dealing with pointers is more complex than the
9189/// C99 spec dictates.
9190///
9191/// Sets 'Kind' for any result kind except Incompatible.
9194 CastKind &Kind, bool ConvertRHS) {
9195 QualType RHSType = RHS.get()->getType();
9196 QualType OrigLHSType = LHSType;
9197
9198 // Get canonical types. We're not formatting these types, just comparing
9199 // them.
9200 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9201 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9202
9203 // Common case: no conversion required.
9204 if (LHSType == RHSType) {
9205 Kind = CK_NoOp;
9206 return Compatible;
9207 }
9208
9209 // If the LHS has an __auto_type, there are no additional type constraints
9210 // to be worried about.
9211 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9212 if (AT->isGNUAutoType()) {
9213 Kind = CK_NoOp;
9214 return Compatible;
9215 }
9216 }
9217
9218 // If we have an atomic type, try a non-atomic assignment, then just add an
9219 // atomic qualification step.
9220 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9222 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9223 if (result != Compatible)
9224 return result;
9225 if (Kind != CK_NoOp && ConvertRHS)
9226 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9227 Kind = CK_NonAtomicToAtomic;
9228 return Compatible;
9229 }
9230
9231 // If the left-hand side is a reference type, then we are in a
9232 // (rare!) case where we've allowed the use of references in C,
9233 // e.g., as a parameter type in a built-in function. In this case,
9234 // just make sure that the type referenced is compatible with the
9235 // right-hand side type. The caller is responsible for adjusting
9236 // LHSType so that the resulting expression does not have reference
9237 // type.
9238 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9239 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9240 Kind = CK_LValueBitCast;
9241 return Compatible;
9242 }
9243 return Incompatible;
9244 }
9245
9246 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9247 // to the same ExtVector type.
9248 if (LHSType->isExtVectorType()) {
9249 if (RHSType->isExtVectorType())
9250 return Incompatible;
9251 if (RHSType->isArithmeticType()) {
9252 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9253 if (ConvertRHS)
9254 RHS = prepareVectorSplat(LHSType, RHS.get());
9255 Kind = CK_VectorSplat;
9256 return Compatible;
9257 }
9258 }
9259
9260 // Conversions to or from vector type.
9261 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9262 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9263 // Allow assignments of an AltiVec vector type to an equivalent GCC
9264 // vector type and vice versa
9265 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9266 Kind = CK_BitCast;
9267 return Compatible;
9268 }
9269
9270 // If we are allowing lax vector conversions, and LHS and RHS are both
9271 // vectors, the total size only needs to be the same. This is a bitcast;
9272 // no bits are changed but the result type is different.
9273 if (isLaxVectorConversion(RHSType, LHSType)) {
9274 // The default for lax vector conversions with Altivec vectors will
9275 // change, so if we are converting between vector types where
9276 // at least one is an Altivec vector, emit a warning.
9277 if (Context.getTargetInfo().getTriple().isPPC() &&
9278 anyAltivecTypes(RHSType, LHSType) &&
9279 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9280 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9281 << RHSType << LHSType;
9282 Kind = CK_BitCast;
9283 return IncompatibleVectors;
9284 }
9285 }
9286
9287 // When the RHS comes from another lax conversion (e.g. binops between
9288 // scalars and vectors) the result is canonicalized as a vector. When the
9289 // LHS is also a vector, the lax is allowed by the condition above. Handle
9290 // the case where LHS is a scalar.
9291 if (LHSType->isScalarType()) {
9292 const VectorType *VecType = RHSType->getAs<VectorType>();
9293 if (VecType && VecType->getNumElements() == 1 &&
9294 isLaxVectorConversion(RHSType, LHSType)) {
9295 if (Context.getTargetInfo().getTriple().isPPC() &&
9297 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9299 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9300 << RHSType << LHSType;
9301 ExprResult *VecExpr = &RHS;
9302 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9303 Kind = CK_BitCast;
9304 return Compatible;
9305 }
9306 }
9307
9308 // Allow assignments between fixed-length and sizeless SVE vectors.
9309 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9310 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9311 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9312 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9313 Kind = CK_BitCast;
9314 return Compatible;
9315 }
9316
9317 // Allow assignments between fixed-length and sizeless RVV vectors.
9318 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9319 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9320 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9321 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9322 Kind = CK_BitCast;
9323 return Compatible;
9324 }
9325 }
9326
9327 return Incompatible;
9328 }
9329
9330 // Diagnose attempts to convert between __ibm128, __float128 and long double
9331 // where such conversions currently can't be handled.
9332 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9333 return Incompatible;
9334
9335 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9336 // discards the imaginary part.
9337 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9338 !LHSType->getAs<ComplexType>())
9339 return Incompatible;
9340
9341 // Arithmetic conversions.
9342 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9343 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9344 if (ConvertRHS)
9345 Kind = PrepareScalarCast(RHS, LHSType);
9346 return Compatible;
9347 }
9348
9349 // Conversions to normal pointers.
9350 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9351 // U* -> T*
9352 if (isa<PointerType>(RHSType)) {
9353 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9354 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9355 if (AddrSpaceL != AddrSpaceR)
9356 Kind = CK_AddressSpaceConversion;
9357 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9358 Kind = CK_NoOp;
9359 else
9360 Kind = CK_BitCast;
9361 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9362 RHS.get()->getBeginLoc());
9363 }
9364
9365 // int -> T*
9366 if (RHSType->isIntegerType()) {
9367 Kind = CK_IntegralToPointer; // FIXME: null?
9368 return IntToPointer;
9369 }
9370
9371 // C pointers are not compatible with ObjC object pointers,
9372 // with two exceptions:
9373 if (isa<ObjCObjectPointerType>(RHSType)) {
9374 // - conversions to void*
9375 if (LHSPointer->getPointeeType()->isVoidType()) {
9376 Kind = CK_BitCast;
9377 return Compatible;
9378 }
9379
9380 // - conversions from 'Class' to the redefinition type
9381 if (RHSType->isObjCClassType() &&
9382 Context.hasSameType(LHSType,
9384 Kind = CK_BitCast;
9385 return Compatible;
9386 }
9387
9388 Kind = CK_BitCast;
9389 return IncompatiblePointer;
9390 }
9391
9392 // U^ -> void*
9393 if (RHSType->getAs<BlockPointerType>()) {
9394 if (LHSPointer->getPointeeType()->isVoidType()) {
9395 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9396 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9397 ->getPointeeType()
9398 .getAddressSpace();
9399 Kind =
9400 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9401 return Compatible;
9402 }
9403 }
9404
9405 return Incompatible;
9406 }
9407
9408 // Conversions to block pointers.
9409 if (isa<BlockPointerType>(LHSType)) {
9410 // U^ -> T^
9411 if (RHSType->isBlockPointerType()) {
9412 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9413 ->getPointeeType()
9414 .getAddressSpace();
9415 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9416 ->getPointeeType()
9417 .getAddressSpace();
9418 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9419 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9420 }
9421
9422 // int or null -> T^
9423 if (RHSType->isIntegerType()) {
9424 Kind = CK_IntegralToPointer; // FIXME: null
9425 return IntToBlockPointer;
9426 }
9427
9428 // id -> T^
9429 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9430 Kind = CK_AnyPointerToBlockPointerCast;
9431 return Compatible;
9432 }
9433
9434 // void* -> T^
9435 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9436 if (RHSPT->getPointeeType()->isVoidType()) {
9437 Kind = CK_AnyPointerToBlockPointerCast;
9438 return Compatible;
9439 }
9440
9441 return Incompatible;
9442 }
9443
9444 // Conversions to Objective-C pointers.
9445 if (isa<ObjCObjectPointerType>(LHSType)) {
9446 // A* -> B*
9447 if (RHSType->isObjCObjectPointerType()) {
9448 Kind = CK_BitCast;
9450 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9451 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9452 result == Compatible &&
9453 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9454 result = IncompatibleObjCWeakRef;
9455 return result;
9456 }
9457
9458 // int or null -> A*
9459 if (RHSType->isIntegerType()) {
9460 Kind = CK_IntegralToPointer; // FIXME: null
9461 return IntToPointer;
9462 }
9463
9464 // In general, C pointers are not compatible with ObjC object pointers,
9465 // with two exceptions:
9466 if (isa<PointerType>(RHSType)) {
9467 Kind = CK_CPointerToObjCPointerCast;
9468
9469 // - conversions from 'void*'
9470 if (RHSType->isVoidPointerType()) {
9471 return Compatible;
9472 }
9473
9474 // - conversions to 'Class' from its redefinition type
9475 if (LHSType->isObjCClassType() &&
9476 Context.hasSameType(RHSType,
9478 return Compatible;
9479 }
9480
9481 return IncompatiblePointer;
9482 }
9483
9484 // Only under strict condition T^ is compatible with an Objective-C pointer.
9485 if (RHSType->isBlockPointerType() &&
9487 if (ConvertRHS)
9489 Kind = CK_BlockPointerToObjCPointerCast;
9490 return Compatible;
9491 }
9492
9493 return Incompatible;
9494 }
9495
9496 // Conversion to nullptr_t (C23 only)
9497 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9500 // null -> nullptr_t
9501 Kind = CK_NullToPointer;
9502 return Compatible;
9503 }
9504
9505 // Conversions from pointers that are not covered by the above.
9506 if (isa<PointerType>(RHSType)) {
9507 // T* -> _Bool
9508 if (LHSType == Context.BoolTy) {
9509 Kind = CK_PointerToBoolean;
9510 return Compatible;
9511 }
9512
9513 // T* -> int
9514 if (LHSType->isIntegerType()) {
9515 Kind = CK_PointerToIntegral;
9516 return PointerToInt;
9517 }
9518
9519 return Incompatible;
9520 }
9521
9522 // Conversions from Objective-C pointers that are not covered by the above.
9523 if (isa<ObjCObjectPointerType>(RHSType)) {
9524 // T* -> _Bool
9525 if (LHSType == Context.BoolTy) {
9526 Kind = CK_PointerToBoolean;
9527 return Compatible;
9528 }
9529
9530 // T* -> int
9531 if (LHSType->isIntegerType()) {
9532 Kind = CK_PointerToIntegral;
9533 return PointerToInt;
9534 }
9535
9536 return Incompatible;
9537 }
9538
9539 // struct A -> struct B
9540 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9541 if (Context.typesAreCompatible(LHSType, RHSType)) {
9542 Kind = CK_NoOp;
9543 return Compatible;
9544 }
9545 }
9546
9547 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9548 Kind = CK_IntToOCLSampler;
9549 return Compatible;
9550 }
9551
9552 return Incompatible;
9553}
9554
9555/// Constructs a transparent union from an expression that is
9556/// used to initialize the transparent union.
9558 ExprResult &EResult, QualType UnionType,
9559 FieldDecl *Field) {
9560 // Build an initializer list that designates the appropriate member
9561 // of the transparent union.
9562 Expr *E = EResult.get();
9564 E, SourceLocation());
9565 Initializer->setType(UnionType);
9566 Initializer->setInitializedFieldInUnion(Field);
9567
9568 // Build a compound literal constructing a value of the transparent
9569 // union type from this initializer list.
9570 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9571 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9572 VK_PRValue, Initializer, false);
9573}
9574
9577 ExprResult &RHS) {
9578 QualType RHSType = RHS.get()->getType();
9579
9580 // If the ArgType is a Union type, we want to handle a potential
9581 // transparent_union GCC extension.
9582 const RecordType *UT = ArgType->getAsUnionType();
9583 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9584 return Incompatible;
9585
9586 // The field to initialize within the transparent union.
9587 RecordDecl *UD = UT->getDecl();
9588 FieldDecl *InitField = nullptr;
9589 // It's compatible if the expression matches any of the fields.
9590 for (auto *it : UD->fields()) {
9591 if (it->getType()->isPointerType()) {
9592 // If the transparent union contains a pointer type, we allow:
9593 // 1) void pointer
9594 // 2) null pointer constant
9595 if (RHSType->isPointerType())
9596 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9597 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9598 InitField = it;
9599 break;
9600 }
9601
9604 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9605 CK_NullToPointer);
9606 InitField = it;
9607 break;
9608 }
9609 }
9610
9611 CastKind Kind;
9612 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9613 == Compatible) {
9614 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9615 InitField = it;
9616 break;
9617 }
9618 }
9619
9620 if (!InitField)
9621 return Incompatible;
9622
9623 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9624 return Compatible;
9625}
9626
9629 bool Diagnose,
9630 bool DiagnoseCFAudited,
9631 bool ConvertRHS) {
9632 // We need to be able to tell the caller whether we diagnosed a problem, if
9633 // they ask us to issue diagnostics.
9634 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9635
9636 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9637 // we can't avoid *all* modifications at the moment, so we need some somewhere
9638 // to put the updated value.
9639 ExprResult LocalRHS = CallerRHS;
9640 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9641
9642 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9643 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9644 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9645 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9646 Diag(RHS.get()->getExprLoc(),
9647 diag::warn_noderef_to_dereferenceable_pointer)
9648 << RHS.get()->getSourceRange();
9649 }
9650 }
9651 }
9652
9653 if (getLangOpts().CPlusPlus) {
9654 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9655 // C++ 5.17p3: If the left operand is not of class type, the
9656 // expression is implicitly converted (C++ 4) to the
9657 // cv-unqualified type of the left operand.
9658 QualType RHSType = RHS.get()->getType();
9659 if (Diagnose) {
9660 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9662 } else {
9665 /*SuppressUserConversions=*/false,
9666 AllowedExplicit::None,
9667 /*InOverloadResolution=*/false,
9668 /*CStyle=*/false,
9669 /*AllowObjCWritebackConversion=*/false);
9670 if (ICS.isFailure())
9671 return Incompatible;
9672 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9674 }
9675 if (RHS.isInvalid())
9676 return Incompatible;
9678 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9679 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9680 result = IncompatibleObjCWeakRef;
9681 return result;
9682 }
9683
9684 // FIXME: Currently, we fall through and treat C++ classes like C
9685 // structures.
9686 // FIXME: We also fall through for atomics; not sure what should
9687 // happen there, though.
9688 } else if (RHS.get()->getType() == Context.OverloadTy) {
9689 // As a set of extensions to C, we support overloading on functions. These
9690 // functions need to be resolved here.
9691 DeclAccessPair DAP;
9693 RHS.get(), LHSType, /*Complain=*/false, DAP))
9694 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9695 else
9696 return Incompatible;
9697 }
9698
9699 // This check seems unnatural, however it is necessary to ensure the proper
9700 // conversion of functions/arrays. If the conversion were done for all
9701 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9702 // expressions that suppress this implicit conversion (&, sizeof). This needs
9703 // to happen before we check for null pointer conversions because C does not
9704 // undergo the same implicit conversions as C++ does above (by the calls to
9705 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
9706 // lvalue to rvalue cast before checking for null pointer constraints. This
9707 // addresses code like: nullptr_t val; int *ptr; ptr = val;
9708 //
9709 // Suppress this for references: C++ 8.5.3p5.
9710 if (!LHSType->isReferenceType()) {
9711 // FIXME: We potentially allocate here even if ConvertRHS is false.
9713 if (RHS.isInvalid())
9714 return Incompatible;
9715 }
9716
9717 // The constraints are expressed in terms of the atomic, qualified, or
9718 // unqualified type of the LHS.
9719 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
9720
9721 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9722 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
9723 if ((LHSTypeAfterConversion->isPointerType() ||
9724 LHSTypeAfterConversion->isObjCObjectPointerType() ||
9725 LHSTypeAfterConversion->isBlockPointerType()) &&
9726 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
9729 if (Diagnose || ConvertRHS) {
9730 CastKind Kind;
9732 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9733 /*IgnoreBaseAccess=*/false, Diagnose);
9734 if (ConvertRHS)
9735 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9736 }
9737 return Compatible;
9738 }
9739 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
9740 // unqualified bool, and the right operand is a pointer or its type is
9741 // nullptr_t.
9742 if (getLangOpts().C23 && LHSType->isBooleanType() &&
9743 RHS.get()->getType()->isNullPtrType()) {
9744 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
9745 // only handles nullptr -> _Bool due to needing an extra conversion
9746 // step.
9747 // We model this by converting from nullptr -> void * and then let the
9748 // conversion from void * -> _Bool happen naturally.
9749 if (Diagnose || ConvertRHS) {
9750 CastKind Kind;
9753 /*IgnoreBaseAccess=*/false, Diagnose);
9754 if (ConvertRHS)
9755 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
9756 &Path);
9757 }
9758 }
9759
9760 // OpenCL queue_t type assignment.
9761 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9763 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9764 return Compatible;
9765 }
9766
9767 CastKind Kind;
9769 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9770
9771 // C99 6.5.16.1p2: The value of the right operand is converted to the
9772 // type of the assignment expression.
9773 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9774 // so that we can use references in built-in functions even in C.
9775 // The getNonReferenceType() call makes sure that the resulting expression
9776 // does not have reference type.
9777 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9779 Expr *E = RHS.get();
9780
9781 // Check for various Objective-C errors. If we are not reporting
9782 // diagnostics and just checking for errors, e.g., during overload
9783 // resolution, return Incompatible to indicate the failure.
9784 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9785 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
9787 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
9788 if (!Diagnose)
9789 return Incompatible;
9790 }
9791 if (getLangOpts().ObjC &&
9792 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9793 E->getType(), E, Diagnose) ||
9794 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9795 if (!Diagnose)
9796 return Incompatible;
9797 // Replace the expression with a corrected version and continue so we
9798 // can find further errors.
9799 RHS = E;
9800 return Compatible;
9801 }
9802
9803 if (ConvertRHS)
9804 RHS = ImpCastExprToType(E, Ty, Kind);
9805 }
9806
9807 return result;
9808}
9809
9810namespace {
9811/// The original operand to an operator, prior to the application of the usual
9812/// arithmetic conversions and converting the arguments of a builtin operator
9813/// candidate.
9814struct OriginalOperand {
9815 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9816 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9817 Op = MTE->getSubExpr();
9818 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9819 Op = BTE->getSubExpr();
9820 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9821 Orig = ICE->getSubExprAsWritten();
9822 Conversion = ICE->getConversionFunction();
9823 }
9824 }
9825
9826 QualType getType() const { return Orig->getType(); }
9827
9828 Expr *Orig;
9829 NamedDecl *Conversion;
9830};
9831}
9832
9834 ExprResult &RHS) {
9835 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9836
9837 Diag(Loc, diag::err_typecheck_invalid_operands)
9838 << OrigLHS.getType() << OrigRHS.getType()
9839 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9840
9841 // If a user-defined conversion was applied to either of the operands prior
9842 // to applying the built-in operator rules, tell the user about it.
9843 if (OrigLHS.Conversion) {
9844 Diag(OrigLHS.Conversion->getLocation(),
9845 diag::note_typecheck_invalid_operands_converted)
9846 << 0 << LHS.get()->getType();
9847 }
9848 if (OrigRHS.Conversion) {
9849 Diag(OrigRHS.Conversion->getLocation(),
9850 diag::note_typecheck_invalid_operands_converted)
9851 << 1 << RHS.get()->getType();
9852 }
9853
9854 return QualType();
9855}
9856
9858 ExprResult &RHS) {
9859 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9860 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9861
9862 bool LHSNatVec = LHSType->isVectorType();
9863 bool RHSNatVec = RHSType->isVectorType();
9864
9865 if (!(LHSNatVec && RHSNatVec)) {
9866 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9867 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9868 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9869 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9870 << Vector->getSourceRange();
9871 return QualType();
9872 }
9873
9874 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9875 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9876 << RHS.get()->getSourceRange();
9877
9878 return QualType();
9879}
9880
9881/// Try to convert a value of non-vector type to a vector type by converting
9882/// the type to the element type of the vector and then performing a splat.
9883/// If the language is OpenCL, we only use conversions that promote scalar
9884/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9885/// for float->int.
9886///
9887/// OpenCL V2.0 6.2.6.p2:
9888/// An error shall occur if any scalar operand type has greater rank
9889/// than the type of the vector element.
9890///
9891/// \param scalar - if non-null, actually perform the conversions
9892/// \return true if the operation fails (but without diagnosing the failure)
9894 QualType scalarTy,
9895 QualType vectorEltTy,
9896 QualType vectorTy,
9897 unsigned &DiagID) {
9898 // The conversion to apply to the scalar before splatting it,
9899 // if necessary.
9900 CastKind scalarCast = CK_NoOp;
9901
9902 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
9903 scalarCast = CK_IntegralToBoolean;
9904 } else if (vectorEltTy->isIntegralType(S.Context)) {
9905 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9906 (scalarTy->isIntegerType() &&
9907 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9908 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9909 return true;
9910 }
9911 if (!scalarTy->isIntegralType(S.Context))
9912 return true;
9913 scalarCast = CK_IntegralCast;
9914 } else if (vectorEltTy->isRealFloatingType()) {
9915 if (scalarTy->isRealFloatingType()) {
9916 if (S.getLangOpts().OpenCL &&
9917 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9918 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9919 return true;
9920 }
9921 scalarCast = CK_FloatingCast;
9922 }
9923 else if (scalarTy->isIntegralType(S.Context))
9924 scalarCast = CK_IntegralToFloating;
9925 else
9926 return true;
9927 } else {
9928 return true;
9929 }
9930
9931 // Adjust scalar if desired.
9932 if (scalar) {
9933 if (scalarCast != CK_NoOp)
9934 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9935 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9936 }
9937 return false;
9938}
9939
9940/// Convert vector E to a vector with the same number of elements but different
9941/// element type.
9942static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9943 const auto *VecTy = E->getType()->getAs<VectorType>();
9944 assert(VecTy && "Expression E must be a vector");
9945 QualType NewVecTy =
9946 VecTy->isExtVectorType()
9947 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
9948 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
9949 VecTy->getVectorKind());
9950
9951 // Look through the implicit cast. Return the subexpression if its type is
9952 // NewVecTy.
9953 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9954 if (ICE->getSubExpr()->getType() == NewVecTy)
9955 return ICE->getSubExpr();
9956
9957 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9958 return S.ImpCastExprToType(E, NewVecTy, Cast);
9959}
9960
9961/// Test if a (constant) integer Int can be casted to another integer type
9962/// IntTy without losing precision.
9964 QualType OtherIntTy) {
9965 if (Int->get()->containsErrors())
9966 return false;
9967
9968 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9969
9970 // Reject cases where the value of the Int is unknown as that would
9971 // possibly cause truncation, but accept cases where the scalar can be
9972 // demoted without loss of precision.
9973 Expr::EvalResult EVResult;
9974 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9975 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9976 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9977 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9978
9979 if (CstInt) {
9980 // If the scalar is constant and is of a higher order and has more active
9981 // bits that the vector element type, reject it.
9982 llvm::APSInt Result = EVResult.Val.getInt();
9983 unsigned NumBits = IntSigned
9984 ? (Result.isNegative() ? Result.getSignificantBits()
9985 : Result.getActiveBits())
9986 : Result.getActiveBits();
9987 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9988 return true;
9989
9990 // If the signedness of the scalar type and the vector element type
9991 // differs and the number of bits is greater than that of the vector
9992 // element reject it.
9993 return (IntSigned != OtherIntSigned &&
9994 NumBits > S.Context.getIntWidth(OtherIntTy));
9995 }
9996
9997 // Reject cases where the value of the scalar is not constant and it's
9998 // order is greater than that of the vector element type.
9999 return (Order < 0);
10000}
10001
10002/// Test if a (constant) integer Int can be casted to floating point type
10003/// FloatTy without losing precision.
10005 QualType FloatTy) {
10006 if (Int->get()->containsErrors())
10007 return false;
10008
10009 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10010
10011 // Determine if the integer constant can be expressed as a floating point
10012 // number of the appropriate type.
10013 Expr::EvalResult EVResult;
10014 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10015
10016 uint64_t Bits = 0;
10017 if (CstInt) {
10018 // Reject constants that would be truncated if they were converted to
10019 // the floating point type. Test by simple to/from conversion.
10020 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10021 // could be avoided if there was a convertFromAPInt method
10022 // which could signal back if implicit truncation occurred.
10023 llvm::APSInt Result = EVResult.Val.getInt();
10024 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10025 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10026 llvm::APFloat::rmTowardZero);
10027 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10029 bool Ignored = false;
10030 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10031 &Ignored);
10032 if (Result != ConvertBack)
10033 return true;
10034 } else {
10035 // Reject types that cannot be fully encoded into the mantissa of
10036 // the float.
10037 Bits = S.Context.getTypeSize(IntTy);
10038 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10039 S.Context.getFloatTypeSemantics(FloatTy));
10040 if (Bits > FloatPrec)
10041 return true;
10042 }
10043
10044 return false;
10045}
10046
10047/// Attempt to convert and splat Scalar into a vector whose types matches
10048/// Vector following GCC conversion rules. The rule is that implicit
10049/// conversion can occur when Scalar can be casted to match Vector's element
10050/// type without causing truncation of Scalar.
10052 ExprResult *Vector) {
10053 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10054 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10055 QualType VectorEltTy;
10056
10057 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10058 assert(!isa<ExtVectorType>(VT) &&
10059 "ExtVectorTypes should not be handled here!");
10060 VectorEltTy = VT->getElementType();
10061 } else if (VectorTy->isSveVLSBuiltinType()) {
10062 VectorEltTy =
10063 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10064 } else {
10065 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10066 }
10067
10068 // Reject cases where the vector element type or the scalar element type are
10069 // not integral or floating point types.
10070 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10071 return true;
10072
10073 // The conversion to apply to the scalar before splatting it,
10074 // if necessary.
10075 CastKind ScalarCast = CK_NoOp;
10076
10077 // Accept cases where the vector elements are integers and the scalar is
10078 // an integer.
10079 // FIXME: Notionally if the scalar was a floating point value with a precise
10080 // integral representation, we could cast it to an appropriate integer
10081 // type and then perform the rest of the checks here. GCC will perform
10082 // this conversion in some cases as determined by the input language.
10083 // We should accept it on a language independent basis.
10084 if (VectorEltTy->isIntegralType(S.Context) &&
10085 ScalarTy->isIntegralType(S.Context) &&
10086 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10087
10088 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10089 return true;
10090
10091 ScalarCast = CK_IntegralCast;
10092 } else if (VectorEltTy->isIntegralType(S.Context) &&
10093 ScalarTy->isRealFloatingType()) {
10094 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10095 ScalarCast = CK_FloatingToIntegral;
10096 else
10097 return true;
10098 } else if (VectorEltTy->isRealFloatingType()) {
10099 if (ScalarTy->isRealFloatingType()) {
10100
10101 // Reject cases where the scalar type is not a constant and has a higher
10102 // Order than the vector element type.
10103 llvm::APFloat Result(0.0);
10104
10105 // Determine whether this is a constant scalar. In the event that the
10106 // value is dependent (and thus cannot be evaluated by the constant
10107 // evaluator), skip the evaluation. This will then diagnose once the
10108 // expression is instantiated.
10109 bool CstScalar = Scalar->get()->isValueDependent() ||
10110 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10111 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10112 if (!CstScalar && Order < 0)
10113 return true;
10114
10115 // If the scalar cannot be safely casted to the vector element type,
10116 // reject it.
10117 if (CstScalar) {
10118 bool Truncated = false;
10119 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10120 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10121 if (Truncated)
10122 return true;
10123 }
10124
10125 ScalarCast = CK_FloatingCast;
10126 } else if (ScalarTy->isIntegralType(S.Context)) {
10127 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10128 return true;
10129
10130 ScalarCast = CK_IntegralToFloating;
10131 } else
10132 return true;
10133 } else if (ScalarTy->isEnumeralType())
10134 return true;
10135
10136 // Adjust scalar if desired.
10137 if (ScalarCast != CK_NoOp)
10138 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10139 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10140 return false;
10141}
10142
10144 SourceLocation Loc, bool IsCompAssign,
10145 bool AllowBothBool,
10146 bool AllowBoolConversions,
10147 bool AllowBoolOperation,
10148 bool ReportInvalid) {
10149 if (!IsCompAssign) {
10151 if (LHS.isInvalid())
10152 return QualType();
10153 }
10155 if (RHS.isInvalid())
10156 return QualType();
10157
10158 // For conversion purposes, we ignore any qualifiers.
10159 // For example, "const float" and "float" are equivalent.
10160 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10161 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10162
10163 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10164 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10165 assert(LHSVecType || RHSVecType);
10166
10167 if (getLangOpts().HLSL)
10168 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10169 IsCompAssign);
10170
10171 // AltiVec-style "vector bool op vector bool" combinations are allowed
10172 // for some operators but not others.
10173 if (!AllowBothBool && LHSVecType &&
10174 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10175 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10176 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10177
10178 // This operation may not be performed on boolean vectors.
10179 if (!AllowBoolOperation &&
10180 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10181 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10182
10183 // If the vector types are identical, return.
10184 if (Context.hasSameType(LHSType, RHSType))
10185 return Context.getCommonSugaredType(LHSType, RHSType);
10186
10187 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10188 if (LHSVecType && RHSVecType &&
10189 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10190 if (isa<ExtVectorType>(LHSVecType)) {
10191 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10192 return LHSType;
10193 }
10194
10195 if (!IsCompAssign)
10196 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10197 return RHSType;
10198 }
10199
10200 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10201 // can be mixed, with the result being the non-bool type. The non-bool
10202 // operand must have integer element type.
10203 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10204 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10205 (Context.getTypeSize(LHSVecType->getElementType()) ==
10206 Context.getTypeSize(RHSVecType->getElementType()))) {
10207 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10208 LHSVecType->getElementType()->isIntegerType() &&
10209 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10210 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10211 return LHSType;
10212 }
10213 if (!IsCompAssign &&
10214 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10215 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10216 RHSVecType->getElementType()->isIntegerType()) {
10217 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10218 return RHSType;
10219 }
10220 }
10221
10222 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10223 // invalid since the ambiguity can affect the ABI.
10224 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10225 unsigned &SVEorRVV) {
10226 const VectorType *VecType = SecondType->getAs<VectorType>();
10227 SVEorRVV = 0;
10228 if (FirstType->isSizelessBuiltinType() && VecType) {
10231 return true;
10237 SVEorRVV = 1;
10238 return true;
10239 }
10240 }
10241
10242 return false;
10243 };
10244
10245 unsigned SVEorRVV;
10246 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10247 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10248 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10249 << SVEorRVV << LHSType << RHSType;
10250 return QualType();
10251 }
10252
10253 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10254 // invalid since the ambiguity can affect the ABI.
10255 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10256 unsigned &SVEorRVV) {
10257 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10258 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10259
10260 SVEorRVV = 0;
10261 if (FirstVecType && SecondVecType) {
10262 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10263 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10264 SecondVecType->getVectorKind() ==
10266 return true;
10267 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10268 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10269 SecondVecType->getVectorKind() ==
10271 SecondVecType->getVectorKind() ==
10273 SecondVecType->getVectorKind() ==
10275 SVEorRVV = 1;
10276 return true;
10277 }
10278 }
10279 return false;
10280 }
10281
10282 if (SecondVecType &&
10283 SecondVecType->getVectorKind() == VectorKind::Generic) {
10284 if (FirstType->isSVESizelessBuiltinType())
10285 return true;
10286 if (FirstType->isRVVSizelessBuiltinType()) {
10287 SVEorRVV = 1;
10288 return true;
10289 }
10290 }
10291
10292 return false;
10293 };
10294
10295 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10296 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10297 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10298 << SVEorRVV << LHSType << RHSType;
10299 return QualType();
10300 }
10301
10302 // If there's a vector type and a scalar, try to convert the scalar to
10303 // the vector element type and splat.
10304 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10305 if (!RHSVecType) {
10306 if (isa<ExtVectorType>(LHSVecType)) {
10307 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10308 LHSVecType->getElementType(), LHSType,
10309 DiagID))
10310 return LHSType;
10311 } else {
10312 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10313 return LHSType;
10314 }
10315 }
10316 if (!LHSVecType) {
10317 if (isa<ExtVectorType>(RHSVecType)) {
10318 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10319 LHSType, RHSVecType->getElementType(),
10320 RHSType, DiagID))
10321 return RHSType;
10322 } else {
10323 if (LHS.get()->isLValue() ||
10324 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10325 return RHSType;
10326 }
10327 }
10328
10329 // FIXME: The code below also handles conversion between vectors and
10330 // non-scalars, we should break this down into fine grained specific checks
10331 // and emit proper diagnostics.
10332 QualType VecType = LHSVecType ? LHSType : RHSType;
10333 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10334 QualType OtherType = LHSVecType ? RHSType : LHSType;
10335 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10336 if (isLaxVectorConversion(OtherType, VecType)) {
10337 if (Context.getTargetInfo().getTriple().isPPC() &&
10338 anyAltivecTypes(RHSType, LHSType) &&
10339 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10340 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10341 // If we're allowing lax vector conversions, only the total (data) size
10342 // needs to be the same. For non compound assignment, if one of the types is
10343 // scalar, the result is always the vector type.
10344 if (!IsCompAssign) {
10345 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10346 return VecType;
10347 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10348 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10349 // type. Note that this is already done by non-compound assignments in
10350 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10351 // <1 x T> -> T. The result is also a vector type.
10352 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10353 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10354 ExprResult *RHSExpr = &RHS;
10355 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10356 return VecType;
10357 }
10358 }
10359
10360 // Okay, the expression is invalid.
10361
10362 // If there's a non-vector, non-real operand, diagnose that.
10363 if ((!RHSVecType && !RHSType->isRealType()) ||
10364 (!LHSVecType && !LHSType->isRealType())) {
10365 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10366 << LHSType << RHSType
10367 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10368 return QualType();
10369 }
10370
10371 // OpenCL V1.1 6.2.6.p1:
10372 // If the operands are of more than one vector type, then an error shall
10373 // occur. Implicit conversions between vector types are not permitted, per
10374 // section 6.2.1.
10375 if (getLangOpts().OpenCL &&
10376 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10377 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10378 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10379 << RHSType;
10380 return QualType();
10381 }
10382
10383
10384 // If there is a vector type that is not a ExtVector and a scalar, we reach
10385 // this point if scalar could not be converted to the vector's element type
10386 // without truncation.
10387 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10388 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10389 QualType Scalar = LHSVecType ? RHSType : LHSType;
10390 QualType Vector = LHSVecType ? LHSType : RHSType;
10391 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10392 Diag(Loc,
10393 diag::err_typecheck_vector_not_convertable_implict_truncation)
10394 << ScalarOrVector << Scalar << Vector;
10395
10396 return QualType();
10397 }
10398
10399 // Otherwise, use the generic diagnostic.
10400 Diag(Loc, DiagID)
10401 << LHSType << RHSType
10402 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10403 return QualType();
10404}
10405
10408 bool IsCompAssign,
10409 ArithConvKind OperationKind) {
10410 if (!IsCompAssign) {
10412 if (LHS.isInvalid())
10413 return QualType();
10414 }
10416 if (RHS.isInvalid())
10417 return QualType();
10418
10419 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10420 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10421
10422 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10423 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10424
10425 unsigned DiagID = diag::err_typecheck_invalid_operands;
10426 if ((OperationKind == ACK_Arithmetic) &&
10427 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10428 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10429 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10430 << RHS.get()->getSourceRange();
10431 return QualType();
10432 }
10433
10434 if (Context.hasSameType(LHSType, RHSType))
10435 return LHSType;
10436
10437 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10438 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10439 return LHSType;
10440 }
10441 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10442 if (LHS.get()->isLValue() ||
10443 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10444 return RHSType;
10445 }
10446
10447 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10448 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10449 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10450 << LHSType << RHSType << LHS.get()->getSourceRange()
10451 << RHS.get()->getSourceRange();
10452 return QualType();
10453 }
10454
10455 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10456 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10457 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10458 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10459 << LHSType << RHSType << LHS.get()->getSourceRange()
10460 << RHS.get()->getSourceRange();
10461 return QualType();
10462 }
10463
10464 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10465 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10466 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10467 bool ScalarOrVector =
10468 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10469
10470 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10471 << ScalarOrVector << Scalar << Vector;
10472
10473 return QualType();
10474 }
10475
10476 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10477 << RHS.get()->getSourceRange();
10478 return QualType();
10479}
10480
10481// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10482// expression. These are mainly cases where the null pointer is used as an
10483// integer instead of a pointer.
10485 SourceLocation Loc, bool IsCompare) {
10486 // The canonical way to check for a GNU null is with isNullPointerConstant,
10487 // but we use a bit of a hack here for speed; this is a relatively
10488 // hot path, and isNullPointerConstant is slow.
10489 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10490 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10491
10492 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10493
10494 // Avoid analyzing cases where the result will either be invalid (and
10495 // diagnosed as such) or entirely valid and not something to warn about.
10496 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10497 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10498 return;
10499
10500 // Comparison operations would not make sense with a null pointer no matter
10501 // what the other expression is.
10502 if (!IsCompare) {
10503 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10504 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10505 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10506 return;
10507 }
10508
10509 // The rest of the operations only make sense with a null pointer
10510 // if the other expression is a pointer.
10511 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10512 NonNullType->canDecayToPointerType())
10513 return;
10514
10515 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10516 << LHSNull /* LHS is NULL */ << NonNullType
10517 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10518}
10519
10522 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10523 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10524 if (!LUE || !RUE)
10525 return;
10526 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10527 RUE->getKind() != UETT_SizeOf)
10528 return;
10529
10530 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10531 QualType LHSTy = LHSArg->getType();
10532 QualType RHSTy;
10533
10534 if (RUE->isArgumentType())
10535 RHSTy = RUE->getArgumentType().getNonReferenceType();
10536 else
10537 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10538
10539 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10540 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10541 return;
10542
10543 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10544 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10545 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10546 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10547 << LHSArgDecl;
10548 }
10549 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10550 QualType ArrayElemTy = ArrayTy->getElementType();
10551 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10552 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10553 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10554 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10555 return;
10556 S.Diag(Loc, diag::warn_division_sizeof_array)
10557 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10558 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10559 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10560 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10561 << LHSArgDecl;
10562 }
10563
10564 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10565 }
10566}
10567
10569 ExprResult &RHS,
10570 SourceLocation Loc, bool IsDiv) {
10571 // Check for division/remainder by zero.
10572 Expr::EvalResult RHSValue;
10573 if (!RHS.get()->isValueDependent() &&
10574 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10575 RHSValue.Val.getInt() == 0)
10576 S.DiagRuntimeBehavior(Loc, RHS.get(),
10577 S.PDiag(diag::warn_remainder_division_by_zero)
10578 << IsDiv << RHS.get()->getSourceRange());
10579}
10580
10583 bool IsCompAssign, bool IsDiv) {
10584 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10585
10586 QualType LHSTy = LHS.get()->getType();
10587 QualType RHSTy = RHS.get()->getType();
10588 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10589 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10590 /*AllowBothBool*/ getLangOpts().AltiVec,
10591 /*AllowBoolConversions*/ false,
10592 /*AllowBooleanOperation*/ false,
10593 /*ReportInvalid*/ true);
10594 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10595 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10597 if (!IsDiv &&
10598 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10599 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10600 // For division, only matrix-by-scalar is supported. Other combinations with
10601 // matrix types are invalid.
10602 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10603 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10604
10606 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10607 if (LHS.isInvalid() || RHS.isInvalid())
10608 return QualType();
10609
10610
10611 if (compType.isNull() || !compType->isArithmeticType())
10612 return InvalidOperands(Loc, LHS, RHS);
10613 if (IsDiv) {
10614 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10615 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10616 }
10617 return compType;
10618}
10619
10621 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10622 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10623
10624 if (LHS.get()->getType()->isVectorType() ||
10625 RHS.get()->getType()->isVectorType()) {
10626 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10628 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10629 /*AllowBothBool*/ getLangOpts().AltiVec,
10630 /*AllowBoolConversions*/ false,
10631 /*AllowBooleanOperation*/ false,
10632 /*ReportInvalid*/ true);
10633 return InvalidOperands(Loc, LHS, RHS);
10634 }
10635
10636 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10637 RHS.get()->getType()->isSveVLSBuiltinType()) {
10638 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10640 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10642
10643 return InvalidOperands(Loc, LHS, RHS);
10644 }
10645
10647 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10648 if (LHS.isInvalid() || RHS.isInvalid())
10649 return QualType();
10650
10651 if (compType.isNull() || !compType->isIntegerType())
10652 return InvalidOperands(Loc, LHS, RHS);
10653 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10654 return compType;
10655}
10656
10657/// Diagnose invalid arithmetic on two void pointers.
10659 Expr *LHSExpr, Expr *RHSExpr) {
10660 S.Diag(Loc, S.getLangOpts().CPlusPlus
10661 ? diag::err_typecheck_pointer_arith_void_type
10662 : diag::ext_gnu_void_ptr)
10663 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10664 << RHSExpr->getSourceRange();
10665}
10666
10667/// Diagnose invalid arithmetic on a void pointer.
10669 Expr *Pointer) {
10670 S.Diag(Loc, S.getLangOpts().CPlusPlus
10671 ? diag::err_typecheck_pointer_arith_void_type
10672 : diag::ext_gnu_void_ptr)
10673 << 0 /* one pointer */ << Pointer->getSourceRange();
10674}
10675
10676/// Diagnose invalid arithmetic on a null pointer.
10677///
10678/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10679/// idiom, which we recognize as a GNU extension.
10680///
10682 Expr *Pointer, bool IsGNUIdiom) {
10683 if (IsGNUIdiom)
10684 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10685 << Pointer->getSourceRange();
10686 else
10687 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10688 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10689}
10690
10691/// Diagnose invalid subraction on a null pointer.
10692///
10694 Expr *Pointer, bool BothNull) {
10695 // Null - null is valid in C++ [expr.add]p7
10696 if (BothNull && S.getLangOpts().CPlusPlus)
10697 return;
10698
10699 // Is this s a macro from a system header?
10701 return;
10702
10704 S.PDiag(diag::warn_pointer_sub_null_ptr)
10705 << S.getLangOpts().CPlusPlus
10706 << Pointer->getSourceRange());
10707}
10708
10709/// Diagnose invalid arithmetic on two function pointers.
10711 Expr *LHS, Expr *RHS) {
10712 assert(LHS->getType()->isAnyPointerType());
10713 assert(RHS->getType()->isAnyPointerType());
10714 S.Diag(Loc, S.getLangOpts().CPlusPlus
10715 ? diag::err_typecheck_pointer_arith_function_type
10716 : diag::ext_gnu_ptr_func_arith)
10717 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10718 // We only show the second type if it differs from the first.
10720 RHS->getType())
10721 << RHS->getType()->getPointeeType()
10722 << LHS->getSourceRange() << RHS->getSourceRange();
10723}
10724
10725/// Diagnose invalid arithmetic on a function pointer.
10727 Expr *Pointer) {
10728 assert(Pointer->getType()->isAnyPointerType());
10729 S.Diag(Loc, S.getLangOpts().CPlusPlus
10730 ? diag::err_typecheck_pointer_arith_function_type
10731 : diag::ext_gnu_ptr_func_arith)
10732 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10733 << 0 /* one pointer, so only one type */
10734 << Pointer->getSourceRange();
10735}
10736
10737/// Emit error if Operand is incomplete pointer type
10738///
10739/// \returns True if pointer has incomplete type
10741 Expr *Operand) {
10742 QualType ResType = Operand->getType();
10743 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10744 ResType = ResAtomicType->getValueType();
10745
10746 assert(ResType->isAnyPointerType());
10747 QualType PointeeTy = ResType->getPointeeType();
10748 return S.RequireCompleteSizedType(
10749 Loc, PointeeTy,
10750 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10751 Operand->getSourceRange());
10752}
10753
10754/// Check the validity of an arithmetic pointer operand.
10755///
10756/// If the operand has pointer type, this code will check for pointer types
10757/// which are invalid in arithmetic operations. These will be diagnosed
10758/// appropriately, including whether or not the use is supported as an
10759/// extension.
10760///
10761/// \returns True when the operand is valid to use (even if as an extension).
10763 Expr *Operand) {
10764 QualType ResType = Operand->getType();
10765 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10766 ResType = ResAtomicType->getValueType();
10767
10768 if (!ResType->isAnyPointerType()) return true;
10769
10770 QualType PointeeTy = ResType->getPointeeType();
10771 if (PointeeTy->isVoidType()) {
10773 return !S.getLangOpts().CPlusPlus;
10774 }
10775 if (PointeeTy->isFunctionType()) {
10777 return !S.getLangOpts().CPlusPlus;
10778 }
10779
10780 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10781
10782 return true;
10783}
10784
10785/// Check the validity of a binary arithmetic operation w.r.t. pointer
10786/// operands.
10787///
10788/// This routine will diagnose any invalid arithmetic on pointer operands much
10789/// like \see checkArithmeticOpPointerOperand. However, it has special logic
10790/// for emitting a single diagnostic even for operations where both LHS and RHS
10791/// are (potentially problematic) pointers.
10792///
10793/// \returns True when the operand is valid to use (even if as an extension).
10795 Expr *LHSExpr, Expr *RHSExpr) {
10796 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10797 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10798 if (!isLHSPointer && !isRHSPointer) return true;
10799
10800 QualType LHSPointeeTy, RHSPointeeTy;
10801 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10802 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10803
10804 // if both are pointers check if operation is valid wrt address spaces
10805 if (isLHSPointer && isRHSPointer) {
10806 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
10807 S.getASTContext())) {
10808 S.Diag(Loc,
10809 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10810 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10811 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10812 return false;
10813 }
10814 }
10815
10816 // Check for arithmetic on pointers to incomplete types.
10817 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10818 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10819 if (isLHSVoidPtr || isRHSVoidPtr) {
10820 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10821 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10822 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10823
10824 return !S.getLangOpts().CPlusPlus;
10825 }
10826
10827 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10828 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10829 if (isLHSFuncPtr || isRHSFuncPtr) {
10830 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10831 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10832 RHSExpr);
10833 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10834
10835 return !S.getLangOpts().CPlusPlus;
10836 }
10837
10838 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10839 return false;
10840 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10841 return false;
10842
10843 return true;
10844}
10845
10846/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10847/// literal.
10849 Expr *LHSExpr, Expr *RHSExpr) {
10850 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10851 Expr* IndexExpr = RHSExpr;
10852 if (!StrExpr) {
10853 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10854 IndexExpr = LHSExpr;
10855 }
10856
10857 bool IsStringPlusInt = StrExpr &&
10859 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10860 return;
10861
10862 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10863 Self.Diag(OpLoc, diag::warn_string_plus_int)
10864 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10865
10866 // Only print a fixit for "str" + int, not for int + "str".
10867 if (IndexExpr == RHSExpr) {
10868 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10869 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10870 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10872 << FixItHint::CreateInsertion(EndLoc, "]");
10873 } else
10874 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10875}
10876
10877/// Emit a warning when adding a char literal to a string.
10879 Expr *LHSExpr, Expr *RHSExpr) {
10880 const Expr *StringRefExpr = LHSExpr;
10881 const CharacterLiteral *CharExpr =
10882 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10883
10884 if (!CharExpr) {
10885 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10886 StringRefExpr = RHSExpr;
10887 }
10888
10889 if (!CharExpr || !StringRefExpr)
10890 return;
10891
10892 const QualType StringType = StringRefExpr->getType();
10893
10894 // Return if not a PointerType.
10895 if (!StringType->isAnyPointerType())
10896 return;
10897
10898 // Return if not a CharacterType.
10899 if (!StringType->getPointeeType()->isAnyCharacterType())
10900 return;
10901
10902 ASTContext &Ctx = Self.getASTContext();
10903 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10904
10905 const QualType CharType = CharExpr->getType();
10906 if (!CharType->isAnyCharacterType() &&
10907 CharType->isIntegerType() &&
10908 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10909 Self.Diag(OpLoc, diag::warn_string_plus_char)
10910 << DiagRange << Ctx.CharTy;
10911 } else {
10912 Self.Diag(OpLoc, diag::warn_string_plus_char)
10913 << DiagRange << CharExpr->getType();
10914 }
10915
10916 // Only print a fixit for str + char, not for char + str.
10917 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10918 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10919 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10920 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10922 << FixItHint::CreateInsertion(EndLoc, "]");
10923 } else {
10924 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10925 }
10926}
10927
10928/// Emit error when two pointers are incompatible.
10930 Expr *LHSExpr, Expr *RHSExpr) {
10931 assert(LHSExpr->getType()->isAnyPointerType());
10932 assert(RHSExpr->getType()->isAnyPointerType());
10933 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10934 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10935 << RHSExpr->getSourceRange();
10936}
10937
10938// C99 6.5.6
10941 QualType* CompLHSTy) {
10942 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10943
10944 if (LHS.get()->getType()->isVectorType() ||
10945 RHS.get()->getType()->isVectorType()) {
10946 QualType compType =
10947 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
10948 /*AllowBothBool*/ getLangOpts().AltiVec,
10949 /*AllowBoolConversions*/ getLangOpts().ZVector,
10950 /*AllowBooleanOperation*/ false,
10951 /*ReportInvalid*/ true);
10952 if (CompLHSTy) *CompLHSTy = compType;
10953 return compType;
10954 }
10955
10956 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10957 RHS.get()->getType()->isSveVLSBuiltinType()) {
10958 QualType compType =
10959 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
10960 if (CompLHSTy)
10961 *CompLHSTy = compType;
10962 return compType;
10963 }
10964
10965 if (LHS.get()->getType()->isConstantMatrixType() ||
10966 RHS.get()->getType()->isConstantMatrixType()) {
10967 QualType compType =
10968 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10969 if (CompLHSTy)
10970 *CompLHSTy = compType;
10971 return compType;
10972 }
10973
10975 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10976 if (LHS.isInvalid() || RHS.isInvalid())
10977 return QualType();
10978
10979 // Diagnose "string literal" '+' int and string '+' "char literal".
10980 if (Opc == BO_Add) {
10981 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10982 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10983 }
10984
10985 // handle the common case first (both operands are arithmetic).
10986 if (!compType.isNull() && compType->isArithmeticType()) {
10987 if (CompLHSTy) *CompLHSTy = compType;
10988 return compType;
10989 }
10990
10991 // Type-checking. Ultimately the pointer's going to be in PExp;
10992 // note that we bias towards the LHS being the pointer.
10993 Expr *PExp = LHS.get(), *IExp = RHS.get();
10994
10995 bool isObjCPointer;
10996 if (PExp->getType()->isPointerType()) {
10997 isObjCPointer = false;
10998 } else if (PExp->getType()->isObjCObjectPointerType()) {
10999 isObjCPointer = true;
11000 } else {
11001 std::swap(PExp, IExp);
11002 if (PExp->getType()->isPointerType()) {
11003 isObjCPointer = false;
11004 } else if (PExp->getType()->isObjCObjectPointerType()) {
11005 isObjCPointer = true;
11006 } else {
11007 return InvalidOperands(Loc, LHS, RHS);
11008 }
11009 }
11010 assert(PExp->getType()->isAnyPointerType());
11011
11012 if (!IExp->getType()->isIntegerType())
11013 return InvalidOperands(Loc, LHS, RHS);
11014
11015 // Adding to a null pointer results in undefined behavior.
11018 // In C++ adding zero to a null pointer is defined.
11019 Expr::EvalResult KnownVal;
11020 if (!getLangOpts().CPlusPlus ||
11021 (!IExp->isValueDependent() &&
11022 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11023 KnownVal.Val.getInt() != 0))) {
11024 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11026 Context, BO_Add, PExp, IExp);
11027 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11028 }
11029 }
11030
11031 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11032 return QualType();
11033
11034 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11035 return QualType();
11036
11037 // Arithmetic on label addresses is normally allowed, except when we add
11038 // a ptrauth signature to the addresses.
11039 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
11040 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11041 << /*addition*/ 1;
11042 return QualType();
11043 }
11044
11045 // Check array bounds for pointer arithemtic
11046 CheckArrayAccess(PExp, IExp);
11047
11048 if (CompLHSTy) {
11050 if (LHSTy.isNull()) {
11051 LHSTy = LHS.get()->getType();
11053 LHSTy = Context.getPromotedIntegerType(LHSTy);
11054 }
11055 *CompLHSTy = LHSTy;
11056 }
11057
11058 return PExp->getType();
11059}
11060
11061// C99 6.5.6
11064 QualType* CompLHSTy) {
11065 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11066
11067 if (LHS.get()->getType()->isVectorType() ||
11068 RHS.get()->getType()->isVectorType()) {
11069 QualType compType =
11070 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11071 /*AllowBothBool*/ getLangOpts().AltiVec,
11072 /*AllowBoolConversions*/ getLangOpts().ZVector,
11073 /*AllowBooleanOperation*/ false,
11074 /*ReportInvalid*/ true);
11075 if (CompLHSTy) *CompLHSTy = compType;
11076 return compType;
11077 }
11078
11079 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11080 RHS.get()->getType()->isSveVLSBuiltinType()) {
11081 QualType compType =
11082 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11083 if (CompLHSTy)
11084 *CompLHSTy = compType;
11085 return compType;
11086 }
11087
11088 if (LHS.get()->getType()->isConstantMatrixType() ||
11089 RHS.get()->getType()->isConstantMatrixType()) {
11090 QualType compType =
11091 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11092 if (CompLHSTy)
11093 *CompLHSTy = compType;
11094 return compType;
11095 }
11096
11098 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11099 if (LHS.isInvalid() || RHS.isInvalid())
11100 return QualType();
11101
11102 // Enforce type constraints: C99 6.5.6p3.
11103
11104 // Handle the common case first (both operands are arithmetic).
11105 if (!compType.isNull() && compType->isArithmeticType()) {
11106 if (CompLHSTy) *CompLHSTy = compType;
11107 return compType;
11108 }
11109
11110 // Either ptr - int or ptr - ptr.
11111 if (LHS.get()->getType()->isAnyPointerType()) {
11112 QualType lpointee = LHS.get()->getType()->getPointeeType();
11113
11114 // Diagnose bad cases where we step over interface counts.
11115 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11116 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11117 return QualType();
11118
11119 // Arithmetic on label addresses is normally allowed, except when we add
11120 // a ptrauth signature to the addresses.
11121 if (isa<AddrLabelExpr>(LHS.get()) &&
11122 getLangOpts().PointerAuthIndirectGotos) {
11123 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11124 << /*subtraction*/ 0;
11125 return QualType();
11126 }
11127
11128 // The result type of a pointer-int computation is the pointer type.
11129 if (RHS.get()->getType()->isIntegerType()) {
11130 // Subtracting from a null pointer should produce a warning.
11131 // The last argument to the diagnose call says this doesn't match the
11132 // GNU int-to-pointer idiom.
11135 // In C++ adding zero to a null pointer is defined.
11136 Expr::EvalResult KnownVal;
11137 if (!getLangOpts().CPlusPlus ||
11138 (!RHS.get()->isValueDependent() &&
11139 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11140 KnownVal.Val.getInt() != 0))) {
11141 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11142 }
11143 }
11144
11145 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11146 return QualType();
11147
11148 // Check array bounds for pointer arithemtic
11149 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11150 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11151
11152 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11153 return LHS.get()->getType();
11154 }
11155
11156 // Handle pointer-pointer subtractions.
11157 if (const PointerType *RHSPTy
11158 = RHS.get()->getType()->getAs<PointerType>()) {
11159 QualType rpointee = RHSPTy->getPointeeType();
11160
11161 if (getLangOpts().CPlusPlus) {
11162 // Pointee types must be the same: C++ [expr.add]
11163 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11164 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11165 }
11166 } else {
11167 // Pointee types must be compatible C99 6.5.6p3
11171 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11172 return QualType();
11173 }
11174 }
11175
11177 LHS.get(), RHS.get()))
11178 return QualType();
11179
11180 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11182 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11184
11185 // Subtracting nullptr or from nullptr is suspect
11186 if (LHSIsNullPtr)
11187 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11188 if (RHSIsNullPtr)
11189 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11190
11191 // The pointee type may have zero size. As an extension, a structure or
11192 // union may have zero size or an array may have zero length. In this
11193 // case subtraction does not make sense.
11194 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11195 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11196 if (ElementSize.isZero()) {
11197 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11198 << rpointee.getUnqualifiedType()
11199 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11200 }
11201 }
11202
11203 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11204 return Context.getPointerDiffType();
11205 }
11206 }
11207
11208 return InvalidOperands(Loc, LHS, RHS);
11209}
11210
11212 if (const EnumType *ET = T->getAs<EnumType>())
11213 return ET->getDecl()->isScoped();
11214 return false;
11215}
11216
11219 QualType LHSType) {
11220 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11221 // so skip remaining warnings as we don't want to modify values within Sema.
11222 if (S.getLangOpts().OpenCL)
11223 return;
11224
11225 // Check right/shifter operand
11226 Expr::EvalResult RHSResult;
11227 if (RHS.get()->isValueDependent() ||
11228 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11229 return;
11230 llvm::APSInt Right = RHSResult.Val.getInt();
11231
11232 if (Right.isNegative()) {
11233 S.DiagRuntimeBehavior(Loc, RHS.get(),
11234 S.PDiag(diag::warn_shift_negative)
11235 << RHS.get()->getSourceRange());
11236 return;
11237 }
11238
11239 QualType LHSExprType = LHS.get()->getType();
11240 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11241 if (LHSExprType->isBitIntType())
11242 LeftSize = S.Context.getIntWidth(LHSExprType);
11243 else if (LHSExprType->isFixedPointType()) {
11244 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11245 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11246 }
11247 if (Right.uge(LeftSize)) {
11248 S.DiagRuntimeBehavior(Loc, RHS.get(),
11249 S.PDiag(diag::warn_shift_gt_typewidth)
11250 << RHS.get()->getSourceRange());
11251 return;
11252 }
11253
11254 // FIXME: We probably need to handle fixed point types specially here.
11255 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11256 return;
11257
11258 // When left shifting an ICE which is signed, we can check for overflow which
11259 // according to C++ standards prior to C++2a has undefined behavior
11260 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11261 // more than the maximum value representable in the result type, so never
11262 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11263 // expression is still probably a bug.)
11264 Expr::EvalResult LHSResult;
11265 if (LHS.get()->isValueDependent() ||
11267 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11268 return;
11269 llvm::APSInt Left = LHSResult.Val.getInt();
11270
11271 // Don't warn if signed overflow is defined, then all the rest of the
11272 // diagnostics will not be triggered because the behavior is defined.
11273 // Also don't warn in C++20 mode (and newer), as signed left shifts
11274 // always wrap and never overflow.
11275 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11276 return;
11277
11278 // If LHS does not have a non-negative value then, the
11279 // behavior is undefined before C++2a. Warn about it.
11280 if (Left.isNegative()) {
11281 S.DiagRuntimeBehavior(Loc, LHS.get(),
11282 S.PDiag(diag::warn_shift_lhs_negative)
11283 << LHS.get()->getSourceRange());
11284 return;
11285 }
11286
11287 llvm::APInt ResultBits =
11288 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11289 if (ResultBits.ule(LeftSize))
11290 return;
11291 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11292 Result = Result.shl(Right);
11293
11294 // Print the bit representation of the signed integer as an unsigned
11295 // hexadecimal number.
11296 SmallString<40> HexResult;
11297 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11298
11299 // If we are only missing a sign bit, this is less likely to result in actual
11300 // bugs -- if the result is cast back to an unsigned type, it will have the
11301 // expected value. Thus we place this behind a different warning that can be
11302 // turned off separately if needed.
11303 if (ResultBits - 1 == LeftSize) {
11304 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11305 << HexResult << LHSType
11306 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11307 return;
11308 }
11309
11310 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11311 << HexResult.str() << Result.getSignificantBits() << LHSType
11312 << Left.getBitWidth() << LHS.get()->getSourceRange()
11313 << RHS.get()->getSourceRange();
11314}
11315
11316/// Return the resulting type when a vector is shifted
11317/// by a scalar or vector shift amount.
11319 SourceLocation Loc, bool IsCompAssign) {
11320 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11321 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11322 !LHS.get()->getType()->isVectorType()) {
11323 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11324 << RHS.get()->getType() << LHS.get()->getType()
11325 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11326 return QualType();
11327 }
11328
11329 if (!IsCompAssign) {
11330 LHS = S.UsualUnaryConversions(LHS.get());
11331 if (LHS.isInvalid()) return QualType();
11332 }
11333
11334 RHS = S.UsualUnaryConversions(RHS.get());
11335 if (RHS.isInvalid()) return QualType();
11336
11337 QualType LHSType = LHS.get()->getType();
11338 // Note that LHS might be a scalar because the routine calls not only in
11339 // OpenCL case.
11340 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11341 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11342
11343 // Note that RHS might not be a vector.
11344 QualType RHSType = RHS.get()->getType();
11345 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11346 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11347
11348 // Do not allow shifts for boolean vectors.
11349 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11350 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11351 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11352 << LHS.get()->getType() << RHS.get()->getType()
11353 << LHS.get()->getSourceRange();
11354 return QualType();
11355 }
11356
11357 // The operands need to be integers.
11358 if (!LHSEleType->isIntegerType()) {
11359 S.Diag(Loc, diag::err_typecheck_expect_int)
11360 << LHS.get()->getType() << LHS.get()->getSourceRange();
11361 return QualType();
11362 }
11363
11364 if (!RHSEleType->isIntegerType()) {
11365 S.Diag(Loc, diag::err_typecheck_expect_int)
11366 << RHS.get()->getType() << RHS.get()->getSourceRange();
11367 return QualType();
11368 }
11369
11370 if (!LHSVecTy) {
11371 assert(RHSVecTy);
11372 if (IsCompAssign)
11373 return RHSType;
11374 if (LHSEleType != RHSEleType) {
11375 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11376 LHSEleType = RHSEleType;
11377 }
11378 QualType VecTy =
11379 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11380 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11381 LHSType = VecTy;
11382 } else if (RHSVecTy) {
11383 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11384 // are applied component-wise. So if RHS is a vector, then ensure
11385 // that the number of elements is the same as LHS...
11386 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11387 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11388 << LHS.get()->getType() << RHS.get()->getType()
11389 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11390 return QualType();
11391 }
11392 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11393 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11394 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11395 if (LHSBT != RHSBT &&
11396 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11397 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11398 << LHS.get()->getType() << RHS.get()->getType()
11399 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11400 }
11401 }
11402 } else {
11403 // ...else expand RHS to match the number of elements in LHS.
11404 QualType VecTy =
11405 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11406 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11407 }
11408
11409 return LHSType;
11410}
11411
11414 bool IsCompAssign) {
11415 if (!IsCompAssign) {
11416 LHS = S.UsualUnaryConversions(LHS.get());
11417 if (LHS.isInvalid())
11418 return QualType();
11419 }
11420
11421 RHS = S.UsualUnaryConversions(RHS.get());
11422 if (RHS.isInvalid())
11423 return QualType();
11424
11425 QualType LHSType = LHS.get()->getType();
11426 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11427 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11428 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11429 : LHSType;
11430
11431 // Note that RHS might not be a vector
11432 QualType RHSType = RHS.get()->getType();
11433 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11434 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11435 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11436 : RHSType;
11437
11438 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11439 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11440 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11441 << LHSType << RHSType << LHS.get()->getSourceRange();
11442 return QualType();
11443 }
11444
11445 if (!LHSEleType->isIntegerType()) {
11446 S.Diag(Loc, diag::err_typecheck_expect_int)
11447 << LHS.get()->getType() << LHS.get()->getSourceRange();
11448 return QualType();
11449 }
11450
11451 if (!RHSEleType->isIntegerType()) {
11452 S.Diag(Loc, diag::err_typecheck_expect_int)
11453 << RHS.get()->getType() << RHS.get()->getSourceRange();
11454 return QualType();
11455 }
11456
11457 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11458 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11459 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11460 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11461 << LHSType << RHSType << LHS.get()->getSourceRange()
11462 << RHS.get()->getSourceRange();
11463 return QualType();
11464 }
11465
11466 if (!LHSType->isSveVLSBuiltinType()) {
11467 assert(RHSType->isSveVLSBuiltinType());
11468 if (IsCompAssign)
11469 return RHSType;
11470 if (LHSEleType != RHSEleType) {
11471 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11472 LHSEleType = RHSEleType;
11473 }
11474 const llvm::ElementCount VecSize =
11475 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11476 QualType VecTy =
11477 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11478 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11479 LHSType = VecTy;
11480 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11481 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11482 S.Context.getTypeSize(LHSBuiltinTy)) {
11483 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11484 << LHSType << RHSType << LHS.get()->getSourceRange()
11485 << RHS.get()->getSourceRange();
11486 return QualType();
11487 }
11488 } else {
11489 const llvm::ElementCount VecSize =
11490 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11491 if (LHSEleType != RHSEleType) {
11492 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11493 RHSEleType = LHSEleType;
11494 }
11495 QualType VecTy =
11496 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11497 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11498 }
11499
11500 return LHSType;
11501}
11502
11503// C99 6.5.7
11506 bool IsCompAssign) {
11507 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11508
11509 // Vector shifts promote their scalar inputs to vector type.
11510 if (LHS.get()->getType()->isVectorType() ||
11511 RHS.get()->getType()->isVectorType()) {
11512 if (LangOpts.ZVector) {
11513 // The shift operators for the z vector extensions work basically
11514 // like general shifts, except that neither the LHS nor the RHS is
11515 // allowed to be a "vector bool".
11516 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11517 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11518 return InvalidOperands(Loc, LHS, RHS);
11519 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11520 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11521 return InvalidOperands(Loc, LHS, RHS);
11522 }
11523 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11524 }
11525
11526 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11527 RHS.get()->getType()->isSveVLSBuiltinType())
11528 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11529
11530 // Shifts don't perform usual arithmetic conversions, they just do integer
11531 // promotions on each operand. C99 6.5.7p3
11532
11533 // For the LHS, do usual unary conversions, but then reset them away
11534 // if this is a compound assignment.
11535 ExprResult OldLHS = LHS;
11536 LHS = UsualUnaryConversions(LHS.get());
11537 if (LHS.isInvalid())
11538 return QualType();
11539 QualType LHSType = LHS.get()->getType();
11540 if (IsCompAssign) LHS = OldLHS;
11541
11542 // The RHS is simpler.
11543 RHS = UsualUnaryConversions(RHS.get());
11544 if (RHS.isInvalid())
11545 return QualType();
11546 QualType RHSType = RHS.get()->getType();
11547
11548 // C99 6.5.7p2: Each of the operands shall have integer type.
11549 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11550 if ((!LHSType->isFixedPointOrIntegerType() &&
11551 !LHSType->hasIntegerRepresentation()) ||
11552 !RHSType->hasIntegerRepresentation())
11553 return InvalidOperands(Loc, LHS, RHS);
11554
11555 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11556 // hasIntegerRepresentation() above instead of this.
11557 if (isScopedEnumerationType(LHSType) ||
11558 isScopedEnumerationType(RHSType)) {
11559 return InvalidOperands(Loc, LHS, RHS);
11560 }
11561 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11562
11563 // "The type of the result is that of the promoted left operand."
11564 return LHSType;
11565}
11566
11567/// Diagnose bad pointer comparisons.
11569 ExprResult &LHS, ExprResult &RHS,
11570 bool IsError) {
11571 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11572 : diag::ext_typecheck_comparison_of_distinct_pointers)
11573 << LHS.get()->getType() << RHS.get()->getType()
11574 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11575}
11576
11577/// Returns false if the pointers are converted to a composite type,
11578/// true otherwise.
11580 ExprResult &LHS, ExprResult &RHS) {
11581 // C++ [expr.rel]p2:
11582 // [...] Pointer conversions (4.10) and qualification
11583 // conversions (4.4) are performed on pointer operands (or on
11584 // a pointer operand and a null pointer constant) to bring
11585 // them to their composite pointer type. [...]
11586 //
11587 // C++ [expr.eq]p1 uses the same notion for (in)equality
11588 // comparisons of pointers.
11589
11590 QualType LHSType = LHS.get()->getType();
11591 QualType RHSType = RHS.get()->getType();
11592 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11593 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11594
11595 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11596 if (T.isNull()) {
11597 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11598 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11599 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11600 else
11601 S.InvalidOperands(Loc, LHS, RHS);
11602 return true;
11603 }
11604
11605 return false;
11606}
11607
11609 ExprResult &LHS,
11610 ExprResult &RHS,
11611 bool IsError) {
11612 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11613 : diag::ext_typecheck_comparison_of_fptr_to_void)
11614 << LHS.get()->getType() << RHS.get()->getType()
11615 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11616}
11617
11619 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11620 case Stmt::ObjCArrayLiteralClass:
11621 case Stmt::ObjCDictionaryLiteralClass:
11622 case Stmt::ObjCStringLiteralClass:
11623 case Stmt::ObjCBoxedExprClass:
11624 return true;
11625 default:
11626 // Note that ObjCBoolLiteral is NOT an object literal!
11627 return false;
11628 }
11629}
11630
11631static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11634
11635 // If this is not actually an Objective-C object, bail out.
11636 if (!Type)
11637 return false;
11638
11639 // Get the LHS object's interface type.
11640 QualType InterfaceType = Type->getPointeeType();
11641
11642 // If the RHS isn't an Objective-C object, bail out.
11643 if (!RHS->getType()->isObjCObjectPointerType())
11644 return false;
11645
11646 // Try to find the -isEqual: method.
11647 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
11648 ObjCMethodDecl *Method =
11649 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
11650 /*IsInstance=*/true);
11651 if (!Method) {
11652 if (Type->isObjCIdType()) {
11653 // For 'id', just check the global pool.
11654 Method =
11656 /*receiverId=*/true);
11657 } else {
11658 // Check protocols.
11659 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
11660 /*IsInstance=*/true);
11661 }
11662 }
11663
11664 if (!Method)
11665 return false;
11666
11667 QualType T = Method->parameters()[0]->getType();
11668 if (!T->isObjCObjectPointerType())
11669 return false;
11670
11671 QualType R = Method->getReturnType();
11672 if (!R->isScalarType())
11673 return false;
11674
11675 return true;
11676}
11677
11679 ExprResult &LHS, ExprResult &RHS,
11681 Expr *Literal;
11682 Expr *Other;
11683 if (isObjCObjectLiteral(LHS)) {
11684 Literal = LHS.get();
11685 Other = RHS.get();
11686 } else {
11687 Literal = RHS.get();
11688 Other = LHS.get();
11689 }
11690
11691 // Don't warn on comparisons against nil.
11692 Other = Other->IgnoreParenCasts();
11693 if (Other->isNullPointerConstant(S.getASTContext(),
11695 return;
11696
11697 // This should be kept in sync with warn_objc_literal_comparison.
11698 // LK_String should always be after the other literals, since it has its own
11699 // warning flag.
11700 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
11701 assert(LiteralKind != SemaObjC::LK_Block);
11702 if (LiteralKind == SemaObjC::LK_None) {
11703 llvm_unreachable("Unknown Objective-C object literal kind");
11704 }
11705
11706 if (LiteralKind == SemaObjC::LK_String)
11707 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11708 << Literal->getSourceRange();
11709 else
11710 S.Diag(Loc, diag::warn_objc_literal_comparison)
11711 << LiteralKind << Literal->getSourceRange();
11712
11714 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11715 SourceLocation Start = LHS.get()->getBeginLoc();
11717 CharSourceRange OpRange =
11719
11720 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11721 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11722 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11723 << FixItHint::CreateInsertion(End, "]");
11724 }
11725}
11726
11727/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11730 BinaryOperatorKind Opc) {
11731 // Check that left hand side is !something.
11732 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11733 if (!UO || UO->getOpcode() != UO_LNot) return;
11734
11735 // Only check if the right hand side is non-bool arithmetic type.
11736 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11737
11738 // Make sure that the something in !something is not bool.
11739 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11740 if (SubExpr->isKnownToHaveBooleanValue()) return;
11741
11742 // Emit warning.
11743 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11744 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11745 << Loc << IsBitwiseOp;
11746
11747 // First note suggest !(x < y)
11748 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11749 SourceLocation FirstClose = RHS.get()->getEndLoc();
11750 FirstClose = S.getLocForEndOfToken(FirstClose);
11751 if (FirstClose.isInvalid())
11752 FirstOpen = SourceLocation();
11753 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11754 << IsBitwiseOp
11755 << FixItHint::CreateInsertion(FirstOpen, "(")
11756 << FixItHint::CreateInsertion(FirstClose, ")");
11757
11758 // Second note suggests (!x) < y
11759 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11760 SourceLocation SecondClose = LHS.get()->getEndLoc();
11761 SecondClose = S.getLocForEndOfToken(SecondClose);
11762 if (SecondClose.isInvalid())
11763 SecondOpen = SourceLocation();
11764 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11765 << FixItHint::CreateInsertion(SecondOpen, "(")
11766 << FixItHint::CreateInsertion(SecondClose, ")");
11767}
11768
11769// Returns true if E refers to a non-weak array.
11770static bool checkForArray(const Expr *E) {
11771 const ValueDecl *D = nullptr;
11772 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11773 D = DR->getDecl();
11774 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11775 if (Mem->isImplicitAccess())
11776 D = Mem->getMemberDecl();
11777 }
11778 if (!D)
11779 return false;
11780 return D->getType()->isArrayType() && !D->isWeak();
11781}
11782
11783/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
11784/// pointer and size is an unsigned integer. Return whether the result is
11785/// always true/false.
11786static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
11787 const Expr *RHS,
11788 BinaryOperatorKind Opc) {
11789 if (!LHS->getType()->isPointerType() ||
11791 return std::nullopt;
11792
11793 // Canonicalize to >= or < predicate.
11794 switch (Opc) {
11795 case BO_GE:
11796 case BO_LT:
11797 break;
11798 case BO_GT:
11799 std::swap(LHS, RHS);
11800 Opc = BO_LT;
11801 break;
11802 case BO_LE:
11803 std::swap(LHS, RHS);
11804 Opc = BO_GE;
11805 break;
11806 default:
11807 return std::nullopt;
11808 }
11809
11810 auto *BO = dyn_cast<BinaryOperator>(LHS);
11811 if (!BO || BO->getOpcode() != BO_Add)
11812 return std::nullopt;
11813
11814 Expr *Other;
11815 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
11816 Other = BO->getRHS();
11817 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
11818 Other = BO->getLHS();
11819 else
11820 return std::nullopt;
11821
11822 if (!Other->getType()->isUnsignedIntegerType())
11823 return std::nullopt;
11824
11825 return Opc == BO_GE;
11826}
11827
11828/// Diagnose some forms of syntactically-obvious tautological comparison.
11830 Expr *LHS, Expr *RHS,
11831 BinaryOperatorKind Opc) {
11832 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11833 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11834
11835 QualType LHSType = LHS->getType();
11836 QualType RHSType = RHS->getType();
11837 if (LHSType->hasFloatingRepresentation() ||
11838 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11840 return;
11841
11842 // WebAssembly Tables cannot be compared, therefore shouldn't emit
11843 // Tautological diagnostics.
11844 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
11845 return;
11846
11847 // Comparisons between two array types are ill-formed for operator<=>, so
11848 // we shouldn't emit any additional warnings about it.
11849 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11850 return;
11851
11852 // For non-floating point types, check for self-comparisons of the form
11853 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11854 // often indicate logic errors in the program.
11855 //
11856 // NOTE: Don't warn about comparison expressions resulting from macro
11857 // expansion. Also don't warn about comparisons which are only self
11858 // comparisons within a template instantiation. The warnings should catch
11859 // obvious cases in the definition of the template anyways. The idea is to
11860 // warn when the typed comparison operator will always evaluate to the same
11861 // result.
11862
11863 // Used for indexing into %select in warn_comparison_always
11864 enum {
11865 AlwaysConstant,
11866 AlwaysTrue,
11867 AlwaysFalse,
11868 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11869 };
11870
11871 // C++1a [array.comp]:
11872 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11873 // operands of array type.
11874 // C++2a [depr.array.comp]:
11875 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11876 // operands of array type are deprecated.
11877 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
11878 RHSStripped->getType()->isArrayType()) {
11879 auto IsDeprArrayComparionIgnored =
11880 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
11881 auto DiagID = S.getLangOpts().CPlusPlus26
11882 ? diag::warn_array_comparison_cxx26
11883 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
11884 ? diag::warn_array_comparison
11885 : diag::warn_depr_array_comparison;
11886 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
11887 << LHSStripped->getType() << RHSStripped->getType();
11888 // Carry on to produce the tautological comparison warning, if this
11889 // expression is potentially-evaluated, we can resolve the array to a
11890 // non-weak declaration, and so on.
11891 }
11892
11893 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11894 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11895 unsigned Result;
11896 switch (Opc) {
11897 case BO_EQ:
11898 case BO_LE:
11899 case BO_GE:
11900 Result = AlwaysTrue;
11901 break;
11902 case BO_NE:
11903 case BO_LT:
11904 case BO_GT:
11905 Result = AlwaysFalse;
11906 break;
11907 case BO_Cmp:
11908 Result = AlwaysEqual;
11909 break;
11910 default:
11911 Result = AlwaysConstant;
11912 break;
11913 }
11914 S.DiagRuntimeBehavior(Loc, nullptr,
11915 S.PDiag(diag::warn_comparison_always)
11916 << 0 /*self-comparison*/
11917 << Result);
11918 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11919 // What is it always going to evaluate to?
11920 unsigned Result;
11921 switch (Opc) {
11922 case BO_EQ: // e.g. array1 == array2
11923 Result = AlwaysFalse;
11924 break;
11925 case BO_NE: // e.g. array1 != array2
11926 Result = AlwaysTrue;
11927 break;
11928 default: // e.g. array1 <= array2
11929 // The best we can say is 'a constant'
11930 Result = AlwaysConstant;
11931 break;
11932 }
11933 S.DiagRuntimeBehavior(Loc, nullptr,
11934 S.PDiag(diag::warn_comparison_always)
11935 << 1 /*array comparison*/
11936 << Result);
11937 } else if (std::optional<bool> Res =
11938 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
11939 S.DiagRuntimeBehavior(Loc, nullptr,
11940 S.PDiag(diag::warn_comparison_always)
11941 << 2 /*pointer comparison*/
11942 << (*Res ? AlwaysTrue : AlwaysFalse));
11943 }
11944 }
11945
11946 if (isa<CastExpr>(LHSStripped))
11947 LHSStripped = LHSStripped->IgnoreParenCasts();
11948 if (isa<CastExpr>(RHSStripped))
11949 RHSStripped = RHSStripped->IgnoreParenCasts();
11950
11951 // Warn about comparisons against a string constant (unless the other
11952 // operand is null); the user probably wants string comparison function.
11953 Expr *LiteralString = nullptr;
11954 Expr *LiteralStringStripped = nullptr;
11955 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11956 !RHSStripped->isNullPointerConstant(S.Context,
11958 LiteralString = LHS;
11959 LiteralStringStripped = LHSStripped;
11960 } else if ((isa<StringLiteral>(RHSStripped) ||
11961 isa<ObjCEncodeExpr>(RHSStripped)) &&
11962 !LHSStripped->isNullPointerConstant(S.Context,
11964 LiteralString = RHS;
11965 LiteralStringStripped = RHSStripped;
11966 }
11967
11968 if (LiteralString) {
11969 S.DiagRuntimeBehavior(Loc, nullptr,
11970 S.PDiag(diag::warn_stringcompare)
11971 << isa<ObjCEncodeExpr>(LiteralStringStripped)
11972 << LiteralString->getSourceRange());
11973 }
11974}
11975
11977 switch (CK) {
11978 default: {
11979#ifndef NDEBUG
11980 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11981 << "\n";
11982#endif
11983 llvm_unreachable("unhandled cast kind");
11984 }
11985 case CK_UserDefinedConversion:
11986 return ICK_Identity;
11987 case CK_LValueToRValue:
11988 return ICK_Lvalue_To_Rvalue;
11989 case CK_ArrayToPointerDecay:
11990 return ICK_Array_To_Pointer;
11991 case CK_FunctionToPointerDecay:
11993 case CK_IntegralCast:
11995 case CK_FloatingCast:
11997 case CK_IntegralToFloating:
11998 case CK_FloatingToIntegral:
11999 return ICK_Floating_Integral;
12000 case CK_IntegralComplexCast:
12001 case CK_FloatingComplexCast:
12002 case CK_FloatingComplexToIntegralComplex:
12003 case CK_IntegralComplexToFloatingComplex:
12005 case CK_FloatingComplexToReal:
12006 case CK_FloatingRealToComplex:
12007 case CK_IntegralComplexToReal:
12008 case CK_IntegralRealToComplex:
12009 return ICK_Complex_Real;
12010 case CK_HLSLArrayRValue:
12011 return ICK_HLSL_Array_RValue;
12012 }
12013}
12014
12016 QualType FromType,
12018 // Check for a narrowing implicit conversion.
12021 SCS.setToType(0, FromType);
12022 SCS.setToType(1, ToType);
12023 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12024 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12025
12026 APValue PreNarrowingValue;
12027 QualType PreNarrowingType;
12028 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12029 PreNarrowingType,
12030 /*IgnoreFloatToIntegralConversion*/ true)) {
12032 // Implicit conversion to a narrower type, but the expression is
12033 // value-dependent so we can't tell whether it's actually narrowing.
12034 case NK_Not_Narrowing:
12035 return false;
12036
12038 // Implicit conversion to a narrower type, and the value is not a constant
12039 // expression.
12040 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12041 << /*Constant*/ 1
12042 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12043 return true;
12044
12046 // Implicit conversion to a narrower type, and the value is not a constant
12047 // expression.
12048 case NK_Type_Narrowing:
12049 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12050 << /*Constant*/ 0 << FromType << ToType;
12051 // TODO: It's not a constant expression, but what if the user intended it
12052 // to be? Can we produce notes to help them figure out why it isn't?
12053 return true;
12054 }
12055 llvm_unreachable("unhandled case in switch");
12056}
12057
12059 ExprResult &LHS,
12060 ExprResult &RHS,
12062 QualType LHSType = LHS.get()->getType();
12063 QualType RHSType = RHS.get()->getType();
12064 // Dig out the original argument type and expression before implicit casts
12065 // were applied. These are the types/expressions we need to check the
12066 // [expr.spaceship] requirements against.
12067 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12068 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12069 QualType LHSStrippedType = LHSStripped.get()->getType();
12070 QualType RHSStrippedType = RHSStripped.get()->getType();
12071
12072 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12073 // other is not, the program is ill-formed.
12074 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12075 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12076 return QualType();
12077 }
12078
12079 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12080 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12081 RHSStrippedType->isEnumeralType();
12082 if (NumEnumArgs == 1) {
12083 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12084 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12085 if (OtherTy->hasFloatingRepresentation()) {
12086 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12087 return QualType();
12088 }
12089 }
12090 if (NumEnumArgs == 2) {
12091 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12092 // type E, the operator yields the result of converting the operands
12093 // to the underlying type of E and applying <=> to the converted operands.
12094 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12095 S.InvalidOperands(Loc, LHS, RHS);
12096 return QualType();
12097 }
12098 QualType IntType =
12099 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12100 assert(IntType->isArithmeticType());
12101
12102 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12103 // promote the boolean type, and all other promotable integer types, to
12104 // avoid this.
12105 if (S.Context.isPromotableIntegerType(IntType))
12106 IntType = S.Context.getPromotedIntegerType(IntType);
12107
12108 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12109 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12110 LHSType = RHSType = IntType;
12111 }
12112
12113 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12114 // usual arithmetic conversions are applied to the operands.
12115 QualType Type =
12117 if (LHS.isInvalid() || RHS.isInvalid())
12118 return QualType();
12119 if (Type.isNull())
12120 return S.InvalidOperands(Loc, LHS, RHS);
12121
12122 std::optional<ComparisonCategoryType> CCT =
12124 if (!CCT)
12125 return S.InvalidOperands(Loc, LHS, RHS);
12126
12127 bool HasNarrowing = checkThreeWayNarrowingConversion(
12128 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12129 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12130 RHS.get()->getBeginLoc());
12131 if (HasNarrowing)
12132 return QualType();
12133
12134 assert(!Type.isNull() && "composite type for <=> has not been set");
12135
12138}
12139
12141 ExprResult &RHS,
12143 BinaryOperatorKind Opc) {
12144 if (Opc == BO_Cmp)
12145 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12146
12147 // C99 6.5.8p3 / C99 6.5.9p4
12148 QualType Type =
12150 if (LHS.isInvalid() || RHS.isInvalid())
12151 return QualType();
12152 if (Type.isNull())
12153 return S.InvalidOperands(Loc, LHS, RHS);
12154 assert(Type->isArithmeticType() || Type->isEnumeralType());
12155
12157 return S.InvalidOperands(Loc, LHS, RHS);
12158
12159 // Check for comparisons of floating point operands using != and ==.
12161 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12162
12163 // The result of comparisons is 'bool' in C++, 'int' in C.
12165}
12166
12168 if (!NullE.get()->getType()->isAnyPointerType())
12169 return;
12170 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12171 if (!E.get()->getType()->isAnyPointerType() &&
12175 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12176 if (CL->getValue() == 0)
12177 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12178 << NullValue
12180 NullValue ? "NULL" : "(void *)0");
12181 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12182 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12184 if (T == Context.CharTy)
12185 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12186 << NullValue
12188 NullValue ? "NULL" : "(void *)0");
12189 }
12190 }
12191}
12192
12193// C99 6.5.8, C++ [expr.rel]
12196 BinaryOperatorKind Opc) {
12197 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12198 bool IsThreeWay = Opc == BO_Cmp;
12199 bool IsOrdered = IsRelational || IsThreeWay;
12200 auto IsAnyPointerType = [](ExprResult E) {
12201 QualType Ty = E.get()->getType();
12202 return Ty->isPointerType() || Ty->isMemberPointerType();
12203 };
12204
12205 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12206 // type, array-to-pointer, ..., conversions are performed on both operands to
12207 // bring them to their composite type.
12208 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12209 // any type-related checks.
12210 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12212 if (LHS.isInvalid())
12213 return QualType();
12215 if (RHS.isInvalid())
12216 return QualType();
12217 } else {
12218 LHS = DefaultLvalueConversion(LHS.get());
12219 if (LHS.isInvalid())
12220 return QualType();
12221 RHS = DefaultLvalueConversion(RHS.get());
12222 if (RHS.isInvalid())
12223 return QualType();
12224 }
12225
12226 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12230 }
12231
12232 // Handle vector comparisons separately.
12233 if (LHS.get()->getType()->isVectorType() ||
12234 RHS.get()->getType()->isVectorType())
12235 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12236
12237 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12238 RHS.get()->getType()->isSveVLSBuiltinType())
12239 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12240
12241 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12242 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12243
12244 QualType LHSType = LHS.get()->getType();
12245 QualType RHSType = RHS.get()->getType();
12246 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12247 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12248 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12249
12250 if ((LHSType->isPointerType() &&
12252 (RHSType->isPointerType() &&
12254 return InvalidOperands(Loc, LHS, RHS);
12255
12256 const Expr::NullPointerConstantKind LHSNullKind =
12258 const Expr::NullPointerConstantKind RHSNullKind =
12260 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12261 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12262
12263 auto computeResultTy = [&]() {
12264 if (Opc != BO_Cmp)
12266 assert(getLangOpts().CPlusPlus);
12267 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12268
12269 QualType CompositeTy = LHS.get()->getType();
12270 assert(!CompositeTy->isReferenceType());
12271
12272 std::optional<ComparisonCategoryType> CCT =
12274 if (!CCT)
12275 return InvalidOperands(Loc, LHS, RHS);
12276
12277 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12278 // P0946R0: Comparisons between a null pointer constant and an object
12279 // pointer result in std::strong_equality, which is ill-formed under
12280 // P1959R0.
12281 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12282 << (LHSIsNull ? LHS.get()->getSourceRange()
12283 : RHS.get()->getSourceRange());
12284 return QualType();
12285 }
12286
12289 };
12290
12291 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12292 bool IsEquality = Opc == BO_EQ;
12293 if (RHSIsNull)
12294 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12295 RHS.get()->getSourceRange());
12296 else
12297 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12298 LHS.get()->getSourceRange());
12299 }
12300
12301 if (IsOrdered && LHSType->isFunctionPointerType() &&
12302 RHSType->isFunctionPointerType()) {
12303 // Valid unless a relational comparison of function pointers
12304 bool IsError = Opc == BO_Cmp;
12305 auto DiagID =
12306 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12307 : getLangOpts().CPlusPlus
12308 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12309 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12310 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12311 << RHS.get()->getSourceRange();
12312 if (IsError)
12313 return QualType();
12314 }
12315
12316 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12317 (RHSType->isIntegerType() && !RHSIsNull)) {
12318 // Skip normal pointer conversion checks in this case; we have better
12319 // diagnostics for this below.
12320 } else if (getLangOpts().CPlusPlus) {
12321 // Equality comparison of a function pointer to a void pointer is invalid,
12322 // but we allow it as an extension.
12323 // FIXME: If we really want to allow this, should it be part of composite
12324 // pointer type computation so it works in conditionals too?
12325 if (!IsOrdered &&
12326 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12327 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12328 // This is a gcc extension compatibility comparison.
12329 // In a SFINAE context, we treat this as a hard error to maintain
12330 // conformance with the C++ standard.
12332 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12333
12334 if (isSFINAEContext())
12335 return QualType();
12336
12337 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12338 return computeResultTy();
12339 }
12340
12341 // C++ [expr.eq]p2:
12342 // If at least one operand is a pointer [...] bring them to their
12343 // composite pointer type.
12344 // C++ [expr.spaceship]p6
12345 // If at least one of the operands is of pointer type, [...] bring them
12346 // to their composite pointer type.
12347 // C++ [expr.rel]p2:
12348 // If both operands are pointers, [...] bring them to their composite
12349 // pointer type.
12350 // For <=>, the only valid non-pointer types are arrays and functions, and
12351 // we already decayed those, so this is really the same as the relational
12352 // comparison rule.
12353 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12354 (IsOrdered ? 2 : 1) &&
12355 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12356 RHSType->isObjCObjectPointerType()))) {
12357 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12358 return QualType();
12359 return computeResultTy();
12360 }
12361 } else if (LHSType->isPointerType() &&
12362 RHSType->isPointerType()) { // C99 6.5.8p2
12363 // All of the following pointer-related warnings are GCC extensions, except
12364 // when handling null pointer constants.
12365 QualType LCanPointeeTy =
12367 QualType RCanPointeeTy =
12369
12370 // C99 6.5.9p2 and C99 6.5.8p2
12371 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12372 RCanPointeeTy.getUnqualifiedType())) {
12373 if (IsRelational) {
12374 // Pointers both need to point to complete or incomplete types
12375 if ((LCanPointeeTy->isIncompleteType() !=
12376 RCanPointeeTy->isIncompleteType()) &&
12377 !getLangOpts().C11) {
12378 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12379 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12380 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12381 << RCanPointeeTy->isIncompleteType();
12382 }
12383 }
12384 } else if (!IsRelational &&
12385 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12386 // Valid unless comparison between non-null pointer and function pointer
12387 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12388 && !LHSIsNull && !RHSIsNull)
12390 /*isError*/false);
12391 } else {
12392 // Invalid
12393 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12394 }
12395 if (LCanPointeeTy != RCanPointeeTy) {
12396 // Treat NULL constant as a special case in OpenCL.
12397 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12398 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
12399 getASTContext())) {
12400 Diag(Loc,
12401 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12402 << LHSType << RHSType << 0 /* comparison */
12403 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12404 }
12405 }
12406 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12407 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12408 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12409 : CK_BitCast;
12410 if (LHSIsNull && !RHSIsNull)
12411 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12412 else
12413 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12414 }
12415 return computeResultTy();
12416 }
12417
12418
12419 // C++ [expr.eq]p4:
12420 // Two operands of type std::nullptr_t or one operand of type
12421 // std::nullptr_t and the other a null pointer constant compare
12422 // equal.
12423 // C23 6.5.9p5:
12424 // If both operands have type nullptr_t or one operand has type nullptr_t
12425 // and the other is a null pointer constant, they compare equal if the
12426 // former is a null pointer.
12427 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12428 if (LHSType->isNullPtrType()) {
12429 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12430 return computeResultTy();
12431 }
12432 if (RHSType->isNullPtrType()) {
12433 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12434 return computeResultTy();
12435 }
12436 }
12437
12438 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12439 // C23 6.5.9p6:
12440 // Otherwise, at least one operand is a pointer. If one is a pointer and
12441 // the other is a null pointer constant or has type nullptr_t, they
12442 // compare equal
12443 if (LHSIsNull && RHSType->isPointerType()) {
12444 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12445 return computeResultTy();
12446 }
12447 if (RHSIsNull && LHSType->isPointerType()) {
12448 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12449 return computeResultTy();
12450 }
12451 }
12452
12453 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12454 // These aren't covered by the composite pointer type rules.
12455 if (!IsOrdered && RHSType->isNullPtrType() &&
12456 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12457 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12458 return computeResultTy();
12459 }
12460 if (!IsOrdered && LHSType->isNullPtrType() &&
12461 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12462 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12463 return computeResultTy();
12464 }
12465
12466 if (getLangOpts().CPlusPlus) {
12467 if (IsRelational &&
12468 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12469 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12470 // HACK: Relational comparison of nullptr_t against a pointer type is
12471 // invalid per DR583, but we allow it within std::less<> and friends,
12472 // since otherwise common uses of it break.
12473 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12474 // friends to have std::nullptr_t overload candidates.
12475 DeclContext *DC = CurContext;
12476 if (isa<FunctionDecl>(DC))
12477 DC = DC->getParent();
12478 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12479 if (CTSD->isInStdNamespace() &&
12480 llvm::StringSwitch<bool>(CTSD->getName())
12481 .Cases("less", "less_equal", "greater", "greater_equal", true)
12482 .Default(false)) {
12483 if (RHSType->isNullPtrType())
12484 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12485 else
12486 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12487 return computeResultTy();
12488 }
12489 }
12490 }
12491
12492 // C++ [expr.eq]p2:
12493 // If at least one operand is a pointer to member, [...] bring them to
12494 // their composite pointer type.
12495 if (!IsOrdered &&
12496 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12497 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12498 return QualType();
12499 else
12500 return computeResultTy();
12501 }
12502 }
12503
12504 // Handle block pointer types.
12505 if (!IsOrdered && LHSType->isBlockPointerType() &&
12506 RHSType->isBlockPointerType()) {
12507 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12508 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12509
12510 if (!LHSIsNull && !RHSIsNull &&
12511 !Context.typesAreCompatible(lpointee, rpointee)) {
12512 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12513 << LHSType << RHSType << LHS.get()->getSourceRange()
12514 << RHS.get()->getSourceRange();
12515 }
12516 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12517 return computeResultTy();
12518 }
12519
12520 // Allow block pointers to be compared with null pointer constants.
12521 if (!IsOrdered
12522 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12523 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12524 if (!LHSIsNull && !RHSIsNull) {
12525 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12527 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12528 ->getPointeeType()->isVoidType())))
12529 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12530 << LHSType << RHSType << LHS.get()->getSourceRange()
12531 << RHS.get()->getSourceRange();
12532 }
12533 if (LHSIsNull && !RHSIsNull)
12534 LHS = ImpCastExprToType(LHS.get(), RHSType,
12535 RHSType->isPointerType() ? CK_BitCast
12536 : CK_AnyPointerToBlockPointerCast);
12537 else
12538 RHS = ImpCastExprToType(RHS.get(), LHSType,
12539 LHSType->isPointerType() ? CK_BitCast
12540 : CK_AnyPointerToBlockPointerCast);
12541 return computeResultTy();
12542 }
12543
12544 if (LHSType->isObjCObjectPointerType() ||
12545 RHSType->isObjCObjectPointerType()) {
12546 const PointerType *LPT = LHSType->getAs<PointerType>();
12547 const PointerType *RPT = RHSType->getAs<PointerType>();
12548 if (LPT || RPT) {
12549 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12550 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12551
12552 if (!LPtrToVoid && !RPtrToVoid &&
12553 !Context.typesAreCompatible(LHSType, RHSType)) {
12554 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12555 /*isError*/false);
12556 }
12557 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12558 // the RHS, but we have test coverage for this behavior.
12559 // FIXME: Consider using convertPointersToCompositeType in C++.
12560 if (LHSIsNull && !RHSIsNull) {
12561 Expr *E = LHS.get();
12562 if (getLangOpts().ObjCAutoRefCount)
12563 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
12565 LHS = ImpCastExprToType(E, RHSType,
12566 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12567 }
12568 else {
12569 Expr *E = RHS.get();
12570 if (getLangOpts().ObjCAutoRefCount)
12571 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
12573 /*Diagnose=*/true,
12574 /*DiagnoseCFAudited=*/false, Opc);
12575 RHS = ImpCastExprToType(E, LHSType,
12576 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12577 }
12578 return computeResultTy();
12579 }
12580 if (LHSType->isObjCObjectPointerType() &&
12581 RHSType->isObjCObjectPointerType()) {
12582 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12583 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12584 /*isError*/false);
12586 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12587
12588 if (LHSIsNull && !RHSIsNull)
12589 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12590 else
12591 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12592 return computeResultTy();
12593 }
12594
12595 if (!IsOrdered && LHSType->isBlockPointerType() &&
12597 LHS = ImpCastExprToType(LHS.get(), RHSType,
12598 CK_BlockPointerToObjCPointerCast);
12599 return computeResultTy();
12600 } else if (!IsOrdered &&
12602 RHSType->isBlockPointerType()) {
12603 RHS = ImpCastExprToType(RHS.get(), LHSType,
12604 CK_BlockPointerToObjCPointerCast);
12605 return computeResultTy();
12606 }
12607 }
12608 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12609 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12610 unsigned DiagID = 0;
12611 bool isError = false;
12612 if (LangOpts.DebuggerSupport) {
12613 // Under a debugger, allow the comparison of pointers to integers,
12614 // since users tend to want to compare addresses.
12615 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12616 (RHSIsNull && RHSType->isIntegerType())) {
12617 if (IsOrdered) {
12618 isError = getLangOpts().CPlusPlus;
12619 DiagID =
12620 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12621 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12622 }
12623 } else if (getLangOpts().CPlusPlus) {
12624 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12625 isError = true;
12626 } else if (IsOrdered)
12627 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12628 else
12629 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12630
12631 if (DiagID) {
12632 Diag(Loc, DiagID)
12633 << LHSType << RHSType << LHS.get()->getSourceRange()
12634 << RHS.get()->getSourceRange();
12635 if (isError)
12636 return QualType();
12637 }
12638
12639 if (LHSType->isIntegerType())
12640 LHS = ImpCastExprToType(LHS.get(), RHSType,
12641 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12642 else
12643 RHS = ImpCastExprToType(RHS.get(), LHSType,
12644 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12645 return computeResultTy();
12646 }
12647
12648 // Handle block pointers.
12649 if (!IsOrdered && RHSIsNull
12650 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12651 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12652 return computeResultTy();
12653 }
12654 if (!IsOrdered && LHSIsNull
12655 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12656 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12657 return computeResultTy();
12658 }
12659
12660 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12661 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12662 return computeResultTy();
12663 }
12664
12665 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12666 return computeResultTy();
12667 }
12668
12669 if (LHSIsNull && RHSType->isQueueT()) {
12670 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12671 return computeResultTy();
12672 }
12673
12674 if (LHSType->isQueueT() && RHSIsNull) {
12675 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12676 return computeResultTy();
12677 }
12678 }
12679
12680 return InvalidOperands(Loc, LHS, RHS);
12681}
12682
12684 const VectorType *VTy = V->castAs<VectorType>();
12685 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12686
12687 if (isa<ExtVectorType>(VTy)) {
12688 if (VTy->isExtVectorBoolType())
12690 if (TypeSize == Context.getTypeSize(Context.CharTy))
12692 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12694 if (TypeSize == Context.getTypeSize(Context.IntTy))
12696 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12698 if (TypeSize == Context.getTypeSize(Context.LongTy))
12700 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12701 "Unhandled vector element size in vector compare");
12703 }
12704
12705 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12708 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12711 if (TypeSize == Context.getTypeSize(Context.LongTy))
12714 if (TypeSize == Context.getTypeSize(Context.IntTy))
12717 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12720 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12721 "Unhandled vector element size in vector compare");
12724}
12725
12727 const BuiltinType *VTy = V->castAs<BuiltinType>();
12728 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
12729
12730 const QualType ETy = V->getSveEltType(Context);
12731 const auto TypeSize = Context.getTypeSize(ETy);
12732
12733 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12734 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12735 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12736}
12737
12740 BinaryOperatorKind Opc) {
12741 if (Opc == BO_Cmp) {
12742 Diag(Loc, diag::err_three_way_vector_comparison);
12743 return QualType();
12744 }
12745
12746 // Check to make sure we're operating on vectors of the same type and width,
12747 // Allowing one side to be a scalar of element type.
12748 QualType vType =
12749 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12750 /*AllowBothBool*/ true,
12751 /*AllowBoolConversions*/ getLangOpts().ZVector,
12752 /*AllowBooleanOperation*/ true,
12753 /*ReportInvalid*/ true);
12754 if (vType.isNull())
12755 return vType;
12756
12757 QualType LHSType = LHS.get()->getType();
12758
12759 // Determine the return type of a vector compare. By default clang will return
12760 // a scalar for all vector compares except vector bool and vector pixel.
12761 // With the gcc compiler we will always return a vector type and with the xl
12762 // compiler we will always return a scalar type. This switch allows choosing
12763 // which behavior is prefered.
12764 if (getLangOpts().AltiVec) {
12765 switch (getLangOpts().getAltivecSrcCompat()) {
12767 // If AltiVec, the comparison results in a numeric type, i.e.
12768 // bool for C++, int for C
12769 if (vType->castAs<VectorType>()->getVectorKind() ==
12772 else
12773 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12774 break;
12776 // For GCC we always return the vector type.
12777 break;
12780 break;
12781 }
12782 }
12783
12784 // For non-floating point types, check for self-comparisons of the form
12785 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12786 // often indicate logic errors in the program.
12787 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12788
12789 // Check for comparisons of floating point operands using != and ==.
12790 if (LHSType->hasFloatingRepresentation()) {
12791 assert(RHS.get()->getType()->hasFloatingRepresentation());
12792 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12793 }
12794
12795 // Return a signed type for the vector.
12796 return GetSignedVectorType(vType);
12797}
12798
12800 ExprResult &RHS,
12802 BinaryOperatorKind Opc) {
12803 if (Opc == BO_Cmp) {
12804 Diag(Loc, diag::err_three_way_vector_comparison);
12805 return QualType();
12806 }
12807
12808 // Check to make sure we're operating on vectors of the same type and width,
12809 // Allowing one side to be a scalar of element type.
12811 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12812
12813 if (vType.isNull())
12814 return vType;
12815
12816 QualType LHSType = LHS.get()->getType();
12817
12818 // For non-floating point types, check for self-comparisons of the form
12819 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12820 // often indicate logic errors in the program.
12821 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12822
12823 // Check for comparisons of floating point operands using != and ==.
12824 if (LHSType->hasFloatingRepresentation()) {
12825 assert(RHS.get()->getType()->hasFloatingRepresentation());
12826 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12827 }
12828
12829 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12830 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12831
12832 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12833 RHSBuiltinTy->isSVEBool())
12834 return LHSType;
12835
12836 // Return a signed type for the vector.
12837 return GetSignedSizelessVectorType(vType);
12838}
12839
12840static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12841 const ExprResult &XorRHS,
12842 const SourceLocation Loc) {
12843 // Do not diagnose macros.
12844 if (Loc.isMacroID())
12845 return;
12846
12847 // Do not diagnose if both LHS and RHS are macros.
12848 if (XorLHS.get()->getExprLoc().isMacroID() &&
12849 XorRHS.get()->getExprLoc().isMacroID())
12850 return;
12851
12852 bool Negative = false;
12853 bool ExplicitPlus = false;
12854 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12855 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12856
12857 if (!LHSInt)
12858 return;
12859 if (!RHSInt) {
12860 // Check negative literals.
12861 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12862 UnaryOperatorKind Opc = UO->getOpcode();
12863 if (Opc != UO_Minus && Opc != UO_Plus)
12864 return;
12865 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12866 if (!RHSInt)
12867 return;
12868 Negative = (Opc == UO_Minus);
12869 ExplicitPlus = !Negative;
12870 } else {
12871 return;
12872 }
12873 }
12874
12875 const llvm::APInt &LeftSideValue = LHSInt->getValue();
12876 llvm::APInt RightSideValue = RHSInt->getValue();
12877 if (LeftSideValue != 2 && LeftSideValue != 10)
12878 return;
12879
12880 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12881 return;
12882
12884 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12885 llvm::StringRef ExprStr =
12887
12888 CharSourceRange XorRange =
12890 llvm::StringRef XorStr =
12892 // Do not diagnose if xor keyword/macro is used.
12893 if (XorStr == "xor")
12894 return;
12895
12896 std::string LHSStr = std::string(Lexer::getSourceText(
12897 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12898 S.getSourceManager(), S.getLangOpts()));
12899 std::string RHSStr = std::string(Lexer::getSourceText(
12900 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12901 S.getSourceManager(), S.getLangOpts()));
12902
12903 if (Negative) {
12904 RightSideValue = -RightSideValue;
12905 RHSStr = "-" + RHSStr;
12906 } else if (ExplicitPlus) {
12907 RHSStr = "+" + RHSStr;
12908 }
12909
12910 StringRef LHSStrRef = LHSStr;
12911 StringRef RHSStrRef = RHSStr;
12912 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12913 // literals.
12914 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
12915 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
12916 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
12917 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
12918 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
12919 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
12920 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12921 return;
12922
12923 bool SuggestXor =
12924 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12925 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12926 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12927 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12928 std::string SuggestedExpr = "1 << " + RHSStr;
12929 bool Overflow = false;
12930 llvm::APInt One = (LeftSideValue - 1);
12931 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12932 if (Overflow) {
12933 if (RightSideIntValue < 64)
12934 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12935 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12936 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12937 else if (RightSideIntValue == 64)
12938 S.Diag(Loc, diag::warn_xor_used_as_pow)
12939 << ExprStr << toString(XorValue, 10, true);
12940 else
12941 return;
12942 } else {
12943 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12944 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12945 << toString(PowValue, 10, true)
12947 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12948 }
12949
12950 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12951 << ("0x2 ^ " + RHSStr) << SuggestXor;
12952 } else if (LeftSideValue == 10) {
12953 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12954 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12955 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12956 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12957 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12958 << ("0xA ^ " + RHSStr) << SuggestXor;
12959 }
12960}
12961
12964 BinaryOperatorKind Opc) {
12965 // Ensure that either both operands are of the same vector type, or
12966 // one operand is of a vector type and the other is of its element type.
12967 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12968 /*AllowBothBool*/ true,
12969 /*AllowBoolConversions*/ false,
12970 /*AllowBooleanOperation*/ false,
12971 /*ReportInvalid*/ false);
12972 if (vType.isNull())
12973 return InvalidOperands(Loc, LHS, RHS);
12974 if (getLangOpts().OpenCL &&
12975 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
12977 return InvalidOperands(Loc, LHS, RHS);
12978 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12979 // usage of the logical operators && and || with vectors in C. This
12980 // check could be notionally dropped.
12981 if (!getLangOpts().CPlusPlus &&
12982 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12983 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12984 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
12985 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
12986 // `select` functions.
12987 if (getLangOpts().HLSL &&
12988 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
12989 (void)InvalidOperands(Loc, LHS, RHS);
12990 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
12991 return QualType();
12992 }
12993
12994 return GetSignedVectorType(LHS.get()->getType());
12995}
12996
12999 bool IsCompAssign) {
13000 if (!IsCompAssign) {
13002 if (LHS.isInvalid())
13003 return QualType();
13004 }
13006 if (RHS.isInvalid())
13007 return QualType();
13008
13009 // For conversion purposes, we ignore any qualifiers.
13010 // For example, "const float" and "float" are equivalent.
13011 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13012 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13013
13014 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13015 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13016 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13017
13018 if (Context.hasSameType(LHSType, RHSType))
13019 return Context.getCommonSugaredType(LHSType, RHSType);
13020
13021 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13022 // case we have to return InvalidOperands.
13023 ExprResult OriginalLHS = LHS;
13024 ExprResult OriginalRHS = RHS;
13025 if (LHSMatType && !RHSMatType) {
13026 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13027 if (!RHS.isInvalid())
13028 return LHSType;
13029
13030 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13031 }
13032
13033 if (!LHSMatType && RHSMatType) {
13034 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13035 if (!LHS.isInvalid())
13036 return RHSType;
13037 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13038 }
13039
13040 return InvalidOperands(Loc, LHS, RHS);
13041}
13042
13045 bool IsCompAssign) {
13046 if (!IsCompAssign) {
13048 if (LHS.isInvalid())
13049 return QualType();
13050 }
13052 if (RHS.isInvalid())
13053 return QualType();
13054
13055 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13056 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13057 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13058
13059 if (LHSMatType && RHSMatType) {
13060 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13061 return InvalidOperands(Loc, LHS, RHS);
13062
13063 if (Context.hasSameType(LHSMatType, RHSMatType))
13065 LHS.get()->getType().getUnqualifiedType(),
13066 RHS.get()->getType().getUnqualifiedType());
13067
13068 QualType LHSELTy = LHSMatType->getElementType(),
13069 RHSELTy = RHSMatType->getElementType();
13070 if (!Context.hasSameType(LHSELTy, RHSELTy))
13071 return InvalidOperands(Loc, LHS, RHS);
13072
13074 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13075 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13076 }
13077 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13078}
13079
13081 switch (Opc) {
13082 default:
13083 return false;
13084 case BO_And:
13085 case BO_AndAssign:
13086 case BO_Or:
13087 case BO_OrAssign:
13088 case BO_Xor:
13089 case BO_XorAssign:
13090 return true;
13091 }
13092}
13093
13096 BinaryOperatorKind Opc) {
13097 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13098
13099 bool IsCompAssign =
13100 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13101
13102 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13103
13104 if (LHS.get()->getType()->isVectorType() ||
13105 RHS.get()->getType()->isVectorType()) {
13106 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13108 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13109 /*AllowBothBool*/ true,
13110 /*AllowBoolConversions*/ getLangOpts().ZVector,
13111 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13112 /*ReportInvalid*/ true);
13113 return InvalidOperands(Loc, LHS, RHS);
13114 }
13115
13116 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13117 RHS.get()->getType()->isSveVLSBuiltinType()) {
13118 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13120 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13122 return InvalidOperands(Loc, LHS, RHS);
13123 }
13124
13125 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13126 RHS.get()->getType()->isSveVLSBuiltinType()) {
13127 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13129 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13131 return InvalidOperands(Loc, LHS, RHS);
13132 }
13133
13134 if (Opc == BO_And)
13135 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13136
13137 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13139 return InvalidOperands(Loc, LHS, RHS);
13140
13141 ExprResult LHSResult = LHS, RHSResult = RHS;
13143 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13144 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13145 return QualType();
13146 LHS = LHSResult.get();
13147 RHS = RHSResult.get();
13148
13149 if (Opc == BO_Xor)
13150 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13151
13152 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13153 return compType;
13154 return InvalidOperands(Loc, LHS, RHS);
13155}
13156
13157// C99 6.5.[13,14]
13160 BinaryOperatorKind Opc) {
13161 // Check vector operands differently.
13162 if (LHS.get()->getType()->isVectorType() ||
13163 RHS.get()->getType()->isVectorType())
13164 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13165
13166 bool EnumConstantInBoolContext = false;
13167 for (const ExprResult &HS : {LHS, RHS}) {
13168 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13169 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13170 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13171 EnumConstantInBoolContext = true;
13172 }
13173 }
13174
13175 if (EnumConstantInBoolContext)
13176 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13177
13178 // WebAssembly tables can't be used with logical operators.
13179 QualType LHSTy = LHS.get()->getType();
13180 QualType RHSTy = RHS.get()->getType();
13181 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13182 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13183 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13184 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13185 return InvalidOperands(Loc, LHS, RHS);
13186 }
13187
13188 // Diagnose cases where the user write a logical and/or but probably meant a
13189 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13190 // is a constant.
13191 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13192 !LHS.get()->getType()->isBooleanType() &&
13193 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13194 // Don't warn in macros or template instantiations.
13196 // If the RHS can be constant folded, and if it constant folds to something
13197 // that isn't 0 or 1 (which indicate a potential logical operation that
13198 // happened to fold to true/false) then warn.
13199 // Parens on the RHS are ignored.
13200 Expr::EvalResult EVResult;
13201 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13202 llvm::APSInt Result = EVResult.Val.getInt();
13203 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13204 !RHS.get()->getExprLoc().isMacroID()) ||
13205 (Result != 0 && Result != 1)) {
13206 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13207 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13208 // Suggest replacing the logical operator with the bitwise version
13209 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13210 << (Opc == BO_LAnd ? "&" : "|")
13213 Opc == BO_LAnd ? "&" : "|");
13214 if (Opc == BO_LAnd)
13215 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13216 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13219 RHS.get()->getEndLoc()));
13220 }
13221 }
13222 }
13223
13224 if (!Context.getLangOpts().CPlusPlus) {
13225 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13226 // not operate on the built-in scalar and vector float types.
13227 if (Context.getLangOpts().OpenCL &&
13228 Context.getLangOpts().OpenCLVersion < 120) {
13229 if (LHS.get()->getType()->isFloatingType() ||
13230 RHS.get()->getType()->isFloatingType())
13231 return InvalidOperands(Loc, LHS, RHS);
13232 }
13233
13234 LHS = UsualUnaryConversions(LHS.get());
13235 if (LHS.isInvalid())
13236 return QualType();
13237
13238 RHS = UsualUnaryConversions(RHS.get());
13239 if (RHS.isInvalid())
13240 return QualType();
13241
13242 if (!LHS.get()->getType()->isScalarType() ||
13243 !RHS.get()->getType()->isScalarType())
13244 return InvalidOperands(Loc, LHS, RHS);
13245
13246 return Context.IntTy;
13247 }
13248
13249 // The following is safe because we only use this method for
13250 // non-overloadable operands.
13251
13252 // C++ [expr.log.and]p1
13253 // C++ [expr.log.or]p1
13254 // The operands are both contextually converted to type bool.
13256 if (LHSRes.isInvalid())
13257 return InvalidOperands(Loc, LHS, RHS);
13258 LHS = LHSRes;
13259
13261 if (RHSRes.isInvalid())
13262 return InvalidOperands(Loc, LHS, RHS);
13263 RHS = RHSRes;
13264
13265 // C++ [expr.log.and]p2
13266 // C++ [expr.log.or]p2
13267 // The result is a bool.
13268 return Context.BoolTy;
13269}
13270
13271static bool IsReadonlyMessage(Expr *E, Sema &S) {
13272 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13273 if (!ME) return false;
13274 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13275 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13277 if (!Base) return false;
13278 return Base->getMethodDecl() != nullptr;
13279}
13280
13281/// Is the given expression (which must be 'const') a reference to a
13282/// variable which was originally non-const, but which has become
13283/// 'const' due to being captured within a block?
13286 assert(E->isLValue() && E->getType().isConstQualified());
13287 E = E->IgnoreParens();
13288
13289 // Must be a reference to a declaration from an enclosing scope.
13290 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13291 if (!DRE) return NCCK_None;
13293
13294 ValueDecl *Value = dyn_cast<ValueDecl>(DRE->getDecl());
13295
13296 // The declaration must be a value which is not declared 'const'.
13297 if (!Value || Value->getType().isConstQualified())
13298 return NCCK_None;
13299
13300 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
13301 if (Binding) {
13302 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
13303 assert(!isa<BlockDecl>(Binding->getDeclContext()));
13304 return NCCK_Lambda;
13305 }
13306
13307 VarDecl *Var = dyn_cast<VarDecl>(Value);
13308 if (!Var)
13309 return NCCK_None;
13310
13311 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
13312
13313 // Decide whether the first capture was for a block or a lambda.
13314 DeclContext *DC = S.CurContext, *Prev = nullptr;
13315 // Decide whether the first capture was for a block or a lambda.
13316 while (DC) {
13317 // For init-capture, it is possible that the variable belongs to the
13318 // template pattern of the current context.
13319 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13320 if (Var->isInitCapture() &&
13321 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
13322 break;
13323 if (DC == Var->getDeclContext())
13324 break;
13325 Prev = DC;
13326 DC = DC->getParent();
13327 }
13328 // Unless we have an init-capture, we've gone one step too far.
13329 if (!Var->isInitCapture())
13330 DC = Prev;
13331 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13332}
13333
13334static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13335 Ty = Ty.getNonReferenceType();
13336 if (IsDereference && Ty->isPointerType())
13337 Ty = Ty->getPointeeType();
13338 return !Ty.isConstQualified();
13339}
13340
13341// Update err_typecheck_assign_const and note_typecheck_assign_const
13342// when this enum is changed.
13343enum {
13349 ConstUnknown, // Keep as last element
13350};
13351
13352/// Emit the "read-only variable not assignable" error and print notes to give
13353/// more information about why the variable is not assignable, such as pointing
13354/// to the declaration of a const variable, showing that a method is const, or
13355/// that the function is returning a const reference.
13356static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13358 SourceRange ExprRange = E->getSourceRange();
13359
13360 // Only emit one error on the first const found. All other consts will emit
13361 // a note to the error.
13362 bool DiagnosticEmitted = false;
13363
13364 // Track if the current expression is the result of a dereference, and if the
13365 // next checked expression is the result of a dereference.
13366 bool IsDereference = false;
13367 bool NextIsDereference = false;
13368
13369 // Loop to process MemberExpr chains.
13370 while (true) {
13371 IsDereference = NextIsDereference;
13372
13374 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13375 NextIsDereference = ME->isArrow();
13376 const ValueDecl *VD = ME->getMemberDecl();
13377 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13378 // Mutable fields can be modified even if the class is const.
13379 if (Field->isMutable()) {
13380 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13381 break;
13382 }
13383
13384 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13385 if (!DiagnosticEmitted) {
13386 S.Diag(Loc, diag::err_typecheck_assign_const)
13387 << ExprRange << ConstMember << false /*static*/ << Field
13388 << Field->getType();
13389 DiagnosticEmitted = true;
13390 }
13391 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13392 << ConstMember << false /*static*/ << Field << Field->getType()
13393 << Field->getSourceRange();
13394 }
13395 E = ME->getBase();
13396 continue;
13397 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13398 if (VDecl->getType().isConstQualified()) {
13399 if (!DiagnosticEmitted) {
13400 S.Diag(Loc, diag::err_typecheck_assign_const)
13401 << ExprRange << ConstMember << true /*static*/ << VDecl
13402 << VDecl->getType();
13403 DiagnosticEmitted = true;
13404 }
13405 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13406 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13407 << VDecl->getSourceRange();
13408 }
13409 // Static fields do not inherit constness from parents.
13410 break;
13411 }
13412 break; // End MemberExpr
13413 } else if (const ArraySubscriptExpr *ASE =
13414 dyn_cast<ArraySubscriptExpr>(E)) {
13415 E = ASE->getBase()->IgnoreParenImpCasts();
13416 continue;
13417 } else if (const ExtVectorElementExpr *EVE =
13418 dyn_cast<ExtVectorElementExpr>(E)) {
13419 E = EVE->getBase()->IgnoreParenImpCasts();
13420 continue;
13421 }
13422 break;
13423 }
13424
13425 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13426 // Function calls
13427 const FunctionDecl *FD = CE->getDirectCallee();
13428 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13429 if (!DiagnosticEmitted) {
13430 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13431 << ConstFunction << FD;
13432 DiagnosticEmitted = true;
13433 }
13435 diag::note_typecheck_assign_const)
13436 << ConstFunction << FD << FD->getReturnType()
13437 << FD->getReturnTypeSourceRange();
13438 }
13439 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13440 // Point to variable declaration.
13441 if (const ValueDecl *VD = DRE->getDecl()) {
13442 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13443 if (!DiagnosticEmitted) {
13444 S.Diag(Loc, diag::err_typecheck_assign_const)
13445 << ExprRange << ConstVariable << VD << VD->getType();
13446 DiagnosticEmitted = true;
13447 }
13448 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13449 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13450 }
13451 }
13452 } else if (isa<CXXThisExpr>(E)) {
13453 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13454 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13455 if (MD->isConst()) {
13456 if (!DiagnosticEmitted) {
13457 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13458 << ConstMethod << MD;
13459 DiagnosticEmitted = true;
13460 }
13461 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13462 << ConstMethod << MD << MD->getSourceRange();
13463 }
13464 }
13465 }
13466 }
13467
13468 if (DiagnosticEmitted)
13469 return;
13470
13471 // Can't determine a more specific message, so display the generic error.
13472 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13473}
13474
13480
13482 const RecordType *Ty,
13484 OriginalExprKind OEK,
13485 bool &DiagnosticEmitted) {
13486 std::vector<const RecordType *> RecordTypeList;
13487 RecordTypeList.push_back(Ty);
13488 unsigned NextToCheckIndex = 0;
13489 // We walk the record hierarchy breadth-first to ensure that we print
13490 // diagnostics in field nesting order.
13491 while (RecordTypeList.size() > NextToCheckIndex) {
13492 bool IsNested = NextToCheckIndex > 0;
13493 for (const FieldDecl *Field :
13494 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13495 // First, check every field for constness.
13496 QualType FieldTy = Field->getType();
13497 if (FieldTy.isConstQualified()) {
13498 if (!DiagnosticEmitted) {
13499 S.Diag(Loc, diag::err_typecheck_assign_const)
13500 << Range << NestedConstMember << OEK << VD
13501 << IsNested << Field;
13502 DiagnosticEmitted = true;
13503 }
13504 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13505 << NestedConstMember << IsNested << Field
13506 << FieldTy << Field->getSourceRange();
13507 }
13508
13509 // Then we append it to the list to check next in order.
13510 FieldTy = FieldTy.getCanonicalType();
13511 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13512 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13513 RecordTypeList.push_back(FieldRecTy);
13514 }
13515 }
13516 ++NextToCheckIndex;
13517 }
13518}
13519
13520/// Emit an error for the case where a record we are trying to assign to has a
13521/// const-qualified field somewhere in its hierarchy.
13524 QualType Ty = E->getType();
13525 assert(Ty->isRecordType() && "lvalue was not record?");
13527 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13528 bool DiagEmitted = false;
13529
13530 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13531 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13532 Range, OEK_Member, DiagEmitted);
13533 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13534 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13535 Range, OEK_Variable, DiagEmitted);
13536 else
13537 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13538 Range, OEK_LValue, DiagEmitted);
13539 if (!DiagEmitted)
13541}
13542
13543/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13544/// emit an error and return true. If so, return false.
13546 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13547
13549
13550 SourceLocation OrigLoc = Loc;
13552 &Loc);
13553 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13555 if (IsLV == Expr::MLV_Valid)
13556 return false;
13557
13558 unsigned DiagID = 0;
13559 bool NeedType = false;
13560 switch (IsLV) { // C99 6.5.16p2
13562 // Use a specialized diagnostic when we're assigning to an object
13563 // from an enclosing function or block.
13565 if (NCCK == NCCK_Block)
13566 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13567 else
13568 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13569 break;
13570 }
13571
13572 // In ARC, use some specialized diagnostics for occasions where we
13573 // infer 'const'. These are always pseudo-strong variables.
13574 if (S.getLangOpts().ObjCAutoRefCount) {
13575 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13576 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13577 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13578
13579 // Use the normal diagnostic if it's pseudo-__strong but the
13580 // user actually wrote 'const'.
13581 if (var->isARCPseudoStrong() &&
13582 (!var->getTypeSourceInfo() ||
13583 !var->getTypeSourceInfo()->getType().isConstQualified())) {
13584 // There are three pseudo-strong cases:
13585 // - self
13586 ObjCMethodDecl *method = S.getCurMethodDecl();
13587 if (method && var == method->getSelfDecl()) {
13588 DiagID = method->isClassMethod()
13589 ? diag::err_typecheck_arc_assign_self_class_method
13590 : diag::err_typecheck_arc_assign_self;
13591
13592 // - Objective-C externally_retained attribute.
13593 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13594 isa<ParmVarDecl>(var)) {
13595 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13596
13597 // - fast enumeration variables
13598 } else {
13599 DiagID = diag::err_typecheck_arr_assign_enumeration;
13600 }
13601
13602 SourceRange Assign;
13603 if (Loc != OrigLoc)
13604 Assign = SourceRange(OrigLoc, OrigLoc);
13605 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13606 // We need to preserve the AST regardless, so migration tool
13607 // can do its job.
13608 return false;
13609 }
13610 }
13611 }
13612
13613 // If none of the special cases above are triggered, then this is a
13614 // simple const assignment.
13615 if (DiagID == 0) {
13617 return true;
13618 }
13619
13620 break;
13623 return true;
13626 return true;
13629 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13630 NeedType = true;
13631 break;
13633 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13634 NeedType = true;
13635 break;
13637 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13638 break;
13639 case Expr::MLV_Valid:
13640 llvm_unreachable("did not take early return for MLV_Valid");
13644 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13645 break;
13648 return S.RequireCompleteType(Loc, E->getType(),
13649 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13651 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13652 break;
13654 llvm_unreachable("readonly properties should be processed differently");
13656 DiagID = diag::err_readonly_message_assignment;
13657 break;
13659 DiagID = diag::err_no_subobject_property_setting;
13660 break;
13661 }
13662
13663 SourceRange Assign;
13664 if (Loc != OrigLoc)
13665 Assign = SourceRange(OrigLoc, OrigLoc);
13666 if (NeedType)
13667 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13668 else
13669 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13670 return true;
13671}
13672
13673static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13675 Sema &Sema) {
13677 return;
13679 return;
13680 if (Loc.isInvalid() || Loc.isMacroID())
13681 return;
13682 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13683 return;
13684
13685 // C / C++ fields
13686 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13687 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13688 if (ML && MR) {
13689 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13690 return;
13691 const ValueDecl *LHSDecl =
13692 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13693 const ValueDecl *RHSDecl =
13694 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13695 if (LHSDecl != RHSDecl)
13696 return;
13697 if (LHSDecl->getType().isVolatileQualified())
13698 return;
13699 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13700 if (RefTy->getPointeeType().isVolatileQualified())
13701 return;
13702
13703 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13704 }
13705
13706 // Objective-C instance variables
13707 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13708 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13709 if (OL && OR && OL->getDecl() == OR->getDecl()) {
13710 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13711 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13712 if (RL && RR && RL->getDecl() == RR->getDecl())
13713 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13714 }
13715}
13716
13717// C99 6.5.16.1
13720 QualType CompoundType,
13721 BinaryOperatorKind Opc) {
13722 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13723
13724 // Verify that LHS is a modifiable lvalue, and emit error if not.
13725 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13726 return QualType();
13727
13728 QualType LHSType = LHSExpr->getType();
13729 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13730 CompoundType;
13731 // OpenCL v1.2 s6.1.1.1 p2:
13732 // The half data type can only be used to declare a pointer to a buffer that
13733 // contains half values
13734 if (getLangOpts().OpenCL &&
13735 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13736 LHSType->isHalfType()) {
13737 Diag(Loc, diag::err_opencl_half_load_store) << 1
13738 << LHSType.getUnqualifiedType();
13739 return QualType();
13740 }
13741
13742 // WebAssembly tables can't be used on RHS of an assignment expression.
13743 if (RHSType->isWebAssemblyTableType()) {
13744 Diag(Loc, diag::err_wasm_table_art) << 0;
13745 return QualType();
13746 }
13747
13748 AssignConvertType ConvTy;
13749 if (CompoundType.isNull()) {
13750 Expr *RHSCheck = RHS.get();
13751
13752 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13753
13754 QualType LHSTy(LHSType);
13755 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13756 if (RHS.isInvalid())
13757 return QualType();
13758 // Special case of NSObject attributes on c-style pointer types.
13759 if (ConvTy == IncompatiblePointer &&
13760 ((Context.isObjCNSObjectType(LHSType) &&
13761 RHSType->isObjCObjectPointerType()) ||
13762 (Context.isObjCNSObjectType(RHSType) &&
13763 LHSType->isObjCObjectPointerType())))
13764 ConvTy = Compatible;
13765
13766 if (ConvTy == Compatible &&
13767 LHSType->isObjCObjectType())
13768 Diag(Loc, diag::err_objc_object_assignment)
13769 << LHSType;
13770
13771 // If the RHS is a unary plus or minus, check to see if they = and + are
13772 // right next to each other. If so, the user may have typo'd "x =+ 4"
13773 // instead of "x += 4".
13774 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13775 RHSCheck = ICE->getSubExpr();
13776 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13777 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13778 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13779 // Only if the two operators are exactly adjacent.
13780 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13781 // And there is a space or other character before the subexpr of the
13782 // unary +/-. We don't want to warn on "x=-1".
13783 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13784 UO->getSubExpr()->getBeginLoc().isFileID()) {
13785 Diag(Loc, diag::warn_not_compound_assign)
13786 << (UO->getOpcode() == UO_Plus ? "+" : "-")
13787 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13788 }
13789 }
13790
13791 if (ConvTy == Compatible) {
13792 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13793 // Warn about retain cycles where a block captures the LHS, but
13794 // not if the LHS is a simple variable into which the block is
13795 // being stored...unless that variable can be captured by reference!
13796 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13797 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13798 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13799 ObjC().checkRetainCycles(LHSExpr, RHS.get());
13800 }
13801
13802 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13804 // It is safe to assign a weak reference into a strong variable.
13805 // Although this code can still have problems:
13806 // id x = self.weakProp;
13807 // id y = self.weakProp;
13808 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13809 // paths through the function. This should be revisited if
13810 // -Wrepeated-use-of-weak is made flow-sensitive.
13811 // For ObjCWeak only, we do not warn if the assign is to a non-weak
13812 // variable, which will be valid for the current autorelease scope.
13813 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13814 RHS.get()->getBeginLoc()))
13816
13817 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13818 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13819 }
13820 }
13821 } else {
13822 // Compound assignment "x += y"
13823 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13824 }
13825
13826 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
13828 return QualType();
13829
13830 CheckForNullPointerDereference(*this, LHSExpr);
13831
13832 AssignedEntity AE{LHSExpr};
13833 checkAssignmentLifetime(*this, AE, RHS.get());
13834
13835 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13836 if (CompoundType.isNull()) {
13837 // C++2a [expr.ass]p5:
13838 // A simple-assignment whose left operand is of a volatile-qualified
13839 // type is deprecated unless the assignment is either a discarded-value
13840 // expression or an unevaluated operand
13841 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13842 }
13843 }
13844
13845 // C11 6.5.16p3: The type of an assignment expression is the type of the
13846 // left operand would have after lvalue conversion.
13847 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13848 // qualified type, the value has the unqualified version of the type of the
13849 // lvalue; additionally, if the lvalue has atomic type, the value has the
13850 // non-atomic version of the type of the lvalue.
13851 // C++ 5.17p1: the type of the assignment expression is that of its left
13852 // operand.
13853 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13854}
13855
13856// Scenarios to ignore if expression E is:
13857// 1. an explicit cast expression into void
13858// 2. a function call expression that returns void
13859static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
13860 E = E->IgnoreParens();
13861
13862 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13863 if (CE->getCastKind() == CK_ToVoid) {
13864 return true;
13865 }
13866
13867 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13868 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13869 CE->getSubExpr()->getType()->isDependentType()) {
13870 return true;
13871 }
13872 }
13873
13874 if (const auto *CE = dyn_cast<CallExpr>(E))
13875 return CE->getCallReturnType(Context)->isVoidType();
13876 return false;
13877}
13878
13880 // No warnings in macros
13881 if (Loc.isMacroID())
13882 return;
13883
13884 // Don't warn in template instantiations.
13886 return;
13887
13888 // Scope isn't fine-grained enough to explicitly list the specific cases, so
13889 // instead, skip more than needed, then call back into here with the
13890 // CommaVisitor in SemaStmt.cpp.
13891 // The listed locations are the initialization and increment portions
13892 // of a for loop. The additional checks are on the condition of
13893 // if statements, do/while loops, and for loops.
13894 // Differences in scope flags for C89 mode requires the extra logic.
13895 const unsigned ForIncrementFlags =
13896 getLangOpts().C99 || getLangOpts().CPlusPlus
13899 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13900 const unsigned ScopeFlags = getCurScope()->getFlags();
13901 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13902 (ScopeFlags & ForInitFlags) == ForInitFlags)
13903 return;
13904
13905 // If there are multiple comma operators used together, get the RHS of the
13906 // of the comma operator as the LHS.
13907 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13908 if (BO->getOpcode() != BO_Comma)
13909 break;
13910 LHS = BO->getRHS();
13911 }
13912
13913 // Only allow some expressions on LHS to not warn.
13914 if (IgnoreCommaOperand(LHS, Context))
13915 return;
13916
13917 Diag(Loc, diag::warn_comma_operator);
13918 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13919 << LHS->getSourceRange()
13921 LangOpts.CPlusPlus ? "static_cast<void>("
13922 : "(void)(")
13924 ")");
13925}
13926
13927// C99 6.5.17
13930 LHS = S.CheckPlaceholderExpr(LHS.get());
13931 RHS = S.CheckPlaceholderExpr(RHS.get());
13932 if (LHS.isInvalid() || RHS.isInvalid())
13933 return QualType();
13934
13935 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13936 // operands, but not unary promotions.
13937 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13938
13939 // So we treat the LHS as a ignored value, and in C++ we allow the
13940 // containing site to determine what should be done with the RHS.
13941 LHS = S.IgnoredValueConversions(LHS.get());
13942 if (LHS.isInvalid())
13943 return QualType();
13944
13945 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13946
13947 if (!S.getLangOpts().CPlusPlus) {
13949 if (RHS.isInvalid())
13950 return QualType();
13951 if (!RHS.get()->getType()->isVoidType())
13952 S.RequireCompleteType(Loc, RHS.get()->getType(),
13953 diag::err_incomplete_type);
13954 }
13955
13956 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13957 S.DiagnoseCommaOperator(LHS.get(), Loc);
13958
13959 return RHS.get()->getType();
13960}
13961
13962/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13963/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13965 ExprValueKind &VK,
13966 ExprObjectKind &OK,
13967 SourceLocation OpLoc, bool IsInc,
13968 bool IsPrefix) {
13969 QualType ResType = Op->getType();
13970 // Atomic types can be used for increment / decrement where the non-atomic
13971 // versions can, so ignore the _Atomic() specifier for the purpose of
13972 // checking.
13973 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13974 ResType = ResAtomicType->getValueType();
13975
13976 assert(!ResType.isNull() && "no type for increment/decrement expression");
13977
13978 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13979 // Decrement of bool is not allowed.
13980 if (!IsInc) {
13981 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13982 return QualType();
13983 }
13984 // Increment of bool sets it to true, but is deprecated.
13985 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13986 : diag::warn_increment_bool)
13987 << Op->getSourceRange();
13988 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
13989 // Error on enum increments and decrements in C++ mode
13990 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
13991 return QualType();
13992 } else if (ResType->isRealType()) {
13993 // OK!
13994 } else if (ResType->isPointerType()) {
13995 // C99 6.5.2.4p2, 6.5.6p2
13996 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
13997 return QualType();
13998 } else if (ResType->isObjCObjectPointerType()) {
13999 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14000 // Otherwise, we just need a complete type.
14001 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14002 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14003 return QualType();
14004 } else if (ResType->isAnyComplexType()) {
14005 // C99 does not support ++/-- on complex types, we allow as an extension.
14006 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14007 : diag::ext_c2y_increment_complex)
14008 << IsInc << Op->getSourceRange();
14009 } else if (ResType->isPlaceholderType()) {
14011 if (PR.isInvalid()) return QualType();
14012 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14013 IsInc, IsPrefix);
14014 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14015 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14016 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14017 (ResType->castAs<VectorType>()->getVectorKind() !=
14019 // The z vector extensions allow ++ and -- for non-bool vectors.
14020 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14021 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14022 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14023 } else {
14024 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14025 << ResType << int(IsInc) << Op->getSourceRange();
14026 return QualType();
14027 }
14028 // At this point, we know we have a real, complex or pointer type.
14029 // Now make sure the operand is a modifiable lvalue.
14030 if (CheckForModifiableLvalue(Op, OpLoc, S))
14031 return QualType();
14032 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14033 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14034 // An operand with volatile-qualified type is deprecated
14035 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14036 << IsInc << ResType;
14037 }
14038 // In C++, a prefix increment is the same type as the operand. Otherwise
14039 // (in C or with postfix), the increment is the unqualified type of the
14040 // operand.
14041 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14042 VK = VK_LValue;
14043 OK = Op->getObjectKind();
14044 return ResType;
14045 } else {
14046 VK = VK_PRValue;
14047 return ResType.getUnqualifiedType();
14048 }
14049}
14050
14051/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14052/// This routine allows us to typecheck complex/recursive expressions
14053/// where the declaration is needed for type checking. We only need to
14054/// handle cases when the expression references a function designator
14055/// or is an lvalue. Here are some examples:
14056/// - &(x) => x
14057/// - &*****f => f for f a function designator.
14058/// - &s.xx => s
14059/// - &s.zz[1].yy -> s, if zz is an array
14060/// - *(x + 1) -> x, if x is an array
14061/// - &"123"[2] -> 0
14062/// - & __real__ x -> x
14063///
14064/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14065/// members.
14067 switch (E->getStmtClass()) {
14068 case Stmt::DeclRefExprClass:
14069 return cast<DeclRefExpr>(E)->getDecl();
14070 case Stmt::MemberExprClass:
14071 // If this is an arrow operator, the address is an offset from
14072 // the base's value, so the object the base refers to is
14073 // irrelevant.
14074 if (cast<MemberExpr>(E)->isArrow())
14075 return nullptr;
14076 // Otherwise, the expression refers to a part of the base
14077 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14078 case Stmt::ArraySubscriptExprClass: {
14079 // FIXME: This code shouldn't be necessary! We should catch the implicit
14080 // promotion of register arrays earlier.
14081 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14082 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14083 if (ICE->getSubExpr()->getType()->isArrayType())
14084 return getPrimaryDecl(ICE->getSubExpr());
14085 }
14086 return nullptr;
14087 }
14088 case Stmt::UnaryOperatorClass: {
14089 UnaryOperator *UO = cast<UnaryOperator>(E);
14090
14091 switch(UO->getOpcode()) {
14092 case UO_Real:
14093 case UO_Imag:
14094 case UO_Extension:
14095 return getPrimaryDecl(UO->getSubExpr());
14096 default:
14097 return nullptr;
14098 }
14099 }
14100 case Stmt::ParenExprClass:
14101 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14102 case Stmt::ImplicitCastExprClass:
14103 // If the result of an implicit cast is an l-value, we care about
14104 // the sub-expression; otherwise, the result here doesn't matter.
14105 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14106 case Stmt::CXXUuidofExprClass:
14107 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14108 default:
14109 return nullptr;
14110 }
14111}
14112
14113namespace {
14114enum {
14115 AO_Bit_Field = 0,
14116 AO_Vector_Element = 1,
14117 AO_Property_Expansion = 2,
14118 AO_Register_Variable = 3,
14119 AO_Matrix_Element = 4,
14120 AO_No_Error = 5
14121};
14122}
14123/// Diagnose invalid operand for address of operations.
14124///
14125/// \param Type The type of operand which cannot have its address taken.
14127 Expr *E, unsigned Type) {
14128 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14129}
14130
14132 const Expr *Op,
14133 const CXXMethodDecl *MD) {
14134 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14135
14136 if (Op != DRE)
14137 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14138 << Op->getSourceRange();
14139
14140 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14141 if (isa<CXXDestructorDecl>(MD))
14142 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14143 << DRE->getSourceRange();
14144
14145 if (DRE->getQualifier())
14146 return false;
14147
14148 if (MD->getParent()->getName().empty())
14149 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14150 << DRE->getSourceRange();
14151
14152 SmallString<32> Str;
14153 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14154 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14155 << DRE->getSourceRange()
14156 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14157}
14158
14160 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14161 if (PTy->getKind() == BuiltinType::Overload) {
14162 Expr *E = OrigOp.get()->IgnoreParens();
14163 if (!isa<OverloadExpr>(E)) {
14164 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14165 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14166 << OrigOp.get()->getSourceRange();
14167 return QualType();
14168 }
14169
14170 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14171 if (isa<UnresolvedMemberExpr>(Ovl))
14173 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14174 << OrigOp.get()->getSourceRange();
14175 return QualType();
14176 }
14177
14178 return Context.OverloadTy;
14179 }
14180
14181 if (PTy->getKind() == BuiltinType::UnknownAny)
14182 return Context.UnknownAnyTy;
14183
14184 if (PTy->getKind() == BuiltinType::BoundMember) {
14185 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14186 << OrigOp.get()->getSourceRange();
14187 return QualType();
14188 }
14189
14190 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14191 if (OrigOp.isInvalid()) return QualType();
14192 }
14193
14194 if (OrigOp.get()->isTypeDependent())
14195 return Context.DependentTy;
14196
14197 assert(!OrigOp.get()->hasPlaceholderType());
14198
14199 // Make sure to ignore parentheses in subsequent checks
14200 Expr *op = OrigOp.get()->IgnoreParens();
14201
14202 // In OpenCL captures for blocks called as lambda functions
14203 // are located in the private address space. Blocks used in
14204 // enqueue_kernel can be located in a different address space
14205 // depending on a vendor implementation. Thus preventing
14206 // taking an address of the capture to avoid invalid AS casts.
14207 if (LangOpts.OpenCL) {
14208 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14209 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14210 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14211 return QualType();
14212 }
14213 }
14214
14215 if (getLangOpts().C99) {
14216 // Implement C99-only parts of addressof rules.
14217 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14218 if (uOp->getOpcode() == UO_Deref)
14219 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14220 // (assuming the deref expression is valid).
14221 return uOp->getSubExpr()->getType();
14222 }
14223 // Technically, there should be a check for array subscript
14224 // expressions here, but the result of one is always an lvalue anyway.
14225 }
14226 ValueDecl *dcl = getPrimaryDecl(op);
14227
14228 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14229 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14230 op->getBeginLoc()))
14231 return QualType();
14232
14234 unsigned AddressOfError = AO_No_Error;
14235
14236 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14237 bool sfinae = (bool)isSFINAEContext();
14238 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14239 : diag::ext_typecheck_addrof_temporary)
14240 << op->getType() << op->getSourceRange();
14241 if (sfinae)
14242 return QualType();
14243 // Materialize the temporary as an lvalue so that we can take its address.
14244 OrigOp = op =
14245 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14246 } else if (isa<ObjCSelectorExpr>(op)) {
14247 return Context.getPointerType(op->getType());
14248 } else if (lval == Expr::LV_MemberFunction) {
14249 // If it's an instance method, make a member pointer.
14250 // The expression must have exactly the form &A::foo.
14251
14252 // If the underlying expression isn't a decl ref, give up.
14253 if (!isa<DeclRefExpr>(op)) {
14254 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14255 << OrigOp.get()->getSourceRange();
14256 return QualType();
14257 }
14258 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14259 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14260
14261 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14262
14265
14266 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14267 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14268 // When pointer authentication is enabled, argument and return types of
14269 // vitual member functions must be complete. This is because vitrual
14270 // member function pointers are implemented using virtual dispatch
14271 // thunks and the thunks cannot be emitted if the argument or return
14272 // types are incomplete.
14273 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
14274 SourceLocation DeclRefLoc,
14275 SourceLocation RetArgTypeLoc) {
14276 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
14277 Diag(DeclRefLoc,
14278 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
14279 Diag(RetArgTypeLoc,
14280 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
14281 << T;
14282 return true;
14283 }
14284 return false;
14285 };
14286 QualType RetTy = MD->getReturnType();
14287 bool IsIncomplete =
14288 !RetTy->isVoidType() &&
14289 ReturnOrParamTypeIsIncomplete(
14290 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
14291 for (auto *PVD : MD->parameters())
14292 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
14293 PVD->getBeginLoc());
14294 if (IsIncomplete)
14295 return QualType();
14296 }
14297
14298 // Under the MS ABI, lock down the inheritance model now.
14300 (void)isCompleteType(OpLoc, MPTy);
14301 return MPTy;
14302 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14303 // C99 6.5.3.2p1
14304 // The operand must be either an l-value or a function designator
14305 if (!op->getType()->isFunctionType()) {
14306 // Use a special diagnostic for loads from property references.
14307 if (isa<PseudoObjectExpr>(op)) {
14308 AddressOfError = AO_Property_Expansion;
14309 } else {
14310 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14311 << op->getType() << op->getSourceRange();
14312 return QualType();
14313 }
14314 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14315 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14316 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14317 }
14318
14319 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14320 // The operand cannot be a bit-field
14321 AddressOfError = AO_Bit_Field;
14322 } else if (op->getObjectKind() == OK_VectorComponent) {
14323 // The operand cannot be an element of a vector
14324 AddressOfError = AO_Vector_Element;
14325 } else if (op->getObjectKind() == OK_MatrixComponent) {
14326 // The operand cannot be an element of a matrix.
14327 AddressOfError = AO_Matrix_Element;
14328 } else if (dcl) { // C99 6.5.3.2p1
14329 // We have an lvalue with a decl. Make sure the decl is not declared
14330 // with the register storage-class specifier.
14331 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14332 // in C++ it is not error to take address of a register
14333 // variable (c++03 7.1.1P3)
14334 if (vd->getStorageClass() == SC_Register &&
14336 AddressOfError = AO_Register_Variable;
14337 }
14338 } else if (isa<MSPropertyDecl>(dcl)) {
14339 AddressOfError = AO_Property_Expansion;
14340 } else if (isa<FunctionTemplateDecl>(dcl)) {
14341 return Context.OverloadTy;
14342 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14343 // Okay: we can take the address of a field.
14344 // Could be a pointer to member, though, if there is an explicit
14345 // scope qualifier for the class.
14346
14347 // [C++26] [expr.prim.id.general]
14348 // If an id-expression E denotes a non-static non-type member
14349 // of some class C [...] and if E is a qualified-id, E is
14350 // not the un-parenthesized operand of the unary & operator [...]
14351 // the id-expression is transformed into a class member access expression.
14352 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
14353 !isa<ParenExpr>(OrigOp.get())) {
14354 DeclContext *Ctx = dcl->getDeclContext();
14355 if (Ctx && Ctx->isRecord()) {
14356 if (dcl->getType()->isReferenceType()) {
14357 Diag(OpLoc,
14358 diag::err_cannot_form_pointer_to_member_of_reference_type)
14359 << dcl->getDeclName() << dcl->getType();
14360 return QualType();
14361 }
14362
14363 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14364 Ctx = Ctx->getParent();
14365
14367 op->getType(),
14368 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14369 // Under the MS ABI, lock down the inheritance model now.
14371 (void)isCompleteType(OpLoc, MPTy);
14372 return MPTy;
14373 }
14374 }
14377 llvm_unreachable("Unknown/unexpected decl type");
14378 }
14379
14380 if (AddressOfError != AO_No_Error) {
14381 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14382 return QualType();
14383 }
14384
14385 if (lval == Expr::LV_IncompleteVoidType) {
14386 // Taking the address of a void variable is technically illegal, but we
14387 // allow it in cases which are otherwise valid.
14388 // Example: "extern void x; void* y = &x;".
14389 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14390 }
14391
14392 // If the operand has type "type", the result has type "pointer to type".
14393 if (op->getType()->isObjCObjectType())
14395
14396 // Cannot take the address of WebAssembly references or tables.
14397 if (Context.getTargetInfo().getTriple().isWasm()) {
14398 QualType OpTy = op->getType();
14399 if (OpTy.isWebAssemblyReferenceType()) {
14400 Diag(OpLoc, diag::err_wasm_ca_reference)
14401 << 1 << OrigOp.get()->getSourceRange();
14402 return QualType();
14403 }
14404 if (OpTy->isWebAssemblyTableType()) {
14405 Diag(OpLoc, diag::err_wasm_table_pr)
14406 << 1 << OrigOp.get()->getSourceRange();
14407 return QualType();
14408 }
14409 }
14410
14411 CheckAddressOfPackedMember(op);
14412
14413 return Context.getPointerType(op->getType());
14414}
14415
14416static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14417 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14418 if (!DRE)
14419 return;
14420 const Decl *D = DRE->getDecl();
14421 if (!D)
14422 return;
14423 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14424 if (!Param)
14425 return;
14426 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14427 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14428 return;
14429 if (FunctionScopeInfo *FD = S.getCurFunction())
14430 FD->ModifiedNonNullParams.insert(Param);
14431}
14432
14433/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14435 SourceLocation OpLoc,
14436 bool IsAfterAmp = false) {
14437 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14438 if (ConvResult.isInvalid())
14439 return QualType();
14440 Op = ConvResult.get();
14441 QualType OpTy = Op->getType();
14443
14444 if (isa<CXXReinterpretCastExpr>(Op)) {
14445 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14446 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14447 Op->getSourceRange());
14448 }
14449
14450 if (const PointerType *PT = OpTy->getAs<PointerType>())
14451 {
14452 Result = PT->getPointeeType();
14453 }
14454 else if (const ObjCObjectPointerType *OPT =
14456 Result = OPT->getPointeeType();
14457 else {
14459 if (PR.isInvalid()) return QualType();
14460 if (PR.get() != Op)
14461 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14462 }
14463
14464 if (Result.isNull()) {
14465 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14466 << OpTy << Op->getSourceRange();
14467 return QualType();
14468 }
14469
14470 if (Result->isVoidType()) {
14471 // C++ [expr.unary.op]p1:
14472 // [...] the expression to which [the unary * operator] is applied shall
14473 // be a pointer to an object type, or a pointer to a function type
14474 LangOptions LO = S.getLangOpts();
14475 if (LO.CPlusPlus)
14476 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
14477 << OpTy << Op->getSourceRange();
14478 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14479 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14480 << OpTy << Op->getSourceRange();
14481 }
14482
14483 // Dereferences are usually l-values...
14484 VK = VK_LValue;
14485
14486 // ...except that certain expressions are never l-values in C.
14487 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14488 VK = VK_PRValue;
14489
14490 return Result;
14491}
14492
14493BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14495 switch (Kind) {
14496 default: llvm_unreachable("Unknown binop!");
14497 case tok::periodstar: Opc = BO_PtrMemD; break;
14498 case tok::arrowstar: Opc = BO_PtrMemI; break;
14499 case tok::star: Opc = BO_Mul; break;
14500 case tok::slash: Opc = BO_Div; break;
14501 case tok::percent: Opc = BO_Rem; break;
14502 case tok::plus: Opc = BO_Add; break;
14503 case tok::minus: Opc = BO_Sub; break;
14504 case tok::lessless: Opc = BO_Shl; break;
14505 case tok::greatergreater: Opc = BO_Shr; break;
14506 case tok::lessequal: Opc = BO_LE; break;
14507 case tok::less: Opc = BO_LT; break;
14508 case tok::greaterequal: Opc = BO_GE; break;
14509 case tok::greater: Opc = BO_GT; break;
14510 case tok::exclaimequal: Opc = BO_NE; break;
14511 case tok::equalequal: Opc = BO_EQ; break;
14512 case tok::spaceship: Opc = BO_Cmp; break;
14513 case tok::amp: Opc = BO_And; break;
14514 case tok::caret: Opc = BO_Xor; break;
14515 case tok::pipe: Opc = BO_Or; break;
14516 case tok::ampamp: Opc = BO_LAnd; break;
14517 case tok::pipepipe: Opc = BO_LOr; break;
14518 case tok::equal: Opc = BO_Assign; break;
14519 case tok::starequal: Opc = BO_MulAssign; break;
14520 case tok::slashequal: Opc = BO_DivAssign; break;
14521 case tok::percentequal: Opc = BO_RemAssign; break;
14522 case tok::plusequal: Opc = BO_AddAssign; break;
14523 case tok::minusequal: Opc = BO_SubAssign; break;
14524 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14525 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14526 case tok::ampequal: Opc = BO_AndAssign; break;
14527 case tok::caretequal: Opc = BO_XorAssign; break;
14528 case tok::pipeequal: Opc = BO_OrAssign; break;
14529 case tok::comma: Opc = BO_Comma; break;
14530 }
14531 return Opc;
14532}
14533
14535 tok::TokenKind Kind) {
14537 switch (Kind) {
14538 default: llvm_unreachable("Unknown unary op!");
14539 case tok::plusplus: Opc = UO_PreInc; break;
14540 case tok::minusminus: Opc = UO_PreDec; break;
14541 case tok::amp: Opc = UO_AddrOf; break;
14542 case tok::star: Opc = UO_Deref; break;
14543 case tok::plus: Opc = UO_Plus; break;
14544 case tok::minus: Opc = UO_Minus; break;
14545 case tok::tilde: Opc = UO_Not; break;
14546 case tok::exclaim: Opc = UO_LNot; break;
14547 case tok::kw___real: Opc = UO_Real; break;
14548 case tok::kw___imag: Opc = UO_Imag; break;
14549 case tok::kw___extension__: Opc = UO_Extension; break;
14550 }
14551 return Opc;
14552}
14553
14554const FieldDecl *
14556 // Explore the case for adding 'this->' to the LHS of a self assignment, very
14557 // common for setters.
14558 // struct A {
14559 // int X;
14560 // -void setX(int X) { X = X; }
14561 // +void setX(int X) { this->X = X; }
14562 // };
14563
14564 // Only consider parameters for self assignment fixes.
14565 if (!isa<ParmVarDecl>(SelfAssigned))
14566 return nullptr;
14567 const auto *Method =
14568 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14569 if (!Method)
14570 return nullptr;
14571
14572 const CXXRecordDecl *Parent = Method->getParent();
14573 // In theory this is fixable if the lambda explicitly captures this, but
14574 // that's added complexity that's rarely going to be used.
14575 if (Parent->isLambda())
14576 return nullptr;
14577
14578 // FIXME: Use an actual Lookup operation instead of just traversing fields
14579 // in order to get base class fields.
14580 auto Field =
14581 llvm::find_if(Parent->fields(),
14582 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14583 return F->getDeclName() == Name;
14584 });
14585 return (Field != Parent->field_end()) ? *Field : nullptr;
14586}
14587
14588/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14589/// This warning suppressed in the event of macro expansions.
14590static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14591 SourceLocation OpLoc, bool IsBuiltin) {
14593 return;
14594 if (S.isUnevaluatedContext())
14595 return;
14596 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14597 return;
14598 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14599 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14600 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14601 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14602 if (!LHSDeclRef || !RHSDeclRef ||
14603 LHSDeclRef->getLocation().isMacroID() ||
14604 RHSDeclRef->getLocation().isMacroID())
14605 return;
14606 const ValueDecl *LHSDecl =
14607 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14608 const ValueDecl *RHSDecl =
14609 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14610 if (LHSDecl != RHSDecl)
14611 return;
14612 if (LHSDecl->getType().isVolatileQualified())
14613 return;
14614 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14615 if (RefTy->getPointeeType().isVolatileQualified())
14616 return;
14617
14618 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14619 : diag::warn_self_assignment_overloaded)
14620 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14621 << RHSExpr->getSourceRange();
14622 if (const FieldDecl *SelfAssignField =
14624 Diag << 1 << SelfAssignField
14625 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14626 else
14627 Diag << 0;
14628}
14629
14630/// Check if a bitwise-& is performed on an Objective-C pointer. This
14631/// is usually indicative of introspection within the Objective-C pointer.
14633 SourceLocation OpLoc) {
14634 if (!S.getLangOpts().ObjC)
14635 return;
14636
14637 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14638 const Expr *LHS = L.get();
14639 const Expr *RHS = R.get();
14640
14642 ObjCPointerExpr = LHS;
14643 OtherExpr = RHS;
14644 }
14645 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14646 ObjCPointerExpr = RHS;
14647 OtherExpr = LHS;
14648 }
14649
14650 // This warning is deliberately made very specific to reduce false
14651 // positives with logic that uses '&' for hashing. This logic mainly
14652 // looks for code trying to introspect into tagged pointers, which
14653 // code should generally never do.
14654 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14655 unsigned Diag = diag::warn_objc_pointer_masking;
14656 // Determine if we are introspecting the result of performSelectorXXX.
14657 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14658 // Special case messages to -performSelector and friends, which
14659 // can return non-pointer values boxed in a pointer value.
14660 // Some clients may wish to silence warnings in this subcase.
14661 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14662 Selector S = ME->getSelector();
14663 StringRef SelArg0 = S.getNameForSlot(0);
14664 if (SelArg0.starts_with("performSelector"))
14665 Diag = diag::warn_objc_pointer_masking_performSelector;
14666 }
14667
14668 S.Diag(OpLoc, Diag)
14669 << ObjCPointerExpr->getSourceRange();
14670 }
14671}
14672
14674 if (!E)
14675 return nullptr;
14676 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14677 return DRE->getDecl();
14678 if (auto *ME = dyn_cast<MemberExpr>(E))
14679 return ME->getMemberDecl();
14680 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14681 return IRE->getDecl();
14682 return nullptr;
14683}
14684
14685// This helper function promotes a binary operator's operands (which are of a
14686// half vector type) to a vector of floats and then truncates the result to
14687// a vector of either half or short.
14689 BinaryOperatorKind Opc, QualType ResultTy,
14691 bool IsCompAssign, SourceLocation OpLoc,
14692 FPOptionsOverride FPFeatures) {
14693 auto &Context = S.getASTContext();
14694 assert((isVector(ResultTy, Context.HalfTy) ||
14695 isVector(ResultTy, Context.ShortTy)) &&
14696 "Result must be a vector of half or short");
14697 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14698 isVector(RHS.get()->getType(), Context.HalfTy) &&
14699 "both operands expected to be a half vector");
14700
14701 RHS = convertVector(RHS.get(), Context.FloatTy, S);
14702 QualType BinOpResTy = RHS.get()->getType();
14703
14704 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14705 // change BinOpResTy to a vector of ints.
14706 if (isVector(ResultTy, Context.ShortTy))
14707 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14708
14709 if (IsCompAssign)
14710 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14711 ResultTy, VK, OK, OpLoc, FPFeatures,
14712 BinOpResTy, BinOpResTy);
14713
14714 LHS = convertVector(LHS.get(), Context.FloatTy, S);
14715 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14716 BinOpResTy, VK, OK, OpLoc, FPFeatures);
14717 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14718}
14719
14720static std::pair<ExprResult, ExprResult>
14722 Expr *RHSExpr) {
14723 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14724 if (!S.Context.isDependenceAllowed()) {
14725 // C cannot handle TypoExpr nodes on either side of a binop because it
14726 // doesn't handle dependent types properly, so make sure any TypoExprs have
14727 // been dealt with before checking the operands.
14728 LHS = S.CorrectDelayedTyposInExpr(LHS);
14730 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14731 [Opc, LHS](Expr *E) {
14732 if (Opc != BO_Assign)
14733 return ExprResult(E);
14734 // Avoid correcting the RHS to the same Expr as the LHS.
14735 Decl *D = getDeclFromExpr(E);
14736 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14737 });
14738 }
14739 return std::make_pair(LHS, RHS);
14740}
14741
14742/// Returns true if conversion between vectors of halfs and vectors of floats
14743/// is needed.
14744static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14745 Expr *E0, Expr *E1 = nullptr) {
14746 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14748 return false;
14749
14750 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14751 QualType Ty = E->IgnoreImplicit()->getType();
14752
14753 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14754 // to vectors of floats. Although the element type of the vectors is __fp16,
14755 // the vectors shouldn't be treated as storage-only types. See the
14756 // discussion here: https://reviews.llvm.org/rG825235c140e7
14757 if (const VectorType *VT = Ty->getAs<VectorType>()) {
14758 if (VT->getVectorKind() == VectorKind::Neon)
14759 return false;
14760 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14761 }
14762 return false;
14763 };
14764
14765 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14766}
14767
14770 Expr *LHSExpr, Expr *RHSExpr) {
14771 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14772 // The syntax only allows initializer lists on the RHS of assignment,
14773 // so we don't need to worry about accepting invalid code for
14774 // non-assignment operators.
14775 // C++11 5.17p9:
14776 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14777 // of x = {} is x = T().
14779 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14780 InitializedEntity Entity =
14782 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14783 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14784 if (Init.isInvalid())
14785 return Init;
14786 RHSExpr = Init.get();
14787 }
14788
14789 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14790 QualType ResultTy; // Result type of the binary operator.
14791 // The following two variables are used for compound assignment operators
14792 QualType CompLHSTy; // Type of LHS after promotions for computation
14793 QualType CompResultTy; // Type of computation result
14796 bool ConvertHalfVec = false;
14797
14798 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14799 if (!LHS.isUsable() || !RHS.isUsable())
14800 return ExprError();
14801
14802 if (getLangOpts().OpenCL) {
14803 QualType LHSTy = LHSExpr->getType();
14804 QualType RHSTy = RHSExpr->getType();
14805 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14806 // the ATOMIC_VAR_INIT macro.
14807 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14808 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14809 if (BO_Assign == Opc)
14810 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14811 else
14812 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14813 return ExprError();
14814 }
14815
14816 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14817 // only with a builtin functions and therefore should be disallowed here.
14818 if (LHSTy->isImageType() || RHSTy->isImageType() ||
14819 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14820 LHSTy->isPipeType() || RHSTy->isPipeType() ||
14821 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14822 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14823 return ExprError();
14824 }
14825 }
14826
14827 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14828 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14829
14830 switch (Opc) {
14831 case BO_Assign:
14832 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
14833 if (getLangOpts().CPlusPlus &&
14834 LHS.get()->getObjectKind() != OK_ObjCProperty) {
14835 VK = LHS.get()->getValueKind();
14836 OK = LHS.get()->getObjectKind();
14837 }
14838 if (!ResultTy.isNull()) {
14839 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14840 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14841
14842 // Avoid copying a block to the heap if the block is assigned to a local
14843 // auto variable that is declared in the same scope as the block. This
14844 // optimization is unsafe if the local variable is declared in an outer
14845 // scope. For example:
14846 //
14847 // BlockTy b;
14848 // {
14849 // b = ^{...};
14850 // }
14851 // // It is unsafe to invoke the block here if it wasn't copied to the
14852 // // heap.
14853 // b();
14854
14855 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14856 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14857 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14858 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14859 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14860
14862 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14864 }
14865 RecordModifiableNonNullParam(*this, LHS.get());
14866 break;
14867 case BO_PtrMemD:
14868 case BO_PtrMemI:
14869 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14870 Opc == BO_PtrMemI);
14871 break;
14872 case BO_Mul:
14873 case BO_Div:
14874 ConvertHalfVec = true;
14875 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14876 Opc == BO_Div);
14877 break;
14878 case BO_Rem:
14879 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14880 break;
14881 case BO_Add:
14882 ConvertHalfVec = true;
14883 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14884 break;
14885 case BO_Sub:
14886 ConvertHalfVec = true;
14887 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14888 break;
14889 case BO_Shl:
14890 case BO_Shr:
14891 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14892 break;
14893 case BO_LE:
14894 case BO_LT:
14895 case BO_GE:
14896 case BO_GT:
14897 ConvertHalfVec = true;
14898 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14899
14900 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
14901 BI && BI->isComparisonOp())
14902 Diag(OpLoc, diag::warn_consecutive_comparison);
14903
14904 break;
14905 case BO_EQ:
14906 case BO_NE:
14907 ConvertHalfVec = true;
14908 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14909 break;
14910 case BO_Cmp:
14911 ConvertHalfVec = true;
14912 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14913 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14914 break;
14915 case BO_And:
14916 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14917 [[fallthrough]];
14918 case BO_Xor:
14919 case BO_Or:
14920 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14921 break;
14922 case BO_LAnd:
14923 case BO_LOr:
14924 ConvertHalfVec = true;
14925 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14926 break;
14927 case BO_MulAssign:
14928 case BO_DivAssign:
14929 ConvertHalfVec = true;
14930 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14931 Opc == BO_DivAssign);
14932 CompLHSTy = CompResultTy;
14933 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14934 ResultTy =
14935 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14936 break;
14937 case BO_RemAssign:
14938 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14939 CompLHSTy = CompResultTy;
14940 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14941 ResultTy =
14942 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14943 break;
14944 case BO_AddAssign:
14945 ConvertHalfVec = true;
14946 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14947 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14948 ResultTy =
14949 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14950 break;
14951 case BO_SubAssign:
14952 ConvertHalfVec = true;
14953 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14954 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14955 ResultTy =
14956 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14957 break;
14958 case BO_ShlAssign:
14959 case BO_ShrAssign:
14960 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14961 CompLHSTy = CompResultTy;
14962 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14963 ResultTy =
14964 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14965 break;
14966 case BO_AndAssign:
14967 case BO_OrAssign: // fallthrough
14968 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14969 [[fallthrough]];
14970 case BO_XorAssign:
14971 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14972 CompLHSTy = CompResultTy;
14973 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14974 ResultTy =
14975 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14976 break;
14977 case BO_Comma:
14978 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14979 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14980 VK = RHS.get()->getValueKind();
14981 OK = RHS.get()->getObjectKind();
14982 }
14983 break;
14984 }
14985 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14986 return ExprError();
14987
14988 // Some of the binary operations require promoting operands of half vector to
14989 // float vectors and truncating the result back to half vector. For now, we do
14990 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
14991 // arm64).
14992 assert(
14993 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
14994 isVector(LHS.get()->getType(), Context.HalfTy)) &&
14995 "both sides are half vectors or neither sides are");
14996 ConvertHalfVec =
14997 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
14998
14999 // Check for array bounds violations for both sides of the BinaryOperator
15000 CheckArrayAccess(LHS.get());
15001 CheckArrayAccess(RHS.get());
15002
15003 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15004 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15005 &Context.Idents.get("object_setClass"),
15007 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15008 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15009 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15011 "object_setClass(")
15012 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15013 ",")
15014 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15015 }
15016 else
15017 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15018 }
15019 else if (const ObjCIvarRefExpr *OIRE =
15020 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15021 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15022
15023 // Opc is not a compound assignment if CompResultTy is null.
15024 if (CompResultTy.isNull()) {
15025 if (ConvertHalfVec)
15026 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15027 OpLoc, CurFPFeatureOverrides());
15028 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15029 VK, OK, OpLoc, CurFPFeatureOverrides());
15030 }
15031
15032 // Handle compound assignments.
15033 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15035 VK = VK_LValue;
15036 OK = LHS.get()->getObjectKind();
15037 }
15038
15039 // The LHS is not converted to the result type for fixed-point compound
15040 // assignment as the common type is computed on demand. Reset the CompLHSTy
15041 // to the LHS type we would have gotten after unary conversions.
15042 if (CompResultTy->isFixedPointType())
15043 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15044
15045 if (ConvertHalfVec)
15046 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15047 OpLoc, CurFPFeatureOverrides());
15048
15050 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15051 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15052}
15053
15054/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15055/// operators are mixed in a way that suggests that the programmer forgot that
15056/// comparison operators have higher precedence. The most typical example of
15057/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15059 SourceLocation OpLoc, Expr *LHSExpr,
15060 Expr *RHSExpr) {
15061 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15062 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15063
15064 // Check that one of the sides is a comparison operator and the other isn't.
15065 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15066 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15067 if (isLeftComp == isRightComp)
15068 return;
15069
15070 // Bitwise operations are sometimes used as eager logical ops.
15071 // Don't diagnose this.
15072 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15073 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15074 if (isLeftBitwise || isRightBitwise)
15075 return;
15076
15077 SourceRange DiagRange = isLeftComp
15078 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15079 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15080 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15081 SourceRange ParensRange =
15082 isLeftComp
15083 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15084 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15085
15086 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15087 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15088 SuggestParentheses(Self, OpLoc,
15089 Self.PDiag(diag::note_precedence_silence) << OpStr,
15090 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15091 SuggestParentheses(Self, OpLoc,
15092 Self.PDiag(diag::note_precedence_bitwise_first)
15094 ParensRange);
15095}
15096
15097/// It accepts a '&&' expr that is inside a '||' one.
15098/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15099/// in parentheses.
15100static void
15102 BinaryOperator *Bop) {
15103 assert(Bop->getOpcode() == BO_LAnd);
15104 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15105 << Bop->getSourceRange() << OpLoc;
15107 Self.PDiag(diag::note_precedence_silence)
15108 << Bop->getOpcodeStr(),
15109 Bop->getSourceRange());
15110}
15111
15112/// Look for '&&' in the left hand of a '||' expr.
15114 Expr *LHSExpr, Expr *RHSExpr) {
15115 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15116 if (Bop->getOpcode() == BO_LAnd) {
15117 // If it's "string_literal && a || b" don't warn since the precedence
15118 // doesn't matter.
15119 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15120 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15121 } else if (Bop->getOpcode() == BO_LOr) {
15122 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15123 // If it's "a || b && string_literal || c" we didn't warn earlier for
15124 // "a || b && string_literal", but warn now.
15125 if (RBop->getOpcode() == BO_LAnd &&
15126 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15127 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15128 }
15129 }
15130 }
15131}
15132
15133/// Look for '&&' in the right hand of a '||' expr.
15135 Expr *LHSExpr, Expr *RHSExpr) {
15136 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15137 if (Bop->getOpcode() == BO_LAnd) {
15138 // If it's "a || b && string_literal" don't warn since the precedence
15139 // doesn't matter.
15140 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15141 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15142 }
15143 }
15144}
15145
15146/// Look for bitwise op in the left or right hand of a bitwise op with
15147/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15148/// the '&' expression in parentheses.
15150 SourceLocation OpLoc, Expr *SubExpr) {
15151 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15152 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15153 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15154 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15155 << Bop->getSourceRange() << OpLoc;
15156 SuggestParentheses(S, Bop->getOperatorLoc(),
15157 S.PDiag(diag::note_precedence_silence)
15158 << Bop->getOpcodeStr(),
15159 Bop->getSourceRange());
15160 }
15161 }
15162}
15163
15165 Expr *SubExpr, StringRef Shift) {
15166 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15167 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15168 StringRef Op = Bop->getOpcodeStr();
15169 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15170 << Bop->getSourceRange() << OpLoc << Shift << Op;
15171 SuggestParentheses(S, Bop->getOperatorLoc(),
15172 S.PDiag(diag::note_precedence_silence) << Op,
15173 Bop->getSourceRange());
15174 }
15175 }
15176}
15177
15179 Expr *LHSExpr, Expr *RHSExpr) {
15180 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15181 if (!OCE)
15182 return;
15183
15184 FunctionDecl *FD = OCE->getDirectCallee();
15185 if (!FD || !FD->isOverloadedOperator())
15186 return;
15187
15189 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15190 return;
15191
15192 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15193 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15194 << (Kind == OO_LessLess);
15196 S.PDiag(diag::note_precedence_silence)
15197 << (Kind == OO_LessLess ? "<<" : ">>"),
15198 OCE->getSourceRange());
15200 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15201 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15202}
15203
15204/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15205/// precedence.
15207 SourceLocation OpLoc, Expr *LHSExpr,
15208 Expr *RHSExpr){
15209 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15211 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15212
15213 // Diagnose "arg1 & arg2 | arg3"
15214 if ((Opc == BO_Or || Opc == BO_Xor) &&
15215 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15216 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15217 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15218 }
15219
15220 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15221 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15222 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15223 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15224 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15225 }
15226
15227 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15228 || Opc == BO_Shr) {
15229 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15230 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15231 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15232 }
15233
15234 // Warn on overloaded shift operators and comparisons, such as:
15235 // cout << 5 == 4;
15237 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15238}
15239
15241 Expr *Operand) {
15242 if (auto *CT = Operand->getType()->getAs<ComplexType>()) {
15243 QualType ElementType = CT->getElementType();
15244 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
15246 if (ElementType->isFloatingType() && IsComplexRangePromoted) {
15247 ASTContext &Ctx = S.getASTContext();
15248 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
15249 const llvm::fltSemantics &ElementTypeSemantics =
15250 Ctx.getFloatTypeSemantics(ElementType);
15251 const llvm::fltSemantics &HigherElementTypeSemantics =
15252 Ctx.getFloatTypeSemantics(HigherElementType);
15253 if (llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
15254 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) {
15255 // Retain the location of the first use of higher precision type.
15258 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
15259 if (Type == HigherElementType) {
15260 Num++;
15261 return;
15262 }
15263 }
15264 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
15265 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
15266 }
15267 }
15268 }
15269}
15270
15272 tok::TokenKind Kind,
15273 Expr *LHSExpr, Expr *RHSExpr) {
15274 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15275 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15276 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15277
15278 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15279 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15280
15281 // Emit warnings if the requested higher precision type equal to the current
15282 // type precision.
15283 if (Kind == tok::TokenKind::slash)
15284 DetectPrecisionLossInComplexDivision(*this, TokLoc, LHSExpr);
15285
15286 BuiltinCountedByRefKind K =
15287 BinaryOperator::isAssignmentOp(Opc) ? AssignmentKind : BinaryExprKind;
15288
15289 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
15290 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
15291
15292 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15293}
15294
15296 UnresolvedSetImpl &Functions) {
15298 if (OverOp != OO_None && OverOp != OO_Equal)
15299 LookupOverloadedOperatorName(OverOp, S, Functions);
15300
15301 // In C++20 onwards, we may have a second operator to look up.
15302 if (getLangOpts().CPlusPlus20) {
15304 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15305 }
15306}
15307
15308/// Build an overloaded binary operator expression in the given scope.
15311 Expr *LHS, Expr *RHS) {
15312 switch (Opc) {
15313 case BO_Assign:
15314 // In the non-overloaded case, we warn about self-assignment (x = x) for
15315 // both simple assignment and certain compound assignments where algebra
15316 // tells us the operation yields a constant result. When the operator is
15317 // overloaded, we can't do the latter because we don't want to assume that
15318 // those algebraic identities still apply; for example, a path-building
15319 // library might use operator/= to append paths. But it's still reasonable
15320 // to assume that simple assignment is just moving/copying values around
15321 // and so self-assignment is likely a bug.
15322 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15323 [[fallthrough]];
15324 case BO_DivAssign:
15325 case BO_RemAssign:
15326 case BO_SubAssign:
15327 case BO_AndAssign:
15328 case BO_OrAssign:
15329 case BO_XorAssign:
15330 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15331 break;
15332 default:
15333 break;
15334 }
15335
15336 // Find all of the overloaded operators visible from this point.
15337 UnresolvedSet<16> Functions;
15338 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15339
15340 // Build the (potentially-overloaded, potentially-dependent)
15341 // binary operation.
15342 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15343}
15344
15347 Expr *LHSExpr, Expr *RHSExpr) {
15348 ExprResult LHS, RHS;
15349 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15350 if (!LHS.isUsable() || !RHS.isUsable())
15351 return ExprError();
15352 LHSExpr = LHS.get();
15353 RHSExpr = RHS.get();
15354
15355 // We want to end up calling one of SemaPseudoObject::checkAssignment
15356 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15357 // both expressions are overloadable or either is type-dependent),
15358 // or CreateBuiltinBinOp (in any other case). We also want to get
15359 // any placeholder types out of the way.
15360
15361 // Handle pseudo-objects in the LHS.
15362 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15363 // Assignments with a pseudo-object l-value need special analysis.
15364 if (pty->getKind() == BuiltinType::PseudoObject &&
15366 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15367
15368 // Don't resolve overloads if the other type is overloadable.
15369 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15370 // We can't actually test that if we still have a placeholder,
15371 // though. Fortunately, none of the exceptions we see in that
15372 // code below are valid when the LHS is an overload set. Note
15373 // that an overload set can be dependently-typed, but it never
15374 // instantiates to having an overloadable type.
15375 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15376 if (resolvedRHS.isInvalid()) return ExprError();
15377 RHSExpr = resolvedRHS.get();
15378
15379 if (RHSExpr->isTypeDependent() ||
15380 RHSExpr->getType()->isOverloadableType())
15381 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15382 }
15383
15384 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15385 // template, diagnose the missing 'template' keyword instead of diagnosing
15386 // an invalid use of a bound member function.
15387 //
15388 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15389 // to C++1z [over.over]/1.4, but we already checked for that case above.
15390 if (Opc == BO_LT && inTemplateInstantiation() &&
15391 (pty->getKind() == BuiltinType::BoundMember ||
15392 pty->getKind() == BuiltinType::Overload)) {
15393 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15394 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15395 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15396 return isa<FunctionTemplateDecl>(ND);
15397 })) {
15398 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15399 : OE->getNameLoc(),
15400 diag::err_template_kw_missing)
15401 << OE->getName().getAsString() << "";
15402 return ExprError();
15403 }
15404 }
15405
15406 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15407 if (LHS.isInvalid()) return ExprError();
15408 LHSExpr = LHS.get();
15409 }
15410
15411 // Handle pseudo-objects in the RHS.
15412 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15413 // An overload in the RHS can potentially be resolved by the type
15414 // being assigned to.
15415 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15416 if (getLangOpts().CPlusPlus &&
15417 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15418 LHSExpr->getType()->isOverloadableType()))
15419 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15420
15421 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15422 }
15423
15424 // Don't resolve overloads if the other type is overloadable.
15425 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15426 LHSExpr->getType()->isOverloadableType())
15427 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15428
15429 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15430 if (!resolvedRHS.isUsable()) return ExprError();
15431 RHSExpr = resolvedRHS.get();
15432 }
15433
15434 if (getLangOpts().CPlusPlus) {
15435 // Otherwise, build an overloaded op if either expression is type-dependent
15436 // or has an overloadable type.
15437 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15438 LHSExpr->getType()->isOverloadableType() ||
15439 RHSExpr->getType()->isOverloadableType())
15440 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15441 }
15442
15443 if (getLangOpts().RecoveryAST &&
15444 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15445 assert(!getLangOpts().CPlusPlus);
15446 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15447 "Should only occur in error-recovery path.");
15449 // C [6.15.16] p3:
15450 // An assignment expression has the value of the left operand after the
15451 // assignment, but is not an lvalue.
15453 Context, LHSExpr, RHSExpr, Opc,
15455 OpLoc, CurFPFeatureOverrides());
15456 QualType ResultType;
15457 switch (Opc) {
15458 case BO_Assign:
15459 ResultType = LHSExpr->getType().getUnqualifiedType();
15460 break;
15461 case BO_LT:
15462 case BO_GT:
15463 case BO_LE:
15464 case BO_GE:
15465 case BO_EQ:
15466 case BO_NE:
15467 case BO_LAnd:
15468 case BO_LOr:
15469 // These operators have a fixed result type regardless of operands.
15470 ResultType = Context.IntTy;
15471 break;
15472 case BO_Comma:
15473 ResultType = RHSExpr->getType();
15474 break;
15475 default:
15476 ResultType = Context.DependentTy;
15477 break;
15478 }
15479 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15480 VK_PRValue, OK_Ordinary, OpLoc,
15482 }
15483
15484 // Build a built-in binary operation.
15485 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15486}
15487
15489 if (T.isNull() || T->isDependentType())
15490 return false;
15491
15492 if (!Ctx.isPromotableIntegerType(T))
15493 return true;
15494
15495 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15496}
15497
15499 UnaryOperatorKind Opc, Expr *InputExpr,
15500 bool IsAfterAmp) {
15501 ExprResult Input = InputExpr;
15504 QualType resultType;
15505 bool CanOverflow = false;
15506
15507 bool ConvertHalfVec = false;
15508 if (getLangOpts().OpenCL) {
15509 QualType Ty = InputExpr->getType();
15510 // The only legal unary operation for atomics is '&'.
15511 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15512 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15513 // only with a builtin functions and therefore should be disallowed here.
15514 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15515 || Ty->isBlockPointerType())) {
15516 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15517 << InputExpr->getType()
15518 << Input.get()->getSourceRange());
15519 }
15520 }
15521
15522 if (getLangOpts().HLSL && OpLoc.isValid()) {
15523 if (Opc == UO_AddrOf)
15524 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15525 if (Opc == UO_Deref)
15526 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15527 }
15528
15529 if (InputExpr->isTypeDependent() &&
15530 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
15531 resultType = Context.DependentTy;
15532 } else {
15533 switch (Opc) {
15534 case UO_PreInc:
15535 case UO_PreDec:
15536 case UO_PostInc:
15537 case UO_PostDec:
15538 resultType =
15539 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
15540 Opc == UO_PreInc || Opc == UO_PostInc,
15541 Opc == UO_PreInc || Opc == UO_PreDec);
15542 CanOverflow = isOverflowingIntegerType(Context, resultType);
15543 break;
15544 case UO_AddrOf:
15545 resultType = CheckAddressOfOperand(Input, OpLoc);
15546 CheckAddressOfNoDeref(InputExpr);
15547 RecordModifiableNonNullParam(*this, InputExpr);
15548 break;
15549 case UO_Deref: {
15551 if (Input.isInvalid())
15552 return ExprError();
15553 resultType =
15554 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15555 break;
15556 }
15557 case UO_Plus:
15558 case UO_Minus:
15559 CanOverflow = Opc == UO_Minus &&
15561 Input = UsualUnaryConversions(Input.get());
15562 if (Input.isInvalid())
15563 return ExprError();
15564 // Unary plus and minus require promoting an operand of half vector to a
15565 // float vector and truncating the result back to a half vector. For now,
15566 // we do this only when HalfArgsAndReturns is set (that is, when the
15567 // target is arm or arm64).
15568 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15569
15570 // If the operand is a half vector, promote it to a float vector.
15571 if (ConvertHalfVec)
15572 Input = convertVector(Input.get(), Context.FloatTy, *this);
15573 resultType = Input.get()->getType();
15574 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15575 break;
15576 else if (resultType->isVectorType() &&
15577 // The z vector extensions don't allow + or - with bool vectors.
15578 (!Context.getLangOpts().ZVector ||
15579 resultType->castAs<VectorType>()->getVectorKind() !=
15581 break;
15582 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
15583 break;
15584 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15585 Opc == UO_Plus && resultType->isPointerType())
15586 break;
15587
15588 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15589 << resultType << Input.get()->getSourceRange());
15590
15591 case UO_Not: // bitwise complement
15592 Input = UsualUnaryConversions(Input.get());
15593 if (Input.isInvalid())
15594 return ExprError();
15595 resultType = Input.get()->getType();
15596 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15597 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15598 // C99 does not support '~' for complex conjugation.
15599 Diag(OpLoc, diag::ext_integer_complement_complex)
15600 << resultType << Input.get()->getSourceRange();
15601 else if (resultType->hasIntegerRepresentation())
15602 break;
15603 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15604 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15605 // on vector float types.
15606 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15607 if (!T->isIntegerType())
15608 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15609 << resultType << Input.get()->getSourceRange());
15610 } else {
15611 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15612 << resultType << Input.get()->getSourceRange());
15613 }
15614 break;
15615
15616 case UO_LNot: // logical negation
15617 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15619 if (Input.isInvalid())
15620 return ExprError();
15621 resultType = Input.get()->getType();
15622
15623 // Though we still have to promote half FP to float...
15624 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15625 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
15626 .get();
15627 resultType = Context.FloatTy;
15628 }
15629
15630 // WebAsembly tables can't be used in unary expressions.
15631 if (resultType->isPointerType() &&
15633 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15634 << resultType << Input.get()->getSourceRange());
15635 }
15636
15637 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15638 // C99 6.5.3.3p1: ok, fallthrough;
15639 if (Context.getLangOpts().CPlusPlus) {
15640 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15641 // operand contextually converted to bool.
15642 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15643 ScalarTypeToBooleanCastKind(resultType));
15644 } else if (Context.getLangOpts().OpenCL &&
15645 Context.getLangOpts().OpenCLVersion < 120) {
15646 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15647 // operate on scalar float types.
15648 if (!resultType->isIntegerType() && !resultType->isPointerType())
15649 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15650 << resultType << Input.get()->getSourceRange());
15651 }
15652 } else if (resultType->isExtVectorType()) {
15653 if (Context.getLangOpts().OpenCL &&
15655 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15656 // operate on vector float types.
15657 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15658 if (!T->isIntegerType())
15659 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15660 << resultType << Input.get()->getSourceRange());
15661 }
15662 // Vector logical not returns the signed variant of the operand type.
15663 resultType = GetSignedVectorType(resultType);
15664 break;
15665 } else if (Context.getLangOpts().CPlusPlus &&
15666 resultType->isVectorType()) {
15667 const VectorType *VTy = resultType->castAs<VectorType>();
15668 if (VTy->getVectorKind() != VectorKind::Generic)
15669 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15670 << resultType << Input.get()->getSourceRange());
15671
15672 // Vector logical not returns the signed variant of the operand type.
15673 resultType = GetSignedVectorType(resultType);
15674 break;
15675 } else {
15676 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15677 << resultType << Input.get()->getSourceRange());
15678 }
15679
15680 // LNot always has type int. C99 6.5.3.3p5.
15681 // In C++, it's bool. C++ 5.3.1p8
15682 resultType = Context.getLogicalOperationType();
15683 break;
15684 case UO_Real:
15685 case UO_Imag:
15686 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15687 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
15688 // ordinary complex l-values to ordinary l-values and all other values to
15689 // r-values.
15690 if (Input.isInvalid())
15691 return ExprError();
15692 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15693 if (Input.get()->isGLValue() &&
15694 Input.get()->getObjectKind() == OK_Ordinary)
15695 VK = Input.get()->getValueKind();
15696 } else if (!getLangOpts().CPlusPlus) {
15697 // In C, a volatile scalar is read by __imag. In C++, it is not.
15698 Input = DefaultLvalueConversion(Input.get());
15699 }
15700 break;
15701 case UO_Extension:
15702 resultType = Input.get()->getType();
15703 VK = Input.get()->getValueKind();
15704 OK = Input.get()->getObjectKind();
15705 break;
15706 case UO_Coawait:
15707 // It's unnecessary to represent the pass-through operator co_await in the
15708 // AST; just return the input expression instead.
15709 assert(!Input.get()->getType()->isDependentType() &&
15710 "the co_await expression must be non-dependant before "
15711 "building operator co_await");
15712 return Input;
15713 }
15714 }
15715 if (resultType.isNull() || Input.isInvalid())
15716 return ExprError();
15717
15718 // Check for array bounds violations in the operand of the UnaryOperator,
15719 // except for the '*' and '&' operators that have to be handled specially
15720 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15721 // that are explicitly defined as valid by the standard).
15722 if (Opc != UO_AddrOf && Opc != UO_Deref)
15723 CheckArrayAccess(Input.get());
15724
15725 auto *UO =
15726 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15727 OpLoc, CanOverflow, CurFPFeatureOverrides());
15728
15729 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15730 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15732 ExprEvalContexts.back().PossibleDerefs.insert(UO);
15733
15734 // Convert the result back to a half vector.
15735 if (ConvertHalfVec)
15736 return convertVector(UO, Context.HalfTy, *this);
15737 return UO;
15738}
15739
15741 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15742 if (!DRE->getQualifier())
15743 return false;
15744
15745 ValueDecl *VD = DRE->getDecl();
15746 if (!VD->isCXXClassMember())
15747 return false;
15748
15749 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15750 return true;
15751 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15752 return Method->isImplicitObjectMemberFunction();
15753
15754 return false;
15755 }
15756
15757 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15758 if (!ULE->getQualifier())
15759 return false;
15760
15761 for (NamedDecl *D : ULE->decls()) {
15762 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15763 if (Method->isImplicitObjectMemberFunction())
15764 return true;
15765 } else {
15766 // Overload set does not contain methods.
15767 break;
15768 }
15769 }
15770
15771 return false;
15772 }
15773
15774 return false;
15775}
15776
15778 UnaryOperatorKind Opc, Expr *Input,
15779 bool IsAfterAmp) {
15780 // First things first: handle placeholders so that the
15781 // overloaded-operator check considers the right type.
15782 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15783 // Increment and decrement of pseudo-object references.
15784 if (pty->getKind() == BuiltinType::PseudoObject &&
15786 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
15787
15788 // extension is always a builtin operator.
15789 if (Opc == UO_Extension)
15790 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15791
15792 // & gets special logic for several kinds of placeholder.
15793 // The builtin code knows what to do.
15794 if (Opc == UO_AddrOf &&
15795 (pty->getKind() == BuiltinType::Overload ||
15796 pty->getKind() == BuiltinType::UnknownAny ||
15797 pty->getKind() == BuiltinType::BoundMember))
15798 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15799
15800 // Anything else needs to be handled now.
15802 if (Result.isInvalid()) return ExprError();
15803 Input = Result.get();
15804 }
15805
15806 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15808 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15809 // Find all of the overloaded operators visible from this point.
15810 UnresolvedSet<16> Functions;
15812 if (S && OverOp != OO_None)
15813 LookupOverloadedOperatorName(OverOp, S, Functions);
15814
15815 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15816 }
15817
15818 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
15819}
15820
15822 Expr *Input, bool IsAfterAmp) {
15823 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
15824 IsAfterAmp);
15825}
15826
15828 LabelDecl *TheDecl) {
15829 TheDecl->markUsed(Context);
15830 // Create the AST node. The address of a label always has type 'void*'.
15831 auto *Res = new (Context) AddrLabelExpr(
15832 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
15833
15834 if (getCurFunction())
15835 getCurFunction()->AddrLabels.push_back(Res);
15836
15837 return Res;
15838}
15839
15842 // Make sure we diagnose jumping into a statement expression.
15844}
15845
15847 // Note that function is also called by TreeTransform when leaving a
15848 // StmtExpr scope without rebuilding anything.
15849
15852}
15853
15855 SourceLocation RPLoc) {
15856 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15857}
15858
15860 SourceLocation RPLoc, unsigned TemplateDepth) {
15861 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15862 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15863
15866 assert(!Cleanup.exprNeedsCleanups() &&
15867 "cleanups within StmtExpr not correctly bound!");
15869
15870 // FIXME: there are a variety of strange constraints to enforce here, for
15871 // example, it is not possible to goto into a stmt expression apparently.
15872 // More semantic analysis is needed.
15873
15874 // If there are sub-stmts in the compound stmt, take the type of the last one
15875 // as the type of the stmtexpr.
15876 QualType Ty = Context.VoidTy;
15877 bool StmtExprMayBindToTemp = false;
15878 if (!Compound->body_empty()) {
15879 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15880 if (const auto *LastStmt =
15881 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15882 if (const Expr *Value = LastStmt->getExprStmt()) {
15883 StmtExprMayBindToTemp = true;
15884 Ty = Value->getType();
15885 }
15886 }
15887 }
15888
15889 // FIXME: Check that expression type is complete/non-abstract; statement
15890 // expressions are not lvalues.
15891 Expr *ResStmtExpr =
15892 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15893 if (StmtExprMayBindToTemp)
15894 return MaybeBindToTemporary(ResStmtExpr);
15895 return ResStmtExpr;
15896}
15897
15899 if (ER.isInvalid())
15900 return ExprError();
15901
15902 // Do function/array conversion on the last expression, but not
15903 // lvalue-to-rvalue. However, initialize an unqualified type.
15905 if (ER.isInvalid())
15906 return ExprError();
15907 Expr *E = ER.get();
15908
15909 if (E->isTypeDependent())
15910 return E;
15911
15912 // In ARC, if the final expression ends in a consume, splice
15913 // the consume out and bind it later. In the alternate case
15914 // (when dealing with a retainable type), the result
15915 // initialization will create a produce. In both cases the
15916 // result will be +1, and we'll need to balance that out with
15917 // a bind.
15918 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15919 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15920 return Cast->getSubExpr();
15921
15922 // FIXME: Provide a better location for the initialization.
15926 SourceLocation(), E);
15927}
15928
15930 TypeSourceInfo *TInfo,
15931 ArrayRef<OffsetOfComponent> Components,
15932 SourceLocation RParenLoc) {
15933 QualType ArgTy = TInfo->getType();
15934 bool Dependent = ArgTy->isDependentType();
15935 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15936
15937 // We must have at least one component that refers to the type, and the first
15938 // one is known to be a field designator. Verify that the ArgTy represents
15939 // a struct/union/class.
15940 if (!Dependent && !ArgTy->isRecordType())
15941 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15942 << ArgTy << TypeRange);
15943
15944 // Type must be complete per C99 7.17p3 because a declaring a variable
15945 // with an incomplete type would be ill-formed.
15946 if (!Dependent
15947 && RequireCompleteType(BuiltinLoc, ArgTy,
15948 diag::err_offsetof_incomplete_type, TypeRange))
15949 return ExprError();
15950
15951 bool DidWarnAboutNonPOD = false;
15952 QualType CurrentType = ArgTy;
15955 for (const OffsetOfComponent &OC : Components) {
15956 if (OC.isBrackets) {
15957 // Offset of an array sub-field. TODO: Should we allow vector elements?
15958 if (!CurrentType->isDependentType()) {
15959 const ArrayType *AT = Context.getAsArrayType(CurrentType);
15960 if(!AT)
15961 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15962 << CurrentType);
15963 CurrentType = AT->getElementType();
15964 } else
15965 CurrentType = Context.DependentTy;
15966
15967 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15968 if (IdxRval.isInvalid())
15969 return ExprError();
15970 Expr *Idx = IdxRval.get();
15971
15972 // The expression must be an integral expression.
15973 // FIXME: An integral constant expression?
15974 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15975 !Idx->getType()->isIntegerType())
15976 return ExprError(
15977 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15978 << Idx->getSourceRange());
15979
15980 // Record this array index.
15981 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15982 Exprs.push_back(Idx);
15983 continue;
15984 }
15985
15986 // Offset of a field.
15987 if (CurrentType->isDependentType()) {
15988 // We have the offset of a field, but we can't look into the dependent
15989 // type. Just record the identifier of the field.
15990 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
15991 CurrentType = Context.DependentTy;
15992 continue;
15993 }
15994
15995 // We need to have a complete type to look into.
15996 if (RequireCompleteType(OC.LocStart, CurrentType,
15997 diag::err_offsetof_incomplete_type))
15998 return ExprError();
15999
16000 // Look for the designated field.
16001 const RecordType *RC = CurrentType->getAs<RecordType>();
16002 if (!RC)
16003 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16004 << CurrentType);
16005 RecordDecl *RD = RC->getDecl();
16006
16007 // C++ [lib.support.types]p5:
16008 // The macro offsetof accepts a restricted set of type arguments in this
16009 // International Standard. type shall be a POD structure or a POD union
16010 // (clause 9).
16011 // C++11 [support.types]p4:
16012 // If type is not a standard-layout class (Clause 9), the results are
16013 // undefined.
16014 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16015 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16016 unsigned DiagID =
16017 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16018 : diag::ext_offsetof_non_pod_type;
16019
16020 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16021 Diag(BuiltinLoc, DiagID)
16022 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16023 DidWarnAboutNonPOD = true;
16024 }
16025 }
16026
16027 // Look for the field.
16028 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16029 LookupQualifiedName(R, RD);
16030 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16031 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16032 if (!MemberDecl) {
16033 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16034 MemberDecl = IndirectMemberDecl->getAnonField();
16035 }
16036
16037 if (!MemberDecl) {
16038 // Lookup could be ambiguous when looking up a placeholder variable
16039 // __builtin_offsetof(S, _).
16040 // In that case we would already have emitted a diagnostic
16041 if (!R.isAmbiguous())
16042 Diag(BuiltinLoc, diag::err_no_member)
16043 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16044 return ExprError();
16045 }
16046
16047 // C99 7.17p3:
16048 // (If the specified member is a bit-field, the behavior is undefined.)
16049 //
16050 // We diagnose this as an error.
16051 if (MemberDecl->isBitField()) {
16052 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16053 << MemberDecl->getDeclName()
16054 << SourceRange(BuiltinLoc, RParenLoc);
16055 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16056 return ExprError();
16057 }
16058
16059 RecordDecl *Parent = MemberDecl->getParent();
16060 if (IndirectMemberDecl)
16061 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16062
16063 // If the member was found in a base class, introduce OffsetOfNodes for
16064 // the base class indirections.
16065 CXXBasePaths Paths;
16066 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16067 Paths)) {
16068 if (Paths.getDetectedVirtual()) {
16069 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16070 << MemberDecl->getDeclName()
16071 << SourceRange(BuiltinLoc, RParenLoc);
16072 return ExprError();
16073 }
16074
16075 CXXBasePath &Path = Paths.front();
16076 for (const CXXBasePathElement &B : Path)
16077 Comps.push_back(OffsetOfNode(B.Base));
16078 }
16079
16080 if (IndirectMemberDecl) {
16081 for (auto *FI : IndirectMemberDecl->chain()) {
16082 assert(isa<FieldDecl>(FI));
16083 Comps.push_back(OffsetOfNode(OC.LocStart,
16084 cast<FieldDecl>(FI), OC.LocEnd));
16085 }
16086 } else
16087 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16088
16089 CurrentType = MemberDecl->getType().getNonReferenceType();
16090 }
16091
16092 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16093 Comps, Exprs, RParenLoc);
16094}
16095
16097 SourceLocation BuiltinLoc,
16099 ParsedType ParsedArgTy,
16100 ArrayRef<OffsetOfComponent> Components,
16101 SourceLocation RParenLoc) {
16102
16103 TypeSourceInfo *ArgTInfo;
16104 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16105 if (ArgTy.isNull())
16106 return ExprError();
16107
16108 if (!ArgTInfo)
16109 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16110
16111 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16112}
16113
16114
16116 Expr *CondExpr,
16117 Expr *LHSExpr, Expr *RHSExpr,
16118 SourceLocation RPLoc) {
16119 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16120
16123 QualType resType;
16124 bool CondIsTrue = false;
16125 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16126 resType = Context.DependentTy;
16127 } else {
16128 // The conditional expression is required to be a constant expression.
16129 llvm::APSInt condEval(32);
16131 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16132 if (CondICE.isInvalid())
16133 return ExprError();
16134 CondExpr = CondICE.get();
16135 CondIsTrue = condEval.getZExtValue();
16136
16137 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16138 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16139
16140 resType = ActiveExpr->getType();
16141 VK = ActiveExpr->getValueKind();
16142 OK = ActiveExpr->getObjectKind();
16143 }
16144
16145 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16146 resType, VK, OK, RPLoc, CondIsTrue);
16147}
16148
16149//===----------------------------------------------------------------------===//
16150// Clang Extensions.
16151//===----------------------------------------------------------------------===//
16152
16153void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16155
16156 if (LangOpts.CPlusPlus) {
16158 Decl *ManglingContextDecl;
16159 std::tie(MCtx, ManglingContextDecl) =
16160 getCurrentMangleNumberContext(Block->getDeclContext());
16161 if (MCtx) {
16162 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16163 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16164 }
16165 }
16166
16167 PushBlockScope(CurScope, Block);
16169 if (CurScope)
16170 PushDeclContext(CurScope, Block);
16171 else
16172 CurContext = Block;
16173
16175
16176 // Enter a new evaluation context to insulate the block from any
16177 // cleanups from the enclosing full-expression.
16180}
16181
16183 Scope *CurScope) {
16184 assert(ParamInfo.getIdentifier() == nullptr &&
16185 "block-id should have no identifier!");
16186 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16187 BlockScopeInfo *CurBlock = getCurBlock();
16188
16189 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16190 QualType T = Sig->getType();
16192
16193 // GetTypeForDeclarator always produces a function type for a block
16194 // literal signature. Furthermore, it is always a FunctionProtoType
16195 // unless the function was written with a typedef.
16196 assert(T->isFunctionType() &&
16197 "GetTypeForDeclarator made a non-function block signature");
16198
16199 // Look for an explicit signature in that function type.
16200 FunctionProtoTypeLoc ExplicitSignature;
16201
16202 if ((ExplicitSignature = Sig->getTypeLoc()
16204
16205 // Check whether that explicit signature was synthesized by
16206 // GetTypeForDeclarator. If so, don't save that as part of the
16207 // written signature.
16208 if (ExplicitSignature.getLocalRangeBegin() ==
16209 ExplicitSignature.getLocalRangeEnd()) {
16210 // This would be much cheaper if we stored TypeLocs instead of
16211 // TypeSourceInfos.
16212 TypeLoc Result = ExplicitSignature.getReturnLoc();
16213 unsigned Size = Result.getFullDataSize();
16214 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16215 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16216
16217 ExplicitSignature = FunctionProtoTypeLoc();
16218 }
16219 }
16220
16221 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16222 CurBlock->FunctionType = T;
16223
16224 const auto *Fn = T->castAs<FunctionType>();
16225 QualType RetTy = Fn->getReturnType();
16226 bool isVariadic =
16227 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16228
16229 CurBlock->TheDecl->setIsVariadic(isVariadic);
16230
16231 // Context.DependentTy is used as a placeholder for a missing block
16232 // return type. TODO: what should we do with declarators like:
16233 // ^ * { ... }
16234 // If the answer is "apply template argument deduction"....
16235 if (RetTy != Context.DependentTy) {
16236 CurBlock->ReturnType = RetTy;
16237 CurBlock->TheDecl->setBlockMissingReturnType(false);
16238 CurBlock->HasImplicitReturnType = false;
16239 }
16240
16241 // Push block parameters from the declarator if we had them.
16243 if (ExplicitSignature) {
16244 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16245 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16246 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16247 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16248 // Diagnose this as an extension in C17 and earlier.
16249 if (!getLangOpts().C23)
16250 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16251 }
16252 Params.push_back(Param);
16253 }
16254
16255 // Fake up parameter variables if we have a typedef, like
16256 // ^ fntype { ... }
16257 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16258 for (const auto &I : Fn->param_types()) {
16260 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16261 Params.push_back(Param);
16262 }
16263 }
16264
16265 // Set the parameters on the block decl.
16266 if (!Params.empty()) {
16267 CurBlock->TheDecl->setParams(Params);
16269 /*CheckParameterNames=*/false);
16270 }
16271
16272 // Finally we can process decl attributes.
16273 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16274
16275 // Put the parameter variables in scope.
16276 for (auto *AI : CurBlock->TheDecl->parameters()) {
16277 AI->setOwningFunction(CurBlock->TheDecl);
16278
16279 // If this has an identifier, add it to the scope stack.
16280 if (AI->getIdentifier()) {
16281 CheckShadow(CurBlock->TheScope, AI);
16282
16283 PushOnScopeChains(AI, CurBlock->TheScope);
16284 }
16285
16286 if (AI->isInvalidDecl())
16287 CurBlock->TheDecl->setInvalidDecl();
16288 }
16289}
16290
16291void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16292 // Leave the expression-evaluation context.
16295
16296 // Pop off CurBlock, handle nested blocks.
16299}
16300
16302 Stmt *Body, Scope *CurScope) {
16303 // If blocks are disabled, emit an error.
16304 if (!LangOpts.Blocks)
16305 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16306
16307 // Leave the expression-evaluation context.
16310 assert(!Cleanup.exprNeedsCleanups() &&
16311 "cleanups within block not correctly bound!");
16313
16314 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16315 BlockDecl *BD = BSI->TheDecl;
16316
16318
16319 if (BSI->HasImplicitReturnType)
16321
16322 QualType RetTy = Context.VoidTy;
16323 if (!BSI->ReturnType.isNull())
16324 RetTy = BSI->ReturnType;
16325
16326 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16327 QualType BlockTy;
16328
16329 // If the user wrote a function type in some form, try to use that.
16330 if (!BSI->FunctionType.isNull()) {
16331 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16332
16333 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16334 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16335
16336 // Turn protoless block types into nullary block types.
16337 if (isa<FunctionNoProtoType>(FTy)) {
16339 EPI.ExtInfo = Ext;
16340 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16341
16342 // Otherwise, if we don't need to change anything about the function type,
16343 // preserve its sugar structure.
16344 } else if (FTy->getReturnType() == RetTy &&
16345 (!NoReturn || FTy->getNoReturnAttr())) {
16346 BlockTy = BSI->FunctionType;
16347
16348 // Otherwise, make the minimal modifications to the function type.
16349 } else {
16350 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16352 EPI.TypeQuals = Qualifiers();
16353 EPI.ExtInfo = Ext;
16354 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16355 }
16356
16357 // If we don't have a function type, just build one from nothing.
16358 } else {
16360 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16361 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16362 }
16363
16365 BlockTy = Context.getBlockPointerType(BlockTy);
16366
16367 // If needed, diagnose invalid gotos and switches in the block.
16368 if (getCurFunction()->NeedsScopeChecking() &&
16370 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16371
16372 BD->setBody(cast<CompoundStmt>(Body));
16373
16374 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16376
16377 // Try to apply the named return value optimization. We have to check again
16378 // if we can do this, though, because blocks keep return statements around
16379 // to deduce an implicit return type.
16380 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16381 !BD->isDependentContext())
16382 computeNRVO(Body, BSI);
16383
16388
16390
16391 // Set the captured variables on the block.
16393 for (Capture &Cap : BSI->Captures) {
16394 if (Cap.isInvalid() || Cap.isThisCapture())
16395 continue;
16396 // Cap.getVariable() is always a VarDecl because
16397 // blocks cannot capture structured bindings or other ValueDecl kinds.
16398 auto *Var = cast<VarDecl>(Cap.getVariable());
16399 Expr *CopyExpr = nullptr;
16400 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16401 if (const RecordType *Record =
16402 Cap.getCaptureType()->getAs<RecordType>()) {
16403 // The capture logic needs the destructor, so make sure we mark it.
16404 // Usually this is unnecessary because most local variables have
16405 // their destructors marked at declaration time, but parameters are
16406 // an exception because it's technically only the call site that
16407 // actually requires the destructor.
16408 if (isa<ParmVarDecl>(Var))
16410
16411 // Enter a separate potentially-evaluated context while building block
16412 // initializers to isolate their cleanups from those of the block
16413 // itself.
16414 // FIXME: Is this appropriate even when the block itself occurs in an
16415 // unevaluated operand?
16418
16420
16422 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16423
16424 // According to the blocks spec, the capture of a variable from
16425 // the stack requires a const copy constructor. This is not true
16426 // of the copy/move done to move a __block variable to the heap.
16427 if (!Result.isInvalid() &&
16428 !Result.get()->getType().isConstQualified()) {
16430 Result.get()->getType().withConst(),
16431 CK_NoOp, VK_LValue);
16432 }
16433
16434 if (!Result.isInvalid()) {
16436 InitializedEntity::InitializeBlock(Var->getLocation(),
16437 Cap.getCaptureType()),
16438 Loc, Result.get());
16439 }
16440
16441 // Build a full-expression copy expression if initialization
16442 // succeeded and used a non-trivial constructor. Recover from
16443 // errors by pretending that the copy isn't necessary.
16444 if (!Result.isInvalid() &&
16445 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16446 ->isTrivial()) {
16448 CopyExpr = Result.get();
16449 }
16450 }
16451 }
16452
16453 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16454 CopyExpr);
16455 Captures.push_back(NewCap);
16456 }
16457 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16458
16459 // Pop the block scope now but keep it alive to the end of this function.
16461 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16462
16463 BlockExpr *Result = new (Context)
16464 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
16465
16466 // If the block isn't obviously global, i.e. it captures anything at
16467 // all, then we need to do a few things in the surrounding context:
16468 if (Result->getBlockDecl()->hasCaptures()) {
16469 // First, this expression has a new cleanup object.
16470 ExprCleanupObjects.push_back(Result->getBlockDecl());
16472
16473 // It also gets a branch-protected scope if any of the captured
16474 // variables needs destruction.
16475 for (const auto &CI : Result->getBlockDecl()->captures()) {
16476 const VarDecl *var = CI.getVariable();
16477 if (var->getType().isDestructedType() != QualType::DK_none) {
16479 break;
16480 }
16481 }
16482 }
16483
16484 if (getCurFunction())
16485 getCurFunction()->addBlock(BD);
16486
16487 // This can happen if the block's return type is deduced, but
16488 // the return expression is invalid.
16489 if (BD->isInvalidDecl())
16490 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
16491 {Result}, Result->getType());
16492 return Result;
16493}
16494
16496 SourceLocation RPLoc) {
16497 TypeSourceInfo *TInfo;
16498 GetTypeFromParser(Ty, &TInfo);
16499 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16500}
16501
16503 Expr *E, TypeSourceInfo *TInfo,
16504 SourceLocation RPLoc) {
16505 Expr *OrigExpr = E;
16506 bool IsMS = false;
16507
16508 // CUDA device code does not support varargs.
16509 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16510 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16514 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16515 }
16516 }
16517
16518 // NVPTX does not support va_arg expression.
16519 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16520 Context.getTargetInfo().getTriple().isNVPTX())
16521 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16522
16523 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16524 // as Microsoft ABI on an actual Microsoft platform, where
16525 // __builtin_ms_va_list and __builtin_va_list are the same.)
16528 QualType MSVaListType = Context.getBuiltinMSVaListType();
16529 if (Context.hasSameType(MSVaListType, E->getType())) {
16530 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16531 return ExprError();
16532 IsMS = true;
16533 }
16534 }
16535
16536 // Get the va_list type
16537 QualType VaListType = Context.getBuiltinVaListType();
16538 if (!IsMS) {
16539 if (VaListType->isArrayType()) {
16540 // Deal with implicit array decay; for example, on x86-64,
16541 // va_list is an array, but it's supposed to decay to
16542 // a pointer for va_arg.
16543 VaListType = Context.getArrayDecayedType(VaListType);
16544 // Make sure the input expression also decays appropriately.
16546 if (Result.isInvalid())
16547 return ExprError();
16548 E = Result.get();
16549 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16550 // If va_list is a record type and we are compiling in C++ mode,
16551 // check the argument using reference binding.
16553 Context, Context.getLValueReferenceType(VaListType), false);
16555 if (Init.isInvalid())
16556 return ExprError();
16557 E = Init.getAs<Expr>();
16558 } else {
16559 // Otherwise, the va_list argument must be an l-value because
16560 // it is modified by va_arg.
16561 if (!E->isTypeDependent() &&
16562 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16563 return ExprError();
16564 }
16565 }
16566
16567 if (!IsMS && !E->isTypeDependent() &&
16568 !Context.hasSameType(VaListType, E->getType()))
16569 return ExprError(
16570 Diag(E->getBeginLoc(),
16571 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16572 << OrigExpr->getType() << E->getSourceRange());
16573
16574 if (!TInfo->getType()->isDependentType()) {
16575 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16576 diag::err_second_parameter_to_va_arg_incomplete,
16577 TInfo->getTypeLoc()))
16578 return ExprError();
16579
16581 TInfo->getType(),
16582 diag::err_second_parameter_to_va_arg_abstract,
16583 TInfo->getTypeLoc()))
16584 return ExprError();
16585
16586 if (!TInfo->getType().isPODType(Context)) {
16587 Diag(TInfo->getTypeLoc().getBeginLoc(),
16588 TInfo->getType()->isObjCLifetimeType()
16589 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16590 : diag::warn_second_parameter_to_va_arg_not_pod)
16591 << TInfo->getType()
16592 << TInfo->getTypeLoc().getSourceRange();
16593 }
16594
16595 // Check for va_arg where arguments of the given type will be promoted
16596 // (i.e. this va_arg is guaranteed to have undefined behavior).
16597 QualType PromoteType;
16598 if (Context.isPromotableIntegerType(TInfo->getType())) {
16599 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16600 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16601 // and C23 7.16.1.1p2 says, in part:
16602 // If type is not compatible with the type of the actual next argument
16603 // (as promoted according to the default argument promotions), the
16604 // behavior is undefined, except for the following cases:
16605 // - both types are pointers to qualified or unqualified versions of
16606 // compatible types;
16607 // - one type is compatible with a signed integer type, the other
16608 // type is compatible with the corresponding unsigned integer type,
16609 // and the value is representable in both types;
16610 // - one type is pointer to qualified or unqualified void and the
16611 // other is a pointer to a qualified or unqualified character type;
16612 // - or, the type of the next argument is nullptr_t and type is a
16613 // pointer type that has the same representation and alignment
16614 // requirements as a pointer to a character type.
16615 // Given that type compatibility is the primary requirement (ignoring
16616 // qualifications), you would think we could call typesAreCompatible()
16617 // directly to test this. However, in C++, that checks for *same type*,
16618 // which causes false positives when passing an enumeration type to
16619 // va_arg. Instead, get the underlying type of the enumeration and pass
16620 // that.
16621 QualType UnderlyingType = TInfo->getType();
16622 if (const auto *ET = UnderlyingType->getAs<EnumType>())
16623 UnderlyingType = ET->getDecl()->getIntegerType();
16624 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16625 /*CompareUnqualified*/ true))
16626 PromoteType = QualType();
16627
16628 // If the types are still not compatible, we need to test whether the
16629 // promoted type and the underlying type are the same except for
16630 // signedness. Ask the AST for the correctly corresponding type and see
16631 // if that's compatible.
16632 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16633 PromoteType->isUnsignedIntegerType() !=
16634 UnderlyingType->isUnsignedIntegerType()) {
16635 UnderlyingType =
16636 UnderlyingType->isUnsignedIntegerType()
16637 ? Context.getCorrespondingSignedType(UnderlyingType)
16638 : Context.getCorrespondingUnsignedType(UnderlyingType);
16639 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16640 /*CompareUnqualified*/ true))
16641 PromoteType = QualType();
16642 }
16643 }
16644 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16645 PromoteType = Context.DoubleTy;
16646 if (!PromoteType.isNull())
16648 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16649 << TInfo->getType()
16650 << PromoteType
16651 << TInfo->getTypeLoc().getSourceRange());
16652 }
16653
16655 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16656}
16657
16659 // The type of __null will be int or long, depending on the size of
16660 // pointers on the target.
16661 QualType Ty;
16663 if (pw == Context.getTargetInfo().getIntWidth())
16664 Ty = Context.IntTy;
16665 else if (pw == Context.getTargetInfo().getLongWidth())
16666 Ty = Context.LongTy;
16667 else if (pw == Context.getTargetInfo().getLongLongWidth())
16668 Ty = Context.LongLongTy;
16669 else {
16670 llvm_unreachable("I don't know size of pointer!");
16671 }
16672
16673 return new (Context) GNUNullExpr(Ty, TokenLoc);
16674}
16675
16677 CXXRecordDecl *ImplDecl = nullptr;
16678
16679 // Fetch the std::source_location::__impl decl.
16680 if (NamespaceDecl *Std = S.getStdNamespace()) {
16681 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16683 if (S.LookupQualifiedName(ResultSL, Std)) {
16684 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16685 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16687 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16688 S.LookupQualifiedName(ResultImpl, SLDecl)) {
16689 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16690 }
16691 }
16692 }
16693 }
16694
16695 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16696 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16697 return nullptr;
16698 }
16699
16700 // Verify that __impl is a trivial struct type, with no base classes, and with
16701 // only the four expected fields.
16702 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16703 ImplDecl->getNumBases() != 0) {
16704 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16705 return nullptr;
16706 }
16707
16708 unsigned Count = 0;
16709 for (FieldDecl *F : ImplDecl->fields()) {
16710 StringRef Name = F->getName();
16711
16712 if (Name == "_M_file_name") {
16713 if (F->getType() !=
16715 break;
16716 Count++;
16717 } else if (Name == "_M_function_name") {
16718 if (F->getType() !=
16720 break;
16721 Count++;
16722 } else if (Name == "_M_line") {
16723 if (!F->getType()->isIntegerType())
16724 break;
16725 Count++;
16726 } else if (Name == "_M_column") {
16727 if (!F->getType()->isIntegerType())
16728 break;
16729 Count++;
16730 } else {
16731 Count = 100; // invalid
16732 break;
16733 }
16734 }
16735 if (Count != 4) {
16736 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16737 return nullptr;
16738 }
16739
16740 return ImplDecl;
16741}
16742
16744 SourceLocation BuiltinLoc,
16745 SourceLocation RPLoc) {
16746 QualType ResultTy;
16747 switch (Kind) {
16753 ResultTy =
16755 break;
16756 }
16759 ResultTy = Context.UnsignedIntTy;
16760 break;
16764 LookupStdSourceLocationImpl(*this, BuiltinLoc);
16766 return ExprError();
16767 }
16768 ResultTy = Context.getPointerType(
16770 break;
16771 }
16772
16773 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16774}
16775
16777 SourceLocation BuiltinLoc,
16778 SourceLocation RPLoc,
16779 DeclContext *ParentContext) {
16780 return new (Context)
16781 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16782}
16783
16785 StringLiteral *BinaryData) {
16787 Data->BinaryData = BinaryData;
16788 return new (Context)
16789 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
16790 Data->getDataElementCount());
16791}
16792
16794 const Expr *SrcExpr) {
16795 if (!DstType->isFunctionPointerType() ||
16796 !SrcExpr->getType()->isFunctionType())
16797 return false;
16798
16799 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16800 if (!DRE)
16801 return false;
16802
16803 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16804 if (!FD)
16805 return false;
16806
16808 /*Complain=*/true,
16809 SrcExpr->getBeginLoc());
16810}
16811
16814 QualType DstType, QualType SrcType,
16815 Expr *SrcExpr, AssignmentAction Action,
16816 bool *Complained) {
16817 if (Complained)
16818 *Complained = false;
16819
16820 // Decode the result (notice that AST's are still created for extensions).
16821 bool CheckInferredResultType = false;
16822 bool isInvalid = false;
16823 unsigned DiagKind = 0;
16824 ConversionFixItGenerator ConvHints;
16825 bool MayHaveConvFixit = false;
16826 bool MayHaveFunctionDiff = false;
16827 const ObjCInterfaceDecl *IFace = nullptr;
16828 const ObjCProtocolDecl *PDecl = nullptr;
16829
16830 switch (ConvTy) {
16831 case Compatible:
16832 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16833 return false;
16834
16835 case PointerToInt:
16836 if (getLangOpts().CPlusPlus) {
16837 DiagKind = diag::err_typecheck_convert_pointer_int;
16838 isInvalid = true;
16839 } else {
16840 DiagKind = diag::ext_typecheck_convert_pointer_int;
16841 }
16842 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16843 MayHaveConvFixit = true;
16844 break;
16845 case IntToPointer:
16846 if (getLangOpts().CPlusPlus) {
16847 DiagKind = diag::err_typecheck_convert_int_pointer;
16848 isInvalid = true;
16849 } else {
16850 DiagKind = diag::ext_typecheck_convert_int_pointer;
16851 }
16852 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16853 MayHaveConvFixit = true;
16854 break;
16856 DiagKind =
16857 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
16858 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16859 MayHaveConvFixit = true;
16860 break;
16862 if (getLangOpts().CPlusPlus) {
16863 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16864 isInvalid = true;
16865 } else {
16866 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16867 }
16868 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16869 MayHaveConvFixit = true;
16870 break;
16873 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16874 } else if (getLangOpts().CPlusPlus) {
16875 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16876 isInvalid = true;
16877 } else {
16878 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16879 }
16880 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16881 SrcType->isObjCObjectPointerType();
16882 if (CheckInferredResultType) {
16883 SrcType = SrcType.getUnqualifiedType();
16884 DstType = DstType.getUnqualifiedType();
16885 } else {
16886 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16887 }
16888 MayHaveConvFixit = true;
16889 break;
16891 if (getLangOpts().CPlusPlus) {
16892 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16893 isInvalid = true;
16894 } else {
16895 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16896 }
16897 break;
16899 if (getLangOpts().CPlusPlus) {
16900 DiagKind = diag::err_typecheck_convert_pointer_void_func;
16901 isInvalid = true;
16902 } else {
16903 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16904 }
16905 break;
16907 // Perform array-to-pointer decay if necessary.
16908 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16909
16910 isInvalid = true;
16911
16912 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16913 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16914 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16915 DiagKind = diag::err_typecheck_incompatible_address_space;
16916 break;
16917 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16918 DiagKind = diag::err_typecheck_incompatible_ownership;
16919 break;
16920 }
16921
16922 llvm_unreachable("unknown error case for discarding qualifiers!");
16923 // fallthrough
16924 }
16926 // If the qualifiers lost were because we were applying the
16927 // (deprecated) C++ conversion from a string literal to a char*
16928 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
16929 // Ideally, this check would be performed in
16930 // checkPointerTypesForAssignment. However, that would require a
16931 // bit of refactoring (so that the second argument is an
16932 // expression, rather than a type), which should be done as part
16933 // of a larger effort to fix checkPointerTypesForAssignment for
16934 // C++ semantics.
16935 if (getLangOpts().CPlusPlus &&
16937 return false;
16938 if (getLangOpts().CPlusPlus) {
16939 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
16940 isInvalid = true;
16941 } else {
16942 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
16943 }
16944
16945 break;
16947 if (getLangOpts().CPlusPlus) {
16948 isInvalid = true;
16949 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16950 } else {
16951 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16952 }
16953 break;
16955 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16956 isInvalid = true;
16957 break;
16958 case IntToBlockPointer:
16959 DiagKind = diag::err_int_to_block_pointer;
16960 isInvalid = true;
16961 break;
16963 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16964 isInvalid = true;
16965 break;
16967 if (SrcType->isObjCQualifiedIdType()) {
16968 const ObjCObjectPointerType *srcOPT =
16969 SrcType->castAs<ObjCObjectPointerType>();
16970 for (auto *srcProto : srcOPT->quals()) {
16971 PDecl = srcProto;
16972 break;
16973 }
16974 if (const ObjCInterfaceType *IFaceT =
16976 IFace = IFaceT->getDecl();
16977 }
16978 else if (DstType->isObjCQualifiedIdType()) {
16979 const ObjCObjectPointerType *dstOPT =
16980 DstType->castAs<ObjCObjectPointerType>();
16981 for (auto *dstProto : dstOPT->quals()) {
16982 PDecl = dstProto;
16983 break;
16984 }
16985 if (const ObjCInterfaceType *IFaceT =
16987 IFace = IFaceT->getDecl();
16988 }
16989 if (getLangOpts().CPlusPlus) {
16990 DiagKind = diag::err_incompatible_qualified_id;
16991 isInvalid = true;
16992 } else {
16993 DiagKind = diag::warn_incompatible_qualified_id;
16994 }
16995 break;
16996 }
16998 if (getLangOpts().CPlusPlus) {
16999 DiagKind = diag::err_incompatible_vectors;
17000 isInvalid = true;
17001 } else {
17002 DiagKind = diag::warn_incompatible_vectors;
17003 }
17004 break;
17006 DiagKind = diag::err_arc_weak_unavailable_assign;
17007 isInvalid = true;
17008 break;
17009 case Incompatible:
17010 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17011 if (Complained)
17012 *Complained = true;
17013 return true;
17014 }
17015
17016 DiagKind = diag::err_typecheck_convert_incompatible;
17017 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17018 MayHaveConvFixit = true;
17019 isInvalid = true;
17020 MayHaveFunctionDiff = true;
17021 break;
17022 }
17023
17024 QualType FirstType, SecondType;
17025 switch (Action) {
17028 // The destination type comes first.
17029 FirstType = DstType;
17030 SecondType = SrcType;
17031 break;
17032
17039 // The source type comes first.
17040 FirstType = SrcType;
17041 SecondType = DstType;
17042 break;
17043 }
17044
17045 PartialDiagnostic FDiag = PDiag(DiagKind);
17046 AssignmentAction ActionForDiag = Action;
17048 ActionForDiag = AssignmentAction::Passing;
17049
17050 FDiag << FirstType << SecondType << ActionForDiag
17051 << SrcExpr->getSourceRange();
17052
17053 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17054 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17055 auto isPlainChar = [](const clang::Type *Type) {
17056 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17057 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17058 };
17059 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17060 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17061 }
17062
17063 // If we can fix the conversion, suggest the FixIts.
17064 if (!ConvHints.isNull()) {
17065 for (FixItHint &H : ConvHints.Hints)
17066 FDiag << H;
17067 }
17068
17069 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17070
17071 if (MayHaveFunctionDiff)
17072 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17073
17074 Diag(Loc, FDiag);
17075 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17076 DiagKind == diag::err_incompatible_qualified_id) &&
17077 PDecl && IFace && !IFace->hasDefinition())
17078 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17079 << IFace << PDecl;
17080
17081 if (SecondType == Context.OverloadTy)
17083 FirstType, /*TakingAddress=*/true);
17084
17085 if (CheckInferredResultType)
17087
17088 if (Action == AssignmentAction::Returning && ConvTy == IncompatiblePointer)
17090
17091 if (Complained)
17092 *Complained = true;
17093 return isInvalid;
17094}
17095
17097 llvm::APSInt *Result,
17098 AllowFoldKind CanFold) {
17099 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17100 public:
17101 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17102 QualType T) override {
17103 return S.Diag(Loc, diag::err_ice_not_integral)
17104 << T << S.LangOpts.CPlusPlus;
17105 }
17106 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17107 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17108 }
17109 } Diagnoser;
17110
17111 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17112}
17113
17115 llvm::APSInt *Result,
17116 unsigned DiagID,
17117 AllowFoldKind CanFold) {
17118 class IDDiagnoser : public VerifyICEDiagnoser {
17119 unsigned DiagID;
17120
17121 public:
17122 IDDiagnoser(unsigned DiagID)
17123 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17124
17125 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17126 return S.Diag(Loc, DiagID);
17127 }
17128 } Diagnoser(DiagID);
17129
17130 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17131}
17132
17135 QualType T) {
17136 return diagnoseNotICE(S, Loc);
17137}
17138
17141 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17142}
17143
17146 VerifyICEDiagnoser &Diagnoser,
17147 AllowFoldKind CanFold) {
17148 SourceLocation DiagLoc = E->getBeginLoc();
17149
17150 if (getLangOpts().CPlusPlus11) {
17151 // C++11 [expr.const]p5:
17152 // If an expression of literal class type is used in a context where an
17153 // integral constant expression is required, then that class type shall
17154 // have a single non-explicit conversion function to an integral or
17155 // unscoped enumeration type
17156 ExprResult Converted;
17157 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17158 VerifyICEDiagnoser &BaseDiagnoser;
17159 public:
17160 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17161 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17162 BaseDiagnoser.Suppress, true),
17163 BaseDiagnoser(BaseDiagnoser) {}
17164
17165 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17166 QualType T) override {
17167 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17168 }
17169
17170 SemaDiagnosticBuilder diagnoseIncomplete(
17171 Sema &S, SourceLocation Loc, QualType T) override {
17172 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17173 }
17174
17175 SemaDiagnosticBuilder diagnoseExplicitConv(
17176 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17177 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17178 }
17179
17180 SemaDiagnosticBuilder noteExplicitConv(
17181 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17182 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17183 << ConvTy->isEnumeralType() << ConvTy;
17184 }
17185
17186 SemaDiagnosticBuilder diagnoseAmbiguous(
17187 Sema &S, SourceLocation Loc, QualType T) override {
17188 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17189 }
17190
17191 SemaDiagnosticBuilder noteAmbiguous(
17192 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17193 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17194 << ConvTy->isEnumeralType() << ConvTy;
17195 }
17196
17197 SemaDiagnosticBuilder diagnoseConversion(
17198 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17199 llvm_unreachable("conversion functions are permitted");
17200 }
17201 } ConvertDiagnoser(Diagnoser);
17202
17203 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17204 ConvertDiagnoser);
17205 if (Converted.isInvalid())
17206 return Converted;
17207 E = Converted.get();
17208 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17209 // don't try to evaluate it later. We also don't want to return the
17210 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17211 // this function will attempt to use 'Value'.
17212 if (isa<RecoveryExpr>(E))
17213 return ExprError();
17215 return ExprError();
17216 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17217 // An ICE must be of integral or unscoped enumeration type.
17218 if (!Diagnoser.Suppress)
17219 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17220 << E->getSourceRange();
17221 return ExprError();
17222 }
17223
17224 ExprResult RValueExpr = DefaultLvalueConversion(E);
17225 if (RValueExpr.isInvalid())
17226 return ExprError();
17227
17228 E = RValueExpr.get();
17229
17230 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17231 // in the non-ICE case.
17234 if (Result)
17236 if (!isa<ConstantExpr>(E))
17239
17240 if (Notes.empty())
17241 return E;
17242
17243 // If our only note is the usual "invalid subexpression" note, just point
17244 // the caret at its location rather than producing an essentially
17245 // redundant note.
17246 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17247 diag::note_invalid_subexpr_in_const_expr) {
17248 DiagLoc = Notes[0].first;
17249 Notes.clear();
17250 }
17251
17252 if (getLangOpts().CPlusPlus) {
17253 if (!Diagnoser.Suppress) {
17254 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17255 for (const PartialDiagnosticAt &Note : Notes)
17256 Diag(Note.first, Note.second);
17257 }
17258 return ExprError();
17259 }
17260
17261 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17262 for (const PartialDiagnosticAt &Note : Notes)
17263 Diag(Note.first, Note.second);
17264
17265 return E;
17266 }
17267
17268 Expr::EvalResult EvalResult;
17270 EvalResult.Diag = &Notes;
17271
17272 // Try to evaluate the expression, and produce diagnostics explaining why it's
17273 // not a constant expression as a side-effect.
17274 bool Folded =
17275 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17276 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17277 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17278
17279 if (!isa<ConstantExpr>(E))
17280 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17281
17282 // In C++11, we can rely on diagnostics being produced for any expression
17283 // which is not a constant expression. If no diagnostics were produced, then
17284 // this is a constant expression.
17285 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17286 if (Result)
17287 *Result = EvalResult.Val.getInt();
17288 return E;
17289 }
17290
17291 // If our only note is the usual "invalid subexpression" note, just point
17292 // the caret at its location rather than producing an essentially
17293 // redundant note.
17294 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17295 diag::note_invalid_subexpr_in_const_expr) {
17296 DiagLoc = Notes[0].first;
17297 Notes.clear();
17298 }
17299
17300 if (!Folded || !CanFold) {
17301 if (!Diagnoser.Suppress) {
17302 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17303 for (const PartialDiagnosticAt &Note : Notes)
17304 Diag(Note.first, Note.second);
17305 }
17306
17307 return ExprError();
17308 }
17309
17310 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17311 for (const PartialDiagnosticAt &Note : Notes)
17312 Diag(Note.first, Note.second);
17313
17314 if (Result)
17315 *Result = EvalResult.Val.getInt();
17316 return E;
17317}
17318
17319namespace {
17320 // Handle the case where we conclude a expression which we speculatively
17321 // considered to be unevaluated is actually evaluated.
17322 class TransformToPE : public TreeTransform<TransformToPE> {
17323 typedef TreeTransform<TransformToPE> BaseTransform;
17324
17325 public:
17326 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17327
17328 // Make sure we redo semantic analysis
17329 bool AlwaysRebuild() { return true; }
17330 bool ReplacingOriginal() { return true; }
17331
17332 // We need to special-case DeclRefExprs referring to FieldDecls which
17333 // are not part of a member pointer formation; normal TreeTransforming
17334 // doesn't catch this case because of the way we represent them in the AST.
17335 // FIXME: This is a bit ugly; is it really the best way to handle this
17336 // case?
17337 //
17338 // Error on DeclRefExprs referring to FieldDecls.
17339 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17340 if (isa<FieldDecl>(E->getDecl()) &&
17341 !SemaRef.isUnevaluatedContext())
17342 return SemaRef.Diag(E->getLocation(),
17343 diag::err_invalid_non_static_member_use)
17344 << E->getDecl() << E->getSourceRange();
17345
17346 return BaseTransform::TransformDeclRefExpr(E);
17347 }
17348
17349 // Exception: filter out member pointer formation
17350 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17351 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17352 return E;
17353
17354 return BaseTransform::TransformUnaryOperator(E);
17355 }
17356
17357 // The body of a lambda-expression is in a separate expression evaluation
17358 // context so never needs to be transformed.
17359 // FIXME: Ideally we wouldn't transform the closure type either, and would
17360 // just recreate the capture expressions and lambda expression.
17361 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17362 return SkipLambdaBody(E, Body);
17363 }
17364 };
17365}
17366
17368 assert(isUnevaluatedContext() &&
17369 "Should only transform unevaluated expressions");
17370 ExprEvalContexts.back().Context =
17371 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17373 return E;
17374 return TransformToPE(*this).TransformExpr(E);
17375}
17376
17378 assert(isUnevaluatedContext() &&
17379 "Should only transform unevaluated expressions");
17382 return TInfo;
17383 return TransformToPE(*this).TransformType(TInfo);
17384}
17385
17386void
17388 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17390 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17391 LambdaContextDecl, ExprContext);
17392
17393 // Discarded statements and immediate contexts nested in other
17394 // discarded statements or immediate context are themselves
17395 // a discarded statement or an immediate context, respectively.
17396 ExprEvalContexts.back().InDiscardedStatement =
17398
17399 // C++23 [expr.const]/p15
17400 // An expression or conversion is in an immediate function context if [...]
17401 // it is a subexpression of a manifestly constant-evaluated expression or
17402 // conversion.
17403 const auto &Prev = parentEvaluationContext();
17404 ExprEvalContexts.back().InImmediateFunctionContext =
17405 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17406
17407 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17408 Prev.InImmediateEscalatingFunctionContext;
17409
17410 Cleanup.reset();
17411 if (!MaybeODRUseExprs.empty())
17412 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17413}
17414
17415void
17419 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17420 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17421}
17422
17423namespace {
17424
17425const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17426 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17427 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17428 if (E->getOpcode() == UO_Deref)
17429 return CheckPossibleDeref(S, E->getSubExpr());
17430 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17431 return CheckPossibleDeref(S, E->getBase());
17432 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17433 return CheckPossibleDeref(S, E->getBase());
17434 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17435 QualType Inner;
17436 QualType Ty = E->getType();
17437 if (const auto *Ptr = Ty->getAs<PointerType>())
17438 Inner = Ptr->getPointeeType();
17439 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17440 Inner = Arr->getElementType();
17441 else
17442 return nullptr;
17443
17444 if (Inner->hasAttr(attr::NoDeref))
17445 return E;
17446 }
17447 return nullptr;
17448}
17449
17450} // namespace
17451
17453 for (const Expr *E : Rec.PossibleDerefs) {
17454 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17455 if (DeclRef) {
17456 const ValueDecl *Decl = DeclRef->getDecl();
17457 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17458 << Decl->getName() << E->getSourceRange();
17459 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17460 } else {
17461 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17462 << E->getSourceRange();
17463 }
17464 }
17465 Rec.PossibleDerefs.clear();
17466}
17467
17470 return;
17471
17472 // Note: ignoring parens here is not justified by the standard rules, but
17473 // ignoring parentheses seems like a more reasonable approach, and this only
17474 // drives a deprecation warning so doesn't affect conformance.
17475 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17476 if (BO->getOpcode() == BO_Assign) {
17477 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17478 llvm::erase(LHSs, BO->getLHS());
17479 }
17480 }
17481}
17482
17484 assert(getLangOpts().CPlusPlus20 &&
17485 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17486 "Cannot mark an immediate escalating expression outside of an "
17487 "immediate escalating context");
17488 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
17489 Call && Call->getCallee()) {
17490 if (auto *DeclRef =
17491 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17492 DeclRef->setIsImmediateEscalating(true);
17493 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
17494 Ctr->setIsImmediateEscalating(true);
17495 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
17496 DeclRef->setIsImmediateEscalating(true);
17497 } else {
17498 assert(false && "expected an immediately escalating expression");
17499 }
17501 FI->FoundImmediateEscalatingExpression = true;
17502}
17503
17505 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17506 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
17509 return E;
17510
17511 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17512 /// It's OK if this fails; we'll also remove this in
17513 /// HandleImmediateInvocations, but catching it here allows us to avoid
17514 /// walking the AST looking for it in simple cases.
17515 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17516 if (auto *DeclRef =
17517 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17518 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17519
17520 // C++23 [expr.const]/p16
17521 // An expression or conversion is immediate-escalating if it is not initially
17522 // in an immediate function context and it is [...] an immediate invocation
17523 // that is not a constant expression and is not a subexpression of an
17524 // immediate invocation.
17525 APValue Cached;
17526 auto CheckConstantExpressionAndKeepResult = [&]() {
17528 Expr::EvalResult Eval;
17529 Eval.Diag = &Notes;
17530 bool Res = E.get()->EvaluateAsConstantExpr(
17531 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
17532 if (Res && Notes.empty()) {
17533 Cached = std::move(Eval.Val);
17534 return true;
17535 }
17536 return false;
17537 };
17538
17539 if (!E.get()->isValueDependent() &&
17540 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17541 !CheckConstantExpressionAndKeepResult()) {
17543 return E;
17544 }
17545
17546 if (Cleanup.exprNeedsCleanups()) {
17547 // Since an immediate invocation is a full expression itself - it requires
17548 // an additional ExprWithCleanups node, but it can participate to a bigger
17549 // full expression which actually requires cleanups to be run after so
17550 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
17551 // may discard cleanups for outer expression too early.
17552
17553 // Note that ExprWithCleanups created here must always have empty cleanup
17554 // objects:
17555 // - compound literals do not create cleanup objects in C++ and immediate
17556 // invocations are C++-only.
17557 // - blocks are not allowed inside constant expressions and compiler will
17558 // issue an error if they appear there.
17559 //
17560 // Hence, in correct code any cleanup objects created inside current
17561 // evaluation context must be outside the immediate invocation.
17564 }
17565
17567 getASTContext(), E.get(),
17568 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17569 getASTContext()),
17570 /*IsImmediateInvocation*/ true);
17571 if (Cached.hasValue())
17572 Res->MoveIntoResult(Cached, getASTContext());
17573 /// Value-dependent constant expressions should not be immediately
17574 /// evaluated until they are instantiated.
17575 if (!Res->isValueDependent())
17576 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17577 return Res;
17578}
17579
17583 Expr::EvalResult Eval;
17584 Eval.Diag = &Notes;
17585 ConstantExpr *CE = Candidate.getPointer();
17586 bool Result = CE->EvaluateAsConstantExpr(
17587 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17588 if (!Result || !Notes.empty()) {
17590 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17591 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17592 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
17593 FunctionDecl *FD = nullptr;
17594 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17595 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17596 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17597 FD = Call->getConstructor();
17598 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
17599 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
17600
17601 assert(FD && FD->isImmediateFunction() &&
17602 "could not find an immediate function in this expression");
17603 if (FD->isInvalidDecl())
17604 return;
17605 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
17606 << FD << FD->isConsteval();
17607 if (auto Context =
17609 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17610 << Context->Decl;
17611 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17612 }
17613 if (!FD->isConsteval())
17615 for (auto &Note : Notes)
17616 SemaRef.Diag(Note.first, Note.second);
17617 return;
17618 }
17620}
17621
17625 struct ComplexRemove : TreeTransform<ComplexRemove> {
17627 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17630 CurrentII;
17631 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17634 4>::reverse_iterator Current)
17635 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17636 void RemoveImmediateInvocation(ConstantExpr* E) {
17637 auto It = std::find_if(CurrentII, IISet.rend(),
17639 return Elem.getPointer() == E;
17640 });
17641 // It is possible that some subexpression of the current immediate
17642 // invocation was handled from another expression evaluation context. Do
17643 // not handle the current immediate invocation if some of its
17644 // subexpressions failed before.
17645 if (It == IISet.rend()) {
17646 if (SemaRef.FailedImmediateInvocations.contains(E))
17647 CurrentII->setInt(1);
17648 } else {
17649 It->setInt(1); // Mark as deleted
17650 }
17651 }
17652 ExprResult TransformConstantExpr(ConstantExpr *E) {
17653 if (!E->isImmediateInvocation())
17654 return Base::TransformConstantExpr(E);
17655 RemoveImmediateInvocation(E);
17656 return Base::TransformExpr(E->getSubExpr());
17657 }
17658 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17659 /// we need to remove its DeclRefExpr from the DRSet.
17660 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17661 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17662 return Base::TransformCXXOperatorCallExpr(E);
17663 }
17664 /// Base::TransformUserDefinedLiteral doesn't preserve the
17665 /// UserDefinedLiteral node.
17666 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
17667 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
17668 /// here.
17669 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17670 if (!Init)
17671 return Init;
17672
17673 // We cannot use IgnoreImpCasts because we need to preserve
17674 // full expressions.
17675 while (true) {
17676 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
17677 Init = ICE->getSubExpr();
17678 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
17679 Init = ICE->getSubExpr();
17680 else
17681 break;
17682 }
17683 /// ConstantExprs are the first layer of implicit node to be removed so if
17684 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17685 if (auto *CE = dyn_cast<ConstantExpr>(Init);
17686 CE && CE->isImmediateInvocation())
17687 RemoveImmediateInvocation(CE);
17688 return Base::TransformInitializer(Init, NotCopyInit);
17689 }
17690 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17691 DRSet.erase(E);
17692 return E;
17693 }
17694 ExprResult TransformLambdaExpr(LambdaExpr *E) {
17695 // Do not rebuild lambdas to avoid creating a new type.
17696 // Lambdas have already been processed inside their eval contexts.
17697 return E;
17698 }
17699 bool AlwaysRebuild() { return false; }
17700 bool ReplacingOriginal() { return true; }
17701 bool AllowSkippingCXXConstructExpr() {
17702 bool Res = AllowSkippingFirstCXXConstructExpr;
17703 AllowSkippingFirstCXXConstructExpr = true;
17704 return Res;
17705 }
17706 bool AllowSkippingFirstCXXConstructExpr = true;
17707 } Transformer(SemaRef, Rec.ReferenceToConsteval,
17709
17710 /// CXXConstructExpr with a single argument are getting skipped by
17711 /// TreeTransform in some situtation because they could be implicit. This
17712 /// can only occur for the top-level CXXConstructExpr because it is used
17713 /// nowhere in the expression being transformed therefore will not be rebuilt.
17714 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17715 /// skipping the first CXXConstructExpr.
17716 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17717 Transformer.AllowSkippingFirstCXXConstructExpr = false;
17718
17719 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17720 // The result may not be usable in case of previous compilation errors.
17721 // In this case evaluation of the expression may result in crash so just
17722 // don't do anything further with the result.
17723 if (Res.isUsable()) {
17725 It->getPointer()->setSubExpr(Res.get());
17726 }
17727}
17728
17729static void
17732 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17733 Rec.ReferenceToConsteval.size() == 0) ||
17735 return;
17736
17737 /// When we have more than 1 ImmediateInvocationCandidates or previously
17738 /// failed immediate invocations, we need to check for nested
17739 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
17740 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
17741 /// invocation.
17742 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
17744
17745 /// Prevent sema calls during the tree transform from adding pointers that
17746 /// are already in the sets.
17747 llvm::SaveAndRestore DisableIITracking(
17749
17750 /// Prevent diagnostic during tree transfrom as they are duplicates
17752
17753 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17754 It != Rec.ImmediateInvocationCandidates.rend(); It++)
17755 if (!It->getInt())
17757 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17758 Rec.ReferenceToConsteval.size()) {
17759 struct SimpleRemove : DynamicRecursiveASTVisitor {
17760 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17761 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17762 bool VisitDeclRefExpr(DeclRefExpr *E) override {
17763 DRSet.erase(E);
17764 return DRSet.size();
17765 }
17766 } Visitor(Rec.ReferenceToConsteval);
17767 Visitor.TraverseStmt(
17768 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17769 }
17770 for (auto CE : Rec.ImmediateInvocationCandidates)
17771 if (!CE.getInt())
17773 for (auto *DR : Rec.ReferenceToConsteval) {
17774 // If the expression is immediate escalating, it is not an error;
17775 // The outer context itself becomes immediate and further errors,
17776 // if any, will be handled by DiagnoseImmediateEscalatingReason.
17777 if (DR->isImmediateEscalating())
17778 continue;
17779 auto *FD = cast<FunctionDecl>(DR->getDecl());
17780 const NamedDecl *ND = FD;
17781 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
17782 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
17783 ND = MD->getParent();
17784
17785 // C++23 [expr.const]/p16
17786 // An expression or conversion is immediate-escalating if it is not
17787 // initially in an immediate function context and it is [...] a
17788 // potentially-evaluated id-expression that denotes an immediate function
17789 // that is not a subexpression of an immediate invocation.
17790 bool ImmediateEscalating = false;
17791 bool IsPotentiallyEvaluated =
17792 Rec.Context ==
17794 Rec.Context ==
17796 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
17797 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
17798
17800 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
17801 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17802 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
17803 if (!FD->getBuiltinID())
17804 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
17805 if (auto Context =
17807 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17808 << Context->Decl;
17809 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17810 }
17811 if (FD->isImmediateEscalating() && !FD->isConsteval())
17813
17814 } else {
17816 }
17817 }
17818}
17819
17822 unsigned NumTypos = Rec.NumTypos;
17823
17824 if (!Rec.Lambdas.empty()) {
17826 if (!getLangOpts().CPlusPlus20 &&
17827 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17828 Rec.isUnevaluated() ||
17830 unsigned D;
17831 if (Rec.isUnevaluated()) {
17832 // C++11 [expr.prim.lambda]p2:
17833 // A lambda-expression shall not appear in an unevaluated operand
17834 // (Clause 5).
17835 D = diag::err_lambda_unevaluated_operand;
17836 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17837 // C++1y [expr.const]p2:
17838 // A conditional-expression e is a core constant expression unless the
17839 // evaluation of e, following the rules of the abstract machine, would
17840 // evaluate [...] a lambda-expression.
17841 D = diag::err_lambda_in_constant_expression;
17842 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17843 // C++17 [expr.prim.lamda]p2:
17844 // A lambda-expression shall not appear [...] in a template-argument.
17845 D = diag::err_lambda_in_invalid_context;
17846 } else
17847 llvm_unreachable("Couldn't infer lambda error message.");
17848
17849 for (const auto *L : Rec.Lambdas)
17850 Diag(L->getBeginLoc(), D);
17851 }
17852 }
17853
17854 // Append the collected materialized temporaries into previous context before
17855 // exit if the previous also is a lifetime extending context.
17857 parentEvaluationContext().InLifetimeExtendingContext &&
17858 !Rec.ForRangeLifetimeExtendTemps.empty()) {
17861 }
17862
17864 HandleImmediateInvocations(*this, Rec);
17865
17866 // Warn on any volatile-qualified simple-assignments that are not discarded-
17867 // value expressions nor unevaluated operands (those cases get removed from
17868 // this list by CheckUnusedVolatileAssignment).
17869 for (auto *BO : Rec.VolatileAssignmentLHSs)
17870 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17871 << BO->getType();
17872
17873 // When are coming out of an unevaluated context, clear out any
17874 // temporaries that we may have created as part of the evaluation of
17875 // the expression in that context: they aren't relevant because they
17876 // will never be constructed.
17877 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17879 ExprCleanupObjects.end());
17880 Cleanup = Rec.ParentCleanup;
17883 // Otherwise, merge the contexts together.
17884 } else {
17886 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17887 Rec.SavedMaybeODRUseExprs.end());
17888 }
17889
17890 // Pop the current expression evaluation context off the stack.
17891 ExprEvalContexts.pop_back();
17892
17893 // The global expression evaluation context record is never popped.
17894 ExprEvalContexts.back().NumTypos += NumTypos;
17895}
17896
17898 ExprCleanupObjects.erase(
17899 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17900 ExprCleanupObjects.end());
17901 Cleanup.reset();
17902 MaybeODRUseExprs.clear();
17903}
17904
17907 if (Result.isInvalid())
17908 return ExprError();
17909 E = Result.get();
17910 if (!E->getType()->isVariablyModifiedType())
17911 return E;
17913}
17914
17915/// Are we in a context that is potentially constant evaluated per C++20
17916/// [expr.const]p12?
17918 /// C++2a [expr.const]p12:
17919 // An expression or conversion is potentially constant evaluated if it is
17920 switch (SemaRef.ExprEvalContexts.back().Context) {
17923
17924 // -- a manifestly constant-evaluated expression,
17928 // -- a potentially-evaluated expression,
17930 // -- an immediate subexpression of a braced-init-list,
17931
17932 // -- [FIXME] an expression of the form & cast-expression that occurs
17933 // within a templated entity
17934 // -- a subexpression of one of the above that is not a subexpression of
17935 // a nested unevaluated operand.
17936 return true;
17937
17940 // Expressions in this context are never evaluated.
17941 return false;
17942 }
17943 llvm_unreachable("Invalid context");
17944}
17945
17946/// Return true if this function has a calling convention that requires mangling
17947/// in the size of the parameter pack.
17949 // These manglings don't do anything on non-Windows or non-x86 platforms, so
17950 // we don't need parameter type sizes.
17951 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17952 if (!TT.isOSWindows() || !TT.isX86())
17953 return false;
17954
17955 // If this is C++ and this isn't an extern "C" function, parameters do not
17956 // need to be complete. In this case, C++ mangling will apply, which doesn't
17957 // use the size of the parameters.
17958 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17959 return false;
17960
17961 // Stdcall, fastcall, and vectorcall need this special treatment.
17962 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17963 switch (CC) {
17964 case CC_X86StdCall:
17965 case CC_X86FastCall:
17966 case CC_X86VectorCall:
17967 return true;
17968 default:
17969 break;
17970 }
17971 return false;
17972}
17973
17974/// Require that all of the parameter types of function be complete. Normally,
17975/// parameter types are only required to be complete when a function is called
17976/// or defined, but to mangle functions with certain calling conventions, the
17977/// mangler needs to know the size of the parameter list. In this situation,
17978/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17979/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17980/// result in a linker error. Clang doesn't implement this behavior, and instead
17981/// attempts to error at compile time.
17984 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
17985 FunctionDecl *FD;
17986 ParmVarDecl *Param;
17987
17988 public:
17989 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
17990 : FD(FD), Param(Param) {}
17991
17992 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
17993 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17994 StringRef CCName;
17995 switch (CC) {
17996 case CC_X86StdCall:
17997 CCName = "stdcall";
17998 break;
17999 case CC_X86FastCall:
18000 CCName = "fastcall";
18001 break;
18002 case CC_X86VectorCall:
18003 CCName = "vectorcall";
18004 break;
18005 default:
18006 llvm_unreachable("CC does not need mangling");
18007 }
18008
18009 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18010 << Param->getDeclName() << FD->getDeclName() << CCName;
18011 }
18012 };
18013
18014 for (ParmVarDecl *Param : FD->parameters()) {
18015 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18016 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18017 }
18018}
18019
18020namespace {
18021enum class OdrUseContext {
18022 /// Declarations in this context are not odr-used.
18023 None,
18024 /// Declarations in this context are formally odr-used, but this is a
18025 /// dependent context.
18026 Dependent,
18027 /// Declarations in this context are odr-used but not actually used (yet).
18028 FormallyOdrUsed,
18029 /// Declarations in this context are used.
18030 Used
18031};
18032}
18033
18034/// Are we within a context in which references to resolved functions or to
18035/// variables result in odr-use?
18036static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18037 OdrUseContext Result;
18038
18039 switch (SemaRef.ExprEvalContexts.back().Context) {
18043 return OdrUseContext::None;
18044
18048 Result = OdrUseContext::Used;
18049 break;
18050
18052 Result = OdrUseContext::FormallyOdrUsed;
18053 break;
18054
18056 // A default argument formally results in odr-use, but doesn't actually
18057 // result in a use in any real sense until it itself is used.
18058 Result = OdrUseContext::FormallyOdrUsed;
18059 break;
18060 }
18061
18063 return OdrUseContext::Dependent;
18064
18065 return Result;
18066}
18067
18069 if (!Func->isConstexpr())
18070 return false;
18071
18072 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18073 return true;
18074 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18075 return CCD && CCD->getInheritedConstructor();
18076}
18077
18079 bool MightBeOdrUse) {
18080 assert(Func && "No function?");
18081
18082 Func->setReferenced();
18083
18084 // Recursive functions aren't really used until they're used from some other
18085 // context.
18086 bool IsRecursiveCall = CurContext == Func;
18087
18088 // C++11 [basic.def.odr]p3:
18089 // A function whose name appears as a potentially-evaluated expression is
18090 // odr-used if it is the unique lookup result or the selected member of a
18091 // set of overloaded functions [...].
18092 //
18093 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18094 // can just check that here.
18095 OdrUseContext OdrUse =
18096 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18097 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18098 OdrUse = OdrUseContext::FormallyOdrUsed;
18099
18100 // Trivial default constructors and destructors are never actually used.
18101 // FIXME: What about other special members?
18102 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18103 OdrUse == OdrUseContext::Used) {
18104 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18105 if (Constructor->isDefaultConstructor())
18106 OdrUse = OdrUseContext::FormallyOdrUsed;
18107 if (isa<CXXDestructorDecl>(Func))
18108 OdrUse = OdrUseContext::FormallyOdrUsed;
18109 }
18110
18111 // C++20 [expr.const]p12:
18112 // A function [...] is needed for constant evaluation if it is [...] a
18113 // constexpr function that is named by an expression that is potentially
18114 // constant evaluated
18115 bool NeededForConstantEvaluation =
18118
18119 // Determine whether we require a function definition to exist, per
18120 // C++11 [temp.inst]p3:
18121 // Unless a function template specialization has been explicitly
18122 // instantiated or explicitly specialized, the function template
18123 // specialization is implicitly instantiated when the specialization is
18124 // referenced in a context that requires a function definition to exist.
18125 // C++20 [temp.inst]p7:
18126 // The existence of a definition of a [...] function is considered to
18127 // affect the semantics of the program if the [...] function is needed for
18128 // constant evaluation by an expression
18129 // C++20 [basic.def.odr]p10:
18130 // Every program shall contain exactly one definition of every non-inline
18131 // function or variable that is odr-used in that program outside of a
18132 // discarded statement
18133 // C++20 [special]p1:
18134 // The implementation will implicitly define [defaulted special members]
18135 // if they are odr-used or needed for constant evaluation.
18136 //
18137 // Note that we skip the implicit instantiation of templates that are only
18138 // used in unused default arguments or by recursive calls to themselves.
18139 // This is formally non-conforming, but seems reasonable in practice.
18140 bool NeedDefinition =
18141 !IsRecursiveCall &&
18142 (OdrUse == OdrUseContext::Used ||
18143 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18144
18145 // C++14 [temp.expl.spec]p6:
18146 // If a template [...] is explicitly specialized then that specialization
18147 // shall be declared before the first use of that specialization that would
18148 // cause an implicit instantiation to take place, in every translation unit
18149 // in which such a use occurs
18150 if (NeedDefinition &&
18151 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18152 Func->getMemberSpecializationInfo()))
18154
18155 if (getLangOpts().CUDA)
18156 CUDA().CheckCall(Loc, Func);
18157
18158 // If we need a definition, try to create one.
18159 if (NeedDefinition && !Func->getBody()) {
18161 if (CXXConstructorDecl *Constructor =
18162 dyn_cast<CXXConstructorDecl>(Func)) {
18163 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18164 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18165 if (Constructor->isDefaultConstructor()) {
18166 if (Constructor->isTrivial() &&
18167 !Constructor->hasAttr<DLLExportAttr>())
18168 return;
18170 } else if (Constructor->isCopyConstructor()) {
18171 DefineImplicitCopyConstructor(Loc, Constructor);
18172 } else if (Constructor->isMoveConstructor()) {
18173 DefineImplicitMoveConstructor(Loc, Constructor);
18174 }
18175 } else if (Constructor->getInheritedConstructor()) {
18176 DefineInheritingConstructor(Loc, Constructor);
18177 }
18178 } else if (CXXDestructorDecl *Destructor =
18179 dyn_cast<CXXDestructorDecl>(Func)) {
18180 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18181 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18182 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18183 return;
18185 }
18186 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18187 MarkVTableUsed(Loc, Destructor->getParent());
18188 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18189 if (MethodDecl->isOverloadedOperator() &&
18190 MethodDecl->getOverloadedOperator() == OO_Equal) {
18191 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18192 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18193 if (MethodDecl->isCopyAssignmentOperator())
18194 DefineImplicitCopyAssignment(Loc, MethodDecl);
18195 else if (MethodDecl->isMoveAssignmentOperator())
18196 DefineImplicitMoveAssignment(Loc, MethodDecl);
18197 }
18198 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18199 MethodDecl->getParent()->isLambda()) {
18200 CXXConversionDecl *Conversion =
18201 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18202 if (Conversion->isLambdaToBlockPointerConversion())
18204 else
18206 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18207 MarkVTableUsed(Loc, MethodDecl->getParent());
18208 }
18209
18210 if (Func->isDefaulted() && !Func->isDeleted()) {
18214 }
18215
18216 // Implicit instantiation of function templates and member functions of
18217 // class templates.
18218 if (Func->isImplicitlyInstantiable()) {
18220 Func->getTemplateSpecializationKindForInstantiation();
18221 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18222 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18223 if (FirstInstantiation) {
18224 PointOfInstantiation = Loc;
18225 if (auto *MSI = Func->getMemberSpecializationInfo())
18226 MSI->setPointOfInstantiation(Loc);
18227 // FIXME: Notify listener.
18228 else
18229 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18230 } else if (TSK != TSK_ImplicitInstantiation) {
18231 // Use the point of use as the point of instantiation, instead of the
18232 // point of explicit instantiation (which we track as the actual point
18233 // of instantiation). This gives better backtraces in diagnostics.
18234 PointOfInstantiation = Loc;
18235 }
18236
18237 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18238 Func->isConstexpr()) {
18239 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18240 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18241 CodeSynthesisContexts.size())
18243 std::make_pair(Func, PointOfInstantiation));
18244 else if (Func->isConstexpr())
18245 // Do not defer instantiations of constexpr functions, to avoid the
18246 // expression evaluator needing to call back into Sema if it sees a
18247 // call to such a function.
18248 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18249 else {
18250 Func->setInstantiationIsPending(true);
18251 PendingInstantiations.push_back(
18252 std::make_pair(Func, PointOfInstantiation));
18253 if (llvm::isTimeTraceVerbose()) {
18254 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
18255 std::string Name;
18256 llvm::raw_string_ostream OS(Name);
18257 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
18258 /*Qualified=*/true);
18259 return Name;
18260 });
18261 }
18262 // Notify the consumer that a function was implicitly instantiated.
18264 }
18265 }
18266 } else {
18267 // Walk redefinitions, as some of them may be instantiable.
18268 for (auto *i : Func->redecls()) {
18269 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18270 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18271 }
18272 }
18273 });
18274 }
18275
18276 // If a constructor was defined in the context of a default parameter
18277 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18278 // context), its initializers may not be referenced yet.
18279 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18281 *this,
18282 Constructor->isImmediateFunction()
18285 Constructor);
18286 for (CXXCtorInitializer *Init : Constructor->inits()) {
18287 if (Init->isInClassMemberInitializer())
18288 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18289 MarkDeclarationsReferencedInExpr(Init->getInit());
18290 });
18291 }
18292 }
18293
18294 // C++14 [except.spec]p17:
18295 // An exception-specification is considered to be needed when:
18296 // - the function is odr-used or, if it appears in an unevaluated operand,
18297 // would be odr-used if the expression were potentially-evaluated;
18298 //
18299 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18300 // function is a pure virtual function we're calling, and in that case the
18301 // function was selected by overload resolution and we need to resolve its
18302 // exception specification for a different reason.
18303 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18306
18307 // A callee could be called by a host function then by a device function.
18308 // If we only try recording once, we will miss recording the use on device
18309 // side. Therefore keep trying until it is recorded.
18310 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18313
18314 // If this is the first "real" use, act on that.
18315 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18316 // Keep track of used but undefined functions.
18317 if (!Func->isDefined()) {
18318 if (mightHaveNonExternalLinkage(Func))
18319 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18320 else if (Func->getMostRecentDecl()->isInlined() &&
18321 !LangOpts.GNUInline &&
18322 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18323 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18325 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18326 }
18327
18328 // Some x86 Windows calling conventions mangle the size of the parameter
18329 // pack into the name. Computing the size of the parameters requires the
18330 // parameter types to be complete. Check that now.
18333
18334 // In the MS C++ ABI, the compiler emits destructor variants where they are
18335 // used. If the destructor is used here but defined elsewhere, mark the
18336 // virtual base destructors referenced. If those virtual base destructors
18337 // are inline, this will ensure they are defined when emitting the complete
18338 // destructor variant. This checking may be redundant if the destructor is
18339 // provided later in this TU.
18341 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18342 CXXRecordDecl *Parent = Dtor->getParent();
18343 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18345 }
18346 }
18347
18348 Func->markUsed(Context);
18349 }
18350}
18351
18352/// Directly mark a variable odr-used. Given a choice, prefer to use
18353/// MarkVariableReferenced since it does additional checks and then
18354/// calls MarkVarDeclODRUsed.
18355/// If the variable must be captured:
18356/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18357/// - else capture it in the DeclContext that maps to the
18358/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18359static void
18361 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18362 // Keep track of used but undefined variables.
18363 // FIXME: We shouldn't suppress this warning for static data members.
18364 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18365 assert(Var && "expected a capturable variable");
18366
18368 (!Var->isExternallyVisible() || Var->isInline() ||
18370 !(Var->isStaticDataMember() && Var->hasInit())) {
18372 if (old.isInvalid())
18373 old = Loc;
18374 }
18375 QualType CaptureType, DeclRefType;
18376 if (SemaRef.LangOpts.OpenMP)
18379 /*EllipsisLoc*/ SourceLocation(),
18380 /*BuildAndDiagnose*/ true, CaptureType,
18381 DeclRefType, FunctionScopeIndexToStopAt);
18382
18383 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18384 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18385 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
18386 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
18387 if (VarTarget == SemaCUDA::CVT_Host &&
18388 (UserTarget == CUDAFunctionTarget::Device ||
18389 UserTarget == CUDAFunctionTarget::HostDevice ||
18390 UserTarget == CUDAFunctionTarget::Global)) {
18391 // Diagnose ODR-use of host global variables in device functions.
18392 // Reference of device global variables in host functions is allowed
18393 // through shadow variables therefore it is not diagnosed.
18394 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18395 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18396 << /*host*/ 2 << /*variable*/ 1 << Var
18397 << llvm::to_underlying(UserTarget);
18399 Var->getType().isConstQualified()
18400 ? diag::note_cuda_const_var_unpromoted
18401 : diag::note_cuda_host_var);
18402 }
18403 } else if (VarTarget == SemaCUDA::CVT_Device &&
18404 !Var->hasAttr<CUDASharedAttr>() &&
18405 (UserTarget == CUDAFunctionTarget::Host ||
18406 UserTarget == CUDAFunctionTarget::HostDevice)) {
18407 // Record a CUDA/HIP device side variable if it is ODR-used
18408 // by host code. This is done conservatively, when the variable is
18409 // referenced in any of the following contexts:
18410 // - a non-function context
18411 // - a host function
18412 // - a host device function
18413 // This makes the ODR-use of the device side variable by host code to
18414 // be visible in the device compilation for the compiler to be able to
18415 // emit template variables instantiated by host code only and to
18416 // externalize the static device side variable ODR-used by host code.
18417 if (!Var->hasExternalStorage())
18419 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18420 (!FD || (!FD->getDescribedFunctionTemplate() &&
18424 }
18425 }
18426
18427 V->markUsed(SemaRef.Context);
18428}
18429
18432 unsigned CapturingScopeIndex) {
18433 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18434}
18435
18437 ValueDecl *var) {
18438 DeclContext *VarDC = var->getDeclContext();
18439
18440 // If the parameter still belongs to the translation unit, then
18441 // we're actually just using one parameter in the declaration of
18442 // the next.
18443 if (isa<ParmVarDecl>(var) &&
18444 isa<TranslationUnitDecl>(VarDC))
18445 return;
18446
18447 // For C code, don't diagnose about capture if we're not actually in code
18448 // right now; it's impossible to write a non-constant expression outside of
18449 // function context, so we'll get other (more useful) diagnostics later.
18450 //
18451 // For C++, things get a bit more nasty... it would be nice to suppress this
18452 // diagnostic for certain cases like using a local variable in an array bound
18453 // for a member of a local class, but the correct predicate is not obvious.
18454 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18455 return;
18456
18457 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18458 unsigned ContextKind = 3; // unknown
18459 if (isa<CXXMethodDecl>(VarDC) &&
18460 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18461 ContextKind = 2;
18462 } else if (isa<FunctionDecl>(VarDC)) {
18463 ContextKind = 0;
18464 } else if (isa<BlockDecl>(VarDC)) {
18465 ContextKind = 1;
18466 }
18467
18468 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18469 << var << ValueKind << ContextKind << VarDC;
18470 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18471 << var;
18472
18473 // FIXME: Add additional diagnostic info about class etc. which prevents
18474 // capture.
18475}
18476
18478 ValueDecl *Var,
18479 bool &SubCapturesAreNested,
18480 QualType &CaptureType,
18481 QualType &DeclRefType) {
18482 // Check whether we've already captured it.
18483 if (CSI->CaptureMap.count(Var)) {
18484 // If we found a capture, any subcaptures are nested.
18485 SubCapturesAreNested = true;
18486
18487 // Retrieve the capture type for this variable.
18488 CaptureType = CSI->getCapture(Var).getCaptureType();
18489
18490 // Compute the type of an expression that refers to this variable.
18491 DeclRefType = CaptureType.getNonReferenceType();
18492
18493 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18494 // are mutable in the sense that user can change their value - they are
18495 // private instances of the captured declarations.
18496 const Capture &Cap = CSI->getCapture(Var);
18497 // C++ [expr.prim.lambda]p10:
18498 // The type of such a data member is [...] an lvalue reference to the
18499 // referenced function type if the entity is a reference to a function.
18500 // [...]
18501 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
18502 !(isa<LambdaScopeInfo>(CSI) &&
18503 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
18504 !(isa<CapturedRegionScopeInfo>(CSI) &&
18505 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18506 DeclRefType.addConst();
18507 return true;
18508 }
18509 return false;
18510}
18511
18512// Only block literals, captured statements, and lambda expressions can
18513// capture; other scopes don't work.
18515 ValueDecl *Var,
18517 const bool Diagnose,
18518 Sema &S) {
18519 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18521
18522 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18523 if (Underlying) {
18524 if (Underlying->hasLocalStorage() && Diagnose)
18526 }
18527 return nullptr;
18528}
18529
18530// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18531// certain types of variables (unnamed, variably modified types etc.)
18532// so check for eligibility.
18534 SourceLocation Loc, const bool Diagnose,
18535 Sema &S) {
18536
18537 assert((isa<VarDecl, BindingDecl>(Var)) &&
18538 "Only variables and structured bindings can be captured");
18539
18540 bool IsBlock = isa<BlockScopeInfo>(CSI);
18541 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18542
18543 // Lambdas are not allowed to capture unnamed variables
18544 // (e.g. anonymous unions).
18545 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18546 // assuming that's the intent.
18547 if (IsLambda && !Var->getDeclName()) {
18548 if (Diagnose) {
18549 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18550 S.Diag(Var->getLocation(), diag::note_declared_at);
18551 }
18552 return false;
18553 }
18554
18555 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18556 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18557 if (Diagnose) {
18558 S.Diag(Loc, diag::err_ref_vm_type);
18559 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18560 }
18561 return false;
18562 }
18563 // Prohibit structs with flexible array members too.
18564 // We cannot capture what is in the tail end of the struct.
18565 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18566 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18567 if (Diagnose) {
18568 if (IsBlock)
18569 S.Diag(Loc, diag::err_ref_flexarray_type);
18570 else
18571 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18572 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18573 }
18574 return false;
18575 }
18576 }
18577 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18578 // Lambdas and captured statements are not allowed to capture __block
18579 // variables; they don't support the expected semantics.
18580 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18581 if (Diagnose) {
18582 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18583 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18584 }
18585 return false;
18586 }
18587 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18588 if (S.getLangOpts().OpenCL && IsBlock &&
18589 Var->getType()->isBlockPointerType()) {
18590 if (Diagnose)
18591 S.Diag(Loc, diag::err_opencl_block_ref_block);
18592 return false;
18593 }
18594
18595 if (isa<BindingDecl>(Var)) {
18596 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18597 if (Diagnose)
18599 return false;
18600 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18601 S.Diag(Loc, S.LangOpts.CPlusPlus20
18602 ? diag::warn_cxx17_compat_capture_binding
18603 : diag::ext_capture_binding)
18604 << Var;
18605 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18606 }
18607 }
18608
18609 return true;
18610}
18611
18612// Returns true if the capture by block was successful.
18614 SourceLocation Loc, const bool BuildAndDiagnose,
18615 QualType &CaptureType, QualType &DeclRefType,
18616 const bool Nested, Sema &S, bool Invalid) {
18617 bool ByRef = false;
18618
18619 // Blocks are not allowed to capture arrays, excepting OpenCL.
18620 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18621 // (decayed to pointers).
18622 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18623 if (BuildAndDiagnose) {
18624 S.Diag(Loc, diag::err_ref_array_type);
18625 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18626 Invalid = true;
18627 } else {
18628 return false;
18629 }
18630 }
18631
18632 // Forbid the block-capture of autoreleasing variables.
18633 if (!Invalid &&
18635 if (BuildAndDiagnose) {
18636 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18637 << /*block*/ 0;
18638 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18639 Invalid = true;
18640 } else {
18641 return false;
18642 }
18643 }
18644
18645 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18646 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18647 QualType PointeeTy = PT->getPointeeType();
18648
18649 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18651 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18652 if (BuildAndDiagnose) {
18653 SourceLocation VarLoc = Var->getLocation();
18654 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18655 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18656 }
18657 }
18658 }
18659
18660 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18661 if (HasBlocksAttr || CaptureType->isReferenceType() ||
18662 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
18663 // Block capture by reference does not change the capture or
18664 // declaration reference types.
18665 ByRef = true;
18666 } else {
18667 // Block capture by copy introduces 'const'.
18668 CaptureType = CaptureType.getNonReferenceType().withConst();
18669 DeclRefType = CaptureType;
18670 }
18671
18672 // Actually capture the variable.
18673 if (BuildAndDiagnose)
18674 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18675 CaptureType, Invalid);
18676
18677 return !Invalid;
18678}
18679
18680/// Capture the given variable in the captured region.
18683 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18684 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18685 bool IsTopScope, Sema &S, bool Invalid) {
18686 // By default, capture variables by reference.
18687 bool ByRef = true;
18688 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18689 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18690 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18691 // Using an LValue reference type is consistent with Lambdas (see below).
18692 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
18693 bool HasConst = DeclRefType.isConstQualified();
18694 DeclRefType = DeclRefType.getUnqualifiedType();
18695 // Don't lose diagnostics about assignments to const.
18696 if (HasConst)
18697 DeclRefType.addConst();
18698 }
18699 // Do not capture firstprivates in tasks.
18700 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
18701 RSI->OpenMPCaptureLevel) != OMPC_unknown)
18702 return true;
18703 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18704 RSI->OpenMPCaptureLevel);
18705 }
18706
18707 if (ByRef)
18708 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18709 else
18710 CaptureType = DeclRefType;
18711
18712 // Actually capture the variable.
18713 if (BuildAndDiagnose)
18714 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18715 Loc, SourceLocation(), CaptureType, Invalid);
18716
18717 return !Invalid;
18718}
18719
18720/// Capture the given variable in the lambda.
18722 SourceLocation Loc, const bool BuildAndDiagnose,
18723 QualType &CaptureType, QualType &DeclRefType,
18724 const bool RefersToCapturedVariable,
18725 const Sema::TryCaptureKind Kind,
18726 SourceLocation EllipsisLoc, const bool IsTopScope,
18727 Sema &S, bool Invalid) {
18728 // Determine whether we are capturing by reference or by value.
18729 bool ByRef = false;
18730 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18731 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18732 } else {
18733 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18734 }
18735
18736 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
18738 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
18739 Invalid = true;
18740 }
18741
18742 // Compute the type of the field that will capture this variable.
18743 if (ByRef) {
18744 // C++11 [expr.prim.lambda]p15:
18745 // An entity is captured by reference if it is implicitly or
18746 // explicitly captured but not captured by copy. It is
18747 // unspecified whether additional unnamed non-static data
18748 // members are declared in the closure type for entities
18749 // captured by reference.
18750 //
18751 // FIXME: It is not clear whether we want to build an lvalue reference
18752 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18753 // to do the former, while EDG does the latter. Core issue 1249 will
18754 // clarify, but for now we follow GCC because it's a more permissive and
18755 // easily defensible position.
18756 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18757 } else {
18758 // C++11 [expr.prim.lambda]p14:
18759 // For each entity captured by copy, an unnamed non-static
18760 // data member is declared in the closure type. The
18761 // declaration order of these members is unspecified. The type
18762 // of such a data member is the type of the corresponding
18763 // captured entity if the entity is not a reference to an
18764 // object, or the referenced type otherwise. [Note: If the
18765 // captured entity is a reference to a function, the
18766 // corresponding data member is also a reference to a
18767 // function. - end note ]
18768 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18769 if (!RefType->getPointeeType()->isFunctionType())
18770 CaptureType = RefType->getPointeeType();
18771 }
18772
18773 // Forbid the lambda copy-capture of autoreleasing variables.
18774 if (!Invalid &&
18776 if (BuildAndDiagnose) {
18777 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18778 S.Diag(Var->getLocation(), diag::note_previous_decl)
18779 << Var->getDeclName();
18780 Invalid = true;
18781 } else {
18782 return false;
18783 }
18784 }
18785
18786 // Make sure that by-copy captures are of a complete and non-abstract type.
18787 if (!Invalid && BuildAndDiagnose) {
18788 if (!CaptureType->isDependentType() &&
18790 Loc, CaptureType,
18791 diag::err_capture_of_incomplete_or_sizeless_type,
18792 Var->getDeclName()))
18793 Invalid = true;
18794 else if (S.RequireNonAbstractType(Loc, CaptureType,
18795 diag::err_capture_of_abstract_type))
18796 Invalid = true;
18797 }
18798 }
18799
18800 // Compute the type of a reference to this captured variable.
18801 if (ByRef)
18802 DeclRefType = CaptureType.getNonReferenceType();
18803 else {
18804 // C++ [expr.prim.lambda]p5:
18805 // The closure type for a lambda-expression has a public inline
18806 // function call operator [...]. This function call operator is
18807 // declared const (9.3.1) if and only if the lambda-expression's
18808 // parameter-declaration-clause is not followed by mutable.
18809 DeclRefType = CaptureType.getNonReferenceType();
18810 bool Const = LSI->lambdaCaptureShouldBeConst();
18811 // C++ [expr.prim.lambda]p10:
18812 // The type of such a data member is [...] an lvalue reference to the
18813 // referenced function type if the entity is a reference to a function.
18814 // [...]
18815 if (Const && !CaptureType->isReferenceType() &&
18816 !DeclRefType->isFunctionType())
18817 DeclRefType.addConst();
18818 }
18819
18820 // Add the capture.
18821 if (BuildAndDiagnose)
18822 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18823 Loc, EllipsisLoc, CaptureType, Invalid);
18824
18825 return !Invalid;
18826}
18827
18829 const ASTContext &Context) {
18830 // Offer a Copy fix even if the type is dependent.
18831 if (Var->getType()->isDependentType())
18832 return true;
18834 if (T.isTriviallyCopyableType(Context))
18835 return true;
18836 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18837
18838 if (!(RD = RD->getDefinition()))
18839 return false;
18840 if (RD->hasSimpleCopyConstructor())
18841 return true;
18842 if (RD->hasUserDeclaredCopyConstructor())
18843 for (CXXConstructorDecl *Ctor : RD->ctors())
18844 if (Ctor->isCopyConstructor())
18845 return !Ctor->isDeleted();
18846 }
18847 return false;
18848}
18849
18850/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18851/// default capture. Fixes may be omitted if they aren't allowed by the
18852/// standard, for example we can't emit a default copy capture fix-it if we
18853/// already explicitly copy capture capture another variable.
18855 ValueDecl *Var) {
18857 // Don't offer Capture by copy of default capture by copy fixes if Var is
18858 // known not to be copy constructible.
18859 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18860
18861 SmallString<32> FixBuffer;
18862 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18863 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18864 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18865 if (ShouldOfferCopyFix) {
18866 // Offer fixes to insert an explicit capture for the variable.
18867 // [] -> [VarName]
18868 // [OtherCapture] -> [OtherCapture, VarName]
18869 FixBuffer.assign({Separator, Var->getName()});
18870 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18871 << Var << /*value*/ 0
18872 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18873 }
18874 // As above but capture by reference.
18875 FixBuffer.assign({Separator, "&", Var->getName()});
18876 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18877 << Var << /*reference*/ 1
18878 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18879 }
18880
18881 // Only try to offer default capture if there are no captures excluding this
18882 // and init captures.
18883 // [this]: OK.
18884 // [X = Y]: OK.
18885 // [&A, &B]: Don't offer.
18886 // [A, B]: Don't offer.
18887 if (llvm::any_of(LSI->Captures, [](Capture &C) {
18888 return !C.isThisCapture() && !C.isInitCapture();
18889 }))
18890 return;
18891
18892 // The default capture specifiers, '=' or '&', must appear first in the
18893 // capture body.
18894 SourceLocation DefaultInsertLoc =
18896
18897 if (ShouldOfferCopyFix) {
18898 bool CanDefaultCopyCapture = true;
18899 // [=, *this] OK since c++17
18900 // [=, this] OK since c++20
18901 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18902 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18904 : false;
18905 // We can't use default capture by copy if any captures already specified
18906 // capture by copy.
18907 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18908 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18909 })) {
18910 FixBuffer.assign({"=", Separator});
18911 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18912 << /*value*/ 0
18913 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18914 }
18915 }
18916
18917 // We can't use default capture by reference if any captures already specified
18918 // capture by reference.
18919 if (llvm::none_of(LSI->Captures, [](Capture &C) {
18920 return !C.isInitCapture() && C.isReferenceCapture() &&
18921 !C.isThisCapture();
18922 })) {
18923 FixBuffer.assign({"&", Separator});
18924 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18925 << /*reference*/ 1
18926 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18927 }
18928}
18929
18931 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18932 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18933 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18934 // An init-capture is notionally from the context surrounding its
18935 // declaration, but its parent DC is the lambda class.
18936 DeclContext *VarDC = Var->getDeclContext();
18937 DeclContext *DC = CurContext;
18938
18939 // Skip past RequiresExprBodys because they don't constitute function scopes.
18940 while (DC->isRequiresExprBody())
18941 DC = DC->getParent();
18942
18943 // tryCaptureVariable is called every time a DeclRef is formed,
18944 // it can therefore have non-negigible impact on performances.
18945 // For local variables and when there is no capturing scope,
18946 // we can bailout early.
18947 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
18948 return true;
18949
18950 // Exception: Function parameters are not tied to the function's DeclContext
18951 // until we enter the function definition. Capturing them anyway would result
18952 // in an out-of-bounds error while traversing DC and its parents.
18953 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
18954 return true;
18955
18956 const auto *VD = dyn_cast<VarDecl>(Var);
18957 if (VD) {
18958 if (VD->isInitCapture())
18959 VarDC = VarDC->getParent();
18960 } else {
18962 }
18963 assert(VD && "Cannot capture a null variable");
18964
18965 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18966 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18967 // We need to sync up the Declaration Context with the
18968 // FunctionScopeIndexToStopAt
18969 if (FunctionScopeIndexToStopAt) {
18970 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
18971 unsigned FSIndex = FunctionScopes.size() - 1;
18972 // When we're parsing the lambda parameter list, the current DeclContext is
18973 // NOT the lambda but its parent. So move away the current LSI before
18974 // aligning DC and FunctionScopeIndexToStopAt.
18975 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
18976 FSIndex && LSI && !LSI->AfterParameterList)
18977 --FSIndex;
18978 assert(MaxFunctionScopesIndex <= FSIndex &&
18979 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
18980 "FunctionScopes.");
18981 while (FSIndex != MaxFunctionScopesIndex) {
18983 --FSIndex;
18984 }
18985 }
18986
18987 // Capture global variables if it is required to use private copy of this
18988 // variable.
18989 bool IsGlobal = !VD->hasLocalStorage();
18990 if (IsGlobal && !(LangOpts.OpenMP &&
18991 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
18992 MaxFunctionScopesIndex)))
18993 return true;
18994
18995 if (isa<VarDecl>(Var))
18996 Var = cast<VarDecl>(Var->getCanonicalDecl());
18997
18998 // Walk up the stack to determine whether we can capture the variable,
18999 // performing the "simple" checks that don't depend on type. We stop when
19000 // we've either hit the declared scope of the variable or find an existing
19001 // capture of that variable. We start from the innermost capturing-entity
19002 // (the DC) and ensure that all intervening capturing-entities
19003 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19004 // declcontext can either capture the variable or have already captured
19005 // the variable.
19006 CaptureType = Var->getType();
19007 DeclRefType = CaptureType.getNonReferenceType();
19008 bool Nested = false;
19009 bool Explicit = (Kind != TryCapture_Implicit);
19010 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19011 do {
19012
19013 LambdaScopeInfo *LSI = nullptr;
19014 if (!FunctionScopes.empty())
19015 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19016 FunctionScopes[FunctionScopesIndex]);
19017
19018 bool IsInScopeDeclarationContext =
19019 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19020
19021 if (LSI && !LSI->AfterParameterList) {
19022 // This allows capturing parameters from a default value which does not
19023 // seems correct
19024 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19025 return true;
19026 }
19027 // If the variable is declared in the current context, there is no need to
19028 // capture it.
19029 if (IsInScopeDeclarationContext &&
19030 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19031 return true;
19032
19033 // Only block literals, captured statements, and lambda expressions can
19034 // capture; other scopes don't work.
19035 DeclContext *ParentDC =
19036 !IsInScopeDeclarationContext
19037 ? DC->getParent()
19038 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19039 BuildAndDiagnose, *this);
19040 // We need to check for the parent *first* because, if we *have*
19041 // private-captured a global variable, we need to recursively capture it in
19042 // intermediate blocks, lambdas, etc.
19043 if (!ParentDC) {
19044 if (IsGlobal) {
19045 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19046 break;
19047 }
19048 return true;
19049 }
19050
19051 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19052 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
19053
19054 // Check whether we've already captured it.
19055 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19056 DeclRefType)) {
19057 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19058 break;
19059 }
19060
19061 // When evaluating some attributes (like enable_if) we might refer to a
19062 // function parameter appertaining to the same declaration as that
19063 // attribute.
19064 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19065 Parm && Parm->getDeclContext() == DC)
19066 return true;
19067
19068 // If we are instantiating a generic lambda call operator body,
19069 // we do not want to capture new variables. What was captured
19070 // during either a lambdas transformation or initial parsing
19071 // should be used.
19073 if (BuildAndDiagnose) {
19074 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19076 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19077 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19078 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19079 buildLambdaCaptureFixit(*this, LSI, Var);
19080 } else
19082 }
19083 return true;
19084 }
19085
19086 // Try to capture variable-length arrays types.
19087 if (Var->getType()->isVariablyModifiedType()) {
19088 // We're going to walk down into the type and look for VLA
19089 // expressions.
19090 QualType QTy = Var->getType();
19091 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19092 QTy = PVD->getOriginalType();
19094 }
19095
19096 if (getLangOpts().OpenMP) {
19097 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19098 // OpenMP private variables should not be captured in outer scope, so
19099 // just break here. Similarly, global variables that are captured in a
19100 // target region should not be captured outside the scope of the region.
19101 if (RSI->CapRegionKind == CR_OpenMP) {
19102 // FIXME: We should support capturing structured bindings in OpenMP.
19103 if (isa<BindingDecl>(Var)) {
19104 if (BuildAndDiagnose) {
19105 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19106 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19107 }
19108 return true;
19109 }
19110 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19111 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19112 // If the variable is private (i.e. not captured) and has variably
19113 // modified type, we still need to capture the type for correct
19114 // codegen in all regions, associated with the construct. Currently,
19115 // it is captured in the innermost captured region only.
19116 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19117 Var->getType()->isVariablyModifiedType()) {
19118 QualType QTy = Var->getType();
19119 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19120 QTy = PVD->getOriginalType();
19121 for (int I = 1,
19122 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
19123 I < E; ++I) {
19124 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19125 FunctionScopes[FunctionScopesIndex - I]);
19126 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19127 "Wrong number of captured regions associated with the "
19128 "OpenMP construct.");
19129 captureVariablyModifiedType(Context, QTy, OuterRSI);
19130 }
19131 }
19132 bool IsTargetCap =
19133 IsOpenMPPrivateDecl != OMPC_private &&
19134 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19135 RSI->OpenMPCaptureLevel);
19136 // Do not capture global if it is not privatized in outer regions.
19137 bool IsGlobalCap =
19138 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19139 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19140
19141 // When we detect target captures we are looking from inside the
19142 // target region, therefore we need to propagate the capture from the
19143 // enclosing region. Therefore, the capture is not initially nested.
19144 if (IsTargetCap)
19145 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19146 RSI->OpenMPLevel);
19147
19148 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19149 (IsGlobal && !IsGlobalCap)) {
19150 Nested = !IsTargetCap;
19151 bool HasConst = DeclRefType.isConstQualified();
19152 DeclRefType = DeclRefType.getUnqualifiedType();
19153 // Don't lose diagnostics about assignments to const.
19154 if (HasConst)
19155 DeclRefType.addConst();
19156 CaptureType = Context.getLValueReferenceType(DeclRefType);
19157 break;
19158 }
19159 }
19160 }
19161 }
19163 // No capture-default, and this is not an explicit capture
19164 // so cannot capture this variable.
19165 if (BuildAndDiagnose) {
19166 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19167 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19168 auto *LSI = cast<LambdaScopeInfo>(CSI);
19169 if (LSI->Lambda) {
19170 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19171 buildLambdaCaptureFixit(*this, LSI, Var);
19172 }
19173 // FIXME: If we error out because an outer lambda can not implicitly
19174 // capture a variable that an inner lambda explicitly captures, we
19175 // should have the inner lambda do the explicit capture - because
19176 // it makes for cleaner diagnostics later. This would purely be done
19177 // so that the diagnostic does not misleadingly claim that a variable
19178 // can not be captured by a lambda implicitly even though it is captured
19179 // explicitly. Suggestion:
19180 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19181 // at the function head
19182 // - cache the StartingDeclContext - this must be a lambda
19183 // - captureInLambda in the innermost lambda the variable.
19184 }
19185 return true;
19186 }
19187 Explicit = false;
19188 FunctionScopesIndex--;
19189 if (IsInScopeDeclarationContext)
19190 DC = ParentDC;
19191 } while (!VarDC->Equals(DC));
19192
19193 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19194 // computing the type of the capture at each step, checking type-specific
19195 // requirements, and adding captures if requested.
19196 // If the variable had already been captured previously, we start capturing
19197 // at the lambda nested within that one.
19198 bool Invalid = false;
19199 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19200 ++I) {
19201 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19202
19203 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19204 // certain types of variables (unnamed, variably modified types etc.)
19205 // so check for eligibility.
19206 if (!Invalid)
19207 Invalid =
19208 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19209
19210 // After encountering an error, if we're actually supposed to capture, keep
19211 // capturing in nested contexts to suppress any follow-on diagnostics.
19212 if (Invalid && !BuildAndDiagnose)
19213 return true;
19214
19215 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19216 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19217 DeclRefType, Nested, *this, Invalid);
19218 Nested = true;
19219 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19221 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19222 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19223 Nested = true;
19224 } else {
19225 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19226 Invalid =
19227 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19228 DeclRefType, Nested, Kind, EllipsisLoc,
19229 /*IsTopScope*/ I == N - 1, *this, Invalid);
19230 Nested = true;
19231 }
19232
19233 if (Invalid && !BuildAndDiagnose)
19234 return true;
19235 }
19236 return Invalid;
19237}
19238
19240 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19241 QualType CaptureType;
19242 QualType DeclRefType;
19243 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19244 /*BuildAndDiagnose=*/true, CaptureType,
19245 DeclRefType, nullptr);
19246}
19247
19249 QualType CaptureType;
19250 QualType DeclRefType;
19252 /*BuildAndDiagnose=*/false, CaptureType,
19253 DeclRefType, nullptr);
19254}
19255
19257 assert(Var && "Null value cannot be captured");
19258
19259 QualType CaptureType;
19260 QualType DeclRefType;
19261
19262 // Determine whether we can capture this variable.
19264 /*BuildAndDiagnose=*/false, CaptureType,
19265 DeclRefType, nullptr))
19266 return QualType();
19267
19268 return DeclRefType;
19269}
19270
19271namespace {
19272// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19273// The produced TemplateArgumentListInfo* points to data stored within this
19274// object, so should only be used in contexts where the pointer will not be
19275// used after the CopiedTemplateArgs object is destroyed.
19276class CopiedTemplateArgs {
19277 bool HasArgs;
19278 TemplateArgumentListInfo TemplateArgStorage;
19279public:
19280 template<typename RefExpr>
19281 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19282 if (HasArgs)
19283 E->copyTemplateArgumentsInto(TemplateArgStorage);
19284 }
19285 operator TemplateArgumentListInfo*()
19286#ifdef __has_cpp_attribute
19287#if __has_cpp_attribute(clang::lifetimebound)
19288 [[clang::lifetimebound]]
19289#endif
19290#endif
19291 {
19292 return HasArgs ? &TemplateArgStorage : nullptr;
19293 }
19294};
19295}
19296
19297/// Walk the set of potential results of an expression and mark them all as
19298/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19299///
19300/// \return A new expression if we found any potential results, ExprEmpty() if
19301/// not, and ExprError() if we diagnosed an error.
19303 NonOdrUseReason NOUR) {
19304 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19305 // an object that satisfies the requirements for appearing in a
19306 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19307 // is immediately applied." This function handles the lvalue-to-rvalue
19308 // conversion part.
19309 //
19310 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19311 // transform it into the relevant kind of non-odr-use node and rebuild the
19312 // tree of nodes leading to it.
19313 //
19314 // This is a mini-TreeTransform that only transforms a restricted subset of
19315 // nodes (and only certain operands of them).
19316
19317 // Rebuild a subexpression.
19318 auto Rebuild = [&](Expr *Sub) {
19319 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19320 };
19321
19322 // Check whether a potential result satisfies the requirements of NOUR.
19323 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19324 // Any entity other than a VarDecl is always odr-used whenever it's named
19325 // in a potentially-evaluated expression.
19326 auto *VD = dyn_cast<VarDecl>(D);
19327 if (!VD)
19328 return true;
19329
19330 // C++2a [basic.def.odr]p4:
19331 // A variable x whose name appears as a potentially-evalauted expression
19332 // e is odr-used by e unless
19333 // -- x is a reference that is usable in constant expressions, or
19334 // -- x is a variable of non-reference type that is usable in constant
19335 // expressions and has no mutable subobjects, and e is an element of
19336 // the set of potential results of an expression of
19337 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19338 // conversion is applied, or
19339 // -- x is a variable of non-reference type, and e is an element of the
19340 // set of potential results of a discarded-value expression to which
19341 // the lvalue-to-rvalue conversion is not applied
19342 //
19343 // We check the first bullet and the "potentially-evaluated" condition in
19344 // BuildDeclRefExpr. We check the type requirements in the second bullet
19345 // in CheckLValueToRValueConversionOperand below.
19346 switch (NOUR) {
19347 case NOUR_None:
19348 case NOUR_Unevaluated:
19349 llvm_unreachable("unexpected non-odr-use-reason");
19350
19351 case NOUR_Constant:
19352 // Constant references were handled when they were built.
19353 if (VD->getType()->isReferenceType())
19354 return true;
19355 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19356 if (RD->hasDefinition() && RD->hasMutableFields())
19357 return true;
19358 if (!VD->isUsableInConstantExpressions(S.Context))
19359 return true;
19360 break;
19361
19362 case NOUR_Discarded:
19363 if (VD->getType()->isReferenceType())
19364 return true;
19365 break;
19366 }
19367 return false;
19368 };
19369
19370 // Mark that this expression does not constitute an odr-use.
19371 auto MarkNotOdrUsed = [&] {
19372 S.MaybeODRUseExprs.remove(E);
19373 if (LambdaScopeInfo *LSI = S.getCurLambda())
19374 LSI->markVariableExprAsNonODRUsed(E);
19375 };
19376
19377 // C++2a [basic.def.odr]p2:
19378 // The set of potential results of an expression e is defined as follows:
19379 switch (E->getStmtClass()) {
19380 // -- If e is an id-expression, ...
19381 case Expr::DeclRefExprClass: {
19382 auto *DRE = cast<DeclRefExpr>(E);
19383 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19384 break;
19385
19386 // Rebuild as a non-odr-use DeclRefExpr.
19387 MarkNotOdrUsed();
19388 return DeclRefExpr::Create(
19389 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19390 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19391 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19392 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19393 }
19394
19395 case Expr::FunctionParmPackExprClass: {
19396 auto *FPPE = cast<FunctionParmPackExpr>(E);
19397 // If any of the declarations in the pack is odr-used, then the expression
19398 // as a whole constitutes an odr-use.
19399 for (VarDecl *D : *FPPE)
19400 if (IsPotentialResultOdrUsed(D))
19401 return ExprEmpty();
19402
19403 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19404 // nothing cares about whether we marked this as an odr-use, but it might
19405 // be useful for non-compiler tools.
19406 MarkNotOdrUsed();
19407 break;
19408 }
19409
19410 // -- If e is a subscripting operation with an array operand...
19411 case Expr::ArraySubscriptExprClass: {
19412 auto *ASE = cast<ArraySubscriptExpr>(E);
19413 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19414 if (!OldBase->getType()->isArrayType())
19415 break;
19416 ExprResult Base = Rebuild(OldBase);
19417 if (!Base.isUsable())
19418 return Base;
19419 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19420 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19421 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19422 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19423 ASE->getRBracketLoc());
19424 }
19425
19426 case Expr::MemberExprClass: {
19427 auto *ME = cast<MemberExpr>(E);
19428 // -- If e is a class member access expression [...] naming a non-static
19429 // data member...
19430 if (isa<FieldDecl>(ME->getMemberDecl())) {
19431 ExprResult Base = Rebuild(ME->getBase());
19432 if (!Base.isUsable())
19433 return Base;
19434 return MemberExpr::Create(
19435 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19436 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19437 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19438 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19439 ME->getObjectKind(), ME->isNonOdrUse());
19440 }
19441
19442 if (ME->getMemberDecl()->isCXXInstanceMember())
19443 break;
19444
19445 // -- If e is a class member access expression naming a static data member,
19446 // ...
19447 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19448 break;
19449
19450 // Rebuild as a non-odr-use MemberExpr.
19451 MarkNotOdrUsed();
19452 return MemberExpr::Create(
19453 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19454 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19455 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19456 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19457 }
19458
19459 case Expr::BinaryOperatorClass: {
19460 auto *BO = cast<BinaryOperator>(E);
19461 Expr *LHS = BO->getLHS();
19462 Expr *RHS = BO->getRHS();
19463 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19464 if (BO->getOpcode() == BO_PtrMemD) {
19465 ExprResult Sub = Rebuild(LHS);
19466 if (!Sub.isUsable())
19467 return Sub;
19468 BO->setLHS(Sub.get());
19469 // -- If e is a comma expression, ...
19470 } else if (BO->getOpcode() == BO_Comma) {
19471 ExprResult Sub = Rebuild(RHS);
19472 if (!Sub.isUsable())
19473 return Sub;
19474 BO->setRHS(Sub.get());
19475 } else {
19476 break;
19477 }
19478 return ExprResult(BO);
19479 }
19480
19481 // -- If e has the form (e1)...
19482 case Expr::ParenExprClass: {
19483 auto *PE = cast<ParenExpr>(E);
19484 ExprResult Sub = Rebuild(PE->getSubExpr());
19485 if (!Sub.isUsable())
19486 return Sub;
19487 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19488 }
19489
19490 // -- If e is a glvalue conditional expression, ...
19491 // We don't apply this to a binary conditional operator. FIXME: Should we?
19492 case Expr::ConditionalOperatorClass: {
19493 auto *CO = cast<ConditionalOperator>(E);
19494 ExprResult LHS = Rebuild(CO->getLHS());
19495 if (LHS.isInvalid())
19496 return ExprError();
19497 ExprResult RHS = Rebuild(CO->getRHS());
19498 if (RHS.isInvalid())
19499 return ExprError();
19500 if (!LHS.isUsable() && !RHS.isUsable())
19501 return ExprEmpty();
19502 if (!LHS.isUsable())
19503 LHS = CO->getLHS();
19504 if (!RHS.isUsable())
19505 RHS = CO->getRHS();
19506 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19507 CO->getCond(), LHS.get(), RHS.get());
19508 }
19509
19510 // [Clang extension]
19511 // -- If e has the form __extension__ e1...
19512 case Expr::UnaryOperatorClass: {
19513 auto *UO = cast<UnaryOperator>(E);
19514 if (UO->getOpcode() != UO_Extension)
19515 break;
19516 ExprResult Sub = Rebuild(UO->getSubExpr());
19517 if (!Sub.isUsable())
19518 return Sub;
19519 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19520 Sub.get());
19521 }
19522
19523 // [Clang extension]
19524 // -- If e has the form _Generic(...), the set of potential results is the
19525 // union of the sets of potential results of the associated expressions.
19526 case Expr::GenericSelectionExprClass: {
19527 auto *GSE = cast<GenericSelectionExpr>(E);
19528
19529 SmallVector<Expr *, 4> AssocExprs;
19530 bool AnyChanged = false;
19531 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19532 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19533 if (AssocExpr.isInvalid())
19534 return ExprError();
19535 if (AssocExpr.isUsable()) {
19536 AssocExprs.push_back(AssocExpr.get());
19537 AnyChanged = true;
19538 } else {
19539 AssocExprs.push_back(OrigAssocExpr);
19540 }
19541 }
19542
19543 void *ExOrTy = nullptr;
19544 bool IsExpr = GSE->isExprPredicate();
19545 if (IsExpr)
19546 ExOrTy = GSE->getControllingExpr();
19547 else
19548 ExOrTy = GSE->getControllingType();
19549 return AnyChanged ? S.CreateGenericSelectionExpr(
19550 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19551 GSE->getRParenLoc(), IsExpr, ExOrTy,
19552 GSE->getAssocTypeSourceInfos(), AssocExprs)
19553 : ExprEmpty();
19554 }
19555
19556 // [Clang extension]
19557 // -- If e has the form __builtin_choose_expr(...), the set of potential
19558 // results is the union of the sets of potential results of the
19559 // second and third subexpressions.
19560 case Expr::ChooseExprClass: {
19561 auto *CE = cast<ChooseExpr>(E);
19562
19563 ExprResult LHS = Rebuild(CE->getLHS());
19564 if (LHS.isInvalid())
19565 return ExprError();
19566
19567 ExprResult RHS = Rebuild(CE->getLHS());
19568 if (RHS.isInvalid())
19569 return ExprError();
19570
19571 if (!LHS.get() && !RHS.get())
19572 return ExprEmpty();
19573 if (!LHS.isUsable())
19574 LHS = CE->getLHS();
19575 if (!RHS.isUsable())
19576 RHS = CE->getRHS();
19577
19578 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19579 RHS.get(), CE->getRParenLoc());
19580 }
19581
19582 // Step through non-syntactic nodes.
19583 case Expr::ConstantExprClass: {
19584 auto *CE = cast<ConstantExpr>(E);
19585 ExprResult Sub = Rebuild(CE->getSubExpr());
19586 if (!Sub.isUsable())
19587 return Sub;
19588 return ConstantExpr::Create(S.Context, Sub.get());
19589 }
19590
19591 // We could mostly rely on the recursive rebuilding to rebuild implicit
19592 // casts, but not at the top level, so rebuild them here.
19593 case Expr::ImplicitCastExprClass: {
19594 auto *ICE = cast<ImplicitCastExpr>(E);
19595 // Only step through the narrow set of cast kinds we expect to encounter.
19596 // Anything else suggests we've left the region in which potential results
19597 // can be found.
19598 switch (ICE->getCastKind()) {
19599 case CK_NoOp:
19600 case CK_DerivedToBase:
19601 case CK_UncheckedDerivedToBase: {
19602 ExprResult Sub = Rebuild(ICE->getSubExpr());
19603 if (!Sub.isUsable())
19604 return Sub;
19605 CXXCastPath Path(ICE->path());
19606 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19607 ICE->getValueKind(), &Path);
19608 }
19609
19610 default:
19611 break;
19612 }
19613 break;
19614 }
19615
19616 default:
19617 break;
19618 }
19619
19620 // Can't traverse through this node. Nothing to do.
19621 return ExprEmpty();
19622}
19623
19625 // Check whether the operand is or contains an object of non-trivial C union
19626 // type.
19627 if (E->getType().isVolatileQualified() &&
19633
19634 // C++2a [basic.def.odr]p4:
19635 // [...] an expression of non-volatile-qualified non-class type to which
19636 // the lvalue-to-rvalue conversion is applied [...]
19638 return E;
19639
19642 if (Result.isInvalid())
19643 return ExprError();
19644 return Result.get() ? Result : E;
19645}
19646
19648 Res = CorrectDelayedTyposInExpr(Res);
19649
19650 if (!Res.isUsable())
19651 return Res;
19652
19653 // If a constant-expression is a reference to a variable where we delay
19654 // deciding whether it is an odr-use, just assume we will apply the
19655 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19656 // (a non-type template argument), we have special handling anyway.
19658}
19659
19661 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19662 // call.
19663 MaybeODRUseExprSet LocalMaybeODRUseExprs;
19664 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19665
19666 for (Expr *E : LocalMaybeODRUseExprs) {
19667 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19668 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19669 DRE->getLocation(), *this);
19670 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19671 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19672 *this);
19673 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19674 for (VarDecl *VD : *FP)
19675 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19676 } else {
19677 llvm_unreachable("Unexpected expression");
19678 }
19679 }
19680
19681 assert(MaybeODRUseExprs.empty() &&
19682 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19683}
19684
19686 ValueDecl *Var, Expr *E) {
19688 if (!VD)
19689 return;
19690
19691 const bool RefersToEnclosingScope =
19692 (SemaRef.CurContext != VD->getDeclContext() &&
19694 if (RefersToEnclosingScope) {
19695 LambdaScopeInfo *const LSI =
19696 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19697 if (LSI && (!LSI->CallOperator ||
19698 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19699 // If a variable could potentially be odr-used, defer marking it so
19700 // until we finish analyzing the full expression for any
19701 // lvalue-to-rvalue
19702 // or discarded value conversions that would obviate odr-use.
19703 // Add it to the list of potential captures that will be analyzed
19704 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19705 // unless the variable is a reference that was initialized by a constant
19706 // expression (this will never need to be captured or odr-used).
19707 //
19708 // FIXME: We can simplify this a lot after implementing P0588R1.
19709 assert(E && "Capture variable should be used in an expression.");
19710 if (!Var->getType()->isReferenceType() ||
19713 }
19714 }
19715}
19716
19719 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19720 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19721 isa<FunctionParmPackExpr>(E)) &&
19722 "Invalid Expr argument to DoMarkVarDeclReferenced");
19723 Var->setReferenced();
19724
19725 if (Var->isInvalidDecl())
19726 return;
19727
19728 auto *MSI = Var->getMemberSpecializationInfo();
19731
19732 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19733 bool UsableInConstantExpr =
19735
19736 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19737 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19738 }
19739
19740 // C++20 [expr.const]p12:
19741 // A variable [...] is needed for constant evaluation if it is [...] a
19742 // variable whose name appears as a potentially constant evaluated
19743 // expression that is either a contexpr variable or is of non-volatile
19744 // const-qualified integral type or of reference type
19745 bool NeededForConstantEvaluation =
19746 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19747
19748 bool NeedDefinition =
19749 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19750
19751 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19752 "Can't instantiate a partial template specialization.");
19753
19754 // If this might be a member specialization of a static data member, check
19755 // the specialization is visible. We already did the checks for variable
19756 // template specializations when we created them.
19757 if (NeedDefinition && TSK != TSK_Undeclared &&
19758 !isa<VarTemplateSpecializationDecl>(Var))
19760
19761 // Perform implicit instantiation of static data members, static data member
19762 // templates of class templates, and variable template specializations. Delay
19763 // instantiations of variable templates, except for those that could be used
19764 // in a constant expression.
19765 if (NeedDefinition && isTemplateInstantiation(TSK)) {
19766 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19767 // instantiation declaration if a variable is usable in a constant
19768 // expression (among other cases).
19769 bool TryInstantiating =
19771 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19772
19773 if (TryInstantiating) {
19774 SourceLocation PointOfInstantiation =
19775 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19776 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19777 if (FirstInstantiation) {
19778 PointOfInstantiation = Loc;
19779 if (MSI)
19780 MSI->setPointOfInstantiation(PointOfInstantiation);
19781 // FIXME: Notify listener.
19782 else
19783 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19784 }
19785
19786 if (UsableInConstantExpr) {
19787 // Do not defer instantiations of variables that could be used in a
19788 // constant expression.
19789 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19790 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19791 });
19792
19793 // Re-set the member to trigger a recomputation of the dependence bits
19794 // for the expression.
19795 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19796 DRE->setDecl(DRE->getDecl());
19797 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19798 ME->setMemberDecl(ME->getMemberDecl());
19799 } else if (FirstInstantiation) {
19801 .push_back(std::make_pair(Var, PointOfInstantiation));
19802 } else {
19803 bool Inserted = false;
19804 for (auto &I : SemaRef.SavedPendingInstantiations) {
19805 auto Iter = llvm::find_if(
19806 I, [Var](const Sema::PendingImplicitInstantiation &P) {
19807 return P.first == Var;
19808 });
19809 if (Iter != I.end()) {
19811 I.erase(Iter);
19812 Inserted = true;
19813 break;
19814 }
19815 }
19816
19817 // FIXME: For a specialization of a variable template, we don't
19818 // distinguish between "declaration and type implicitly instantiated"
19819 // and "implicit instantiation of definition requested", so we have
19820 // no direct way to avoid enqueueing the pending instantiation
19821 // multiple times.
19822 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
19824 .push_back(std::make_pair(Var, PointOfInstantiation));
19825 }
19826 }
19827 }
19828
19829 // C++2a [basic.def.odr]p4:
19830 // A variable x whose name appears as a potentially-evaluated expression e
19831 // is odr-used by e unless
19832 // -- x is a reference that is usable in constant expressions
19833 // -- x is a variable of non-reference type that is usable in constant
19834 // expressions and has no mutable subobjects [FIXME], and e is an
19835 // element of the set of potential results of an expression of
19836 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19837 // conversion is applied
19838 // -- x is a variable of non-reference type, and e is an element of the set
19839 // of potential results of a discarded-value expression to which the
19840 // lvalue-to-rvalue conversion is not applied [FIXME]
19841 //
19842 // We check the first part of the second bullet here, and
19843 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19844 // FIXME: To get the third bullet right, we need to delay this even for
19845 // variables that are not usable in constant expressions.
19846
19847 // If we already know this isn't an odr-use, there's nothing more to do.
19848 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19849 if (DRE->isNonOdrUse())
19850 return;
19851 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19852 if (ME->isNonOdrUse())
19853 return;
19854
19855 switch (OdrUse) {
19856 case OdrUseContext::None:
19857 // In some cases, a variable may not have been marked unevaluated, if it
19858 // appears in a defaukt initializer.
19859 assert((!E || isa<FunctionParmPackExpr>(E) ||
19861 "missing non-odr-use marking for unevaluated decl ref");
19862 break;
19863
19864 case OdrUseContext::FormallyOdrUsed:
19865 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19866 // behavior.
19867 break;
19868
19869 case OdrUseContext::Used:
19870 // If we might later find that this expression isn't actually an odr-use,
19871 // delay the marking.
19873 SemaRef.MaybeODRUseExprs.insert(E);
19874 else
19876 break;
19877
19878 case OdrUseContext::Dependent:
19879 // If this is a dependent context, we don't need to mark variables as
19880 // odr-used, but we may still need to track them for lambda capture.
19881 // FIXME: Do we also need to do this inside dependent typeid expressions
19882 // (which are modeled as unevaluated at this point)?
19884 break;
19885 }
19886}
19887
19889 BindingDecl *BD, Expr *E) {
19890 BD->setReferenced();
19891
19892 if (BD->isInvalidDecl())
19893 return;
19894
19895 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19896 if (OdrUse == OdrUseContext::Used) {
19897 QualType CaptureType, DeclRefType;
19899 /*EllipsisLoc*/ SourceLocation(),
19900 /*BuildAndDiagnose*/ true, CaptureType,
19901 DeclRefType,
19902 /*FunctionScopeIndexToStopAt*/ nullptr);
19903 } else if (OdrUse == OdrUseContext::Dependent) {
19905 }
19906}
19907
19909 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19910}
19911
19912// C++ [temp.dep.expr]p3:
19913// An id-expression is type-dependent if it contains:
19914// - an identifier associated by name lookup with an entity captured by copy
19915// in a lambda-expression that has an explicit object parameter whose type
19916// is dependent ([dcl.fct]),
19918 Sema &SemaRef, ValueDecl *D, Expr *E) {
19919 auto *ID = dyn_cast<DeclRefExpr>(E);
19920 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
19921 return;
19922
19923 // If any enclosing lambda with a dependent explicit object parameter either
19924 // explicitly captures the variable by value, or has a capture default of '='
19925 // and does not capture the variable by reference, then the type of the DRE
19926 // is dependent on the type of that lambda's explicit object parameter.
19927 auto IsDependent = [&]() {
19928 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
19929 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
19930 if (!LSI)
19931 continue;
19932
19933 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
19934 LSI->AfterParameterList)
19935 return false;
19936
19937 const auto *MD = LSI->CallOperator;
19938 if (MD->getType().isNull())
19939 continue;
19940
19941 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
19942 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
19943 !Ty->getParamType(0)->isDependentType())
19944 continue;
19945
19946 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
19947 if (C->isCopyCapture())
19948 return true;
19949 continue;
19950 }
19951
19952 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
19953 return true;
19954 }
19955 return false;
19956 }();
19957
19958 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
19959 IsDependent, SemaRef.getASTContext());
19960}
19961
19962static void
19964 bool MightBeOdrUse,
19965 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19968
19969 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19971 if (SemaRef.getLangOpts().CPlusPlus)
19973 Var, E);
19974 return;
19975 }
19976
19977 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
19979 if (SemaRef.getLangOpts().CPlusPlus)
19981 Decl, E);
19982 return;
19983 }
19984 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
19985
19986 // If this is a call to a method via a cast, also mark the method in the
19987 // derived class used in case codegen can devirtualize the call.
19988 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
19989 if (!ME)
19990 return;
19991 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
19992 if (!MD)
19993 return;
19994 // Only attempt to devirtualize if this is truly a virtual call.
19995 bool IsVirtualCall = MD->isVirtual() &&
19997 if (!IsVirtualCall)
19998 return;
19999
20000 // If it's possible to devirtualize the call, mark the called function
20001 // referenced.
20003 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20004 if (DM)
20005 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20006}
20007
20009 // TODO: update this with DR# once a defect report is filed.
20010 // C++11 defect. The address of a pure member should not be an ODR use, even
20011 // if it's a qualified reference.
20012 bool OdrUse = true;
20013 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20014 if (Method->isVirtual() &&
20015 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20016 OdrUse = false;
20017
20018 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20022 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20023 !FD->isDependentContext())
20024 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20025 }
20026 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20028}
20029
20031 // C++11 [basic.def.odr]p2:
20032 // A non-overloaded function whose name appears as a potentially-evaluated
20033 // expression or a member of a set of candidate functions, if selected by
20034 // overload resolution when referred to from a potentially-evaluated
20035 // expression, is odr-used, unless it is a pure virtual function and its
20036 // name is not explicitly qualified.
20037 bool MightBeOdrUse = true;
20038 if (E->performsVirtualDispatch(getLangOpts())) {
20039 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20040 if (Method->isPureVirtual())
20041 MightBeOdrUse = false;
20042 }
20044 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20045 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20047}
20048
20050 for (VarDecl *VD : *E)
20051 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20053}
20054
20055/// Perform marking for a reference to an arbitrary declaration. It
20056/// marks the declaration referenced, and performs odr-use checking for
20057/// functions and variables. This method should not be used when building a
20058/// normal expression which refers to a variable.
20060 bool MightBeOdrUse) {
20061 if (MightBeOdrUse) {
20062 if (auto *VD = dyn_cast<VarDecl>(D)) {
20064 return;
20065 }
20066 }
20067 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20068 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20069 return;
20070 }
20071 D->setReferenced();
20072}
20073
20074namespace {
20075 // Mark all of the declarations used by a type as referenced.
20076 // FIXME: Not fully implemented yet! We need to have a better understanding
20077 // of when we're entering a context we should not recurse into.
20078 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20079 // TreeTransforms rebuilding the type in a new context. Rather than
20080 // duplicating the TreeTransform logic, we should consider reusing it here.
20081 // Currently that causes problems when rebuilding LambdaExprs.
20082class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20083 Sema &S;
20085
20086public:
20087 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20088
20089 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20090};
20091}
20092
20093bool MarkReferencedDecls::TraverseTemplateArgument(
20094 const TemplateArgument &Arg) {
20095 {
20096 // A non-type template argument is a constant-evaluated context.
20100 if (Decl *D = Arg.getAsDecl())
20101 S.MarkAnyDeclReferenced(Loc, D, true);
20102 } else if (Arg.getKind() == TemplateArgument::Expression) {
20104 }
20105 }
20106
20108}
20109
20111 MarkReferencedDecls Marker(*this, Loc);
20112 Marker.TraverseType(T);
20113}
20114
20115namespace {
20116/// Helper class that marks all of the declarations referenced by
20117/// potentially-evaluated subexpressions as "referenced".
20118class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20119public:
20120 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20121 bool SkipLocalVariables;
20123
20124 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20126 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20127
20128 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20129 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20130 }
20131
20132 void Visit(Expr *E) {
20133 if (llvm::is_contained(StopAt, E))
20134 return;
20135 Inherited::Visit(E);
20136 }
20137
20138 void VisitConstantExpr(ConstantExpr *E) {
20139 // Don't mark declarations within a ConstantExpression, as this expression
20140 // will be evaluated and folded to a value.
20141 }
20142
20143 void VisitDeclRefExpr(DeclRefExpr *E) {
20144 // If we were asked not to visit local variables, don't.
20145 if (SkipLocalVariables) {
20146 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20147 if (VD->hasLocalStorage())
20148 return;
20149 }
20150
20151 // FIXME: This can trigger the instantiation of the initializer of a
20152 // variable, which can cause the expression to become value-dependent
20153 // or error-dependent. Do we need to propagate the new dependence bits?
20155 }
20156
20157 void VisitMemberExpr(MemberExpr *E) {
20159 Visit(E->getBase());
20160 }
20161};
20162} // namespace
20163
20165 bool SkipLocalVariables,
20166 ArrayRef<const Expr*> StopAt) {
20167 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20168}
20169
20170/// Emit a diagnostic when statements are reachable.
20171/// FIXME: check for reachability even in expressions for which we don't build a
20172/// CFG (eg, in the initializer of a global or in a constant expression).
20173/// For example,
20174/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20176 const PartialDiagnostic &PD) {
20177 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20178 if (!FunctionScopes.empty())
20179 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20181 return true;
20182 }
20183
20184 // The initializer of a constexpr variable or of the first declaration of a
20185 // static data member is not syntactically a constant evaluated constant,
20186 // but nonetheless is always required to be a constant expression, so we
20187 // can skip diagnosing.
20188 // FIXME: Using the mangling context here is a hack.
20189 if (auto *VD = dyn_cast_or_null<VarDecl>(
20190 ExprEvalContexts.back().ManglingContextDecl)) {
20191 if (VD->isConstexpr() ||
20192 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20193 return false;
20194 // FIXME: For any other kind of variable, we should build a CFG for its
20195 // initializer and check whether the context in question is reachable.
20196 }
20197
20198 Diag(Loc, PD);
20199 return true;
20200}
20201
20202/// Emit a diagnostic that describes an effect on the run-time behavior
20203/// of the program being compiled.
20204///
20205/// This routine emits the given diagnostic when the code currently being
20206/// type-checked is "potentially evaluated", meaning that there is a
20207/// possibility that the code will actually be executable. Code in sizeof()
20208/// expressions, code used only during overload resolution, etc., are not
20209/// potentially evaluated. This routine will suppress such diagnostics or,
20210/// in the absolutely nutty case of potentially potentially evaluated
20211/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20212/// later.
20213///
20214/// This routine should be used for all diagnostics that describe the run-time
20215/// behavior of a program, such as passing a non-POD value through an ellipsis.
20216/// Failure to do so will likely result in spurious diagnostics or failures
20217/// during overload resolution or within sizeof/alignof/typeof/typeid.
20219 const PartialDiagnostic &PD) {
20220
20221 if (ExprEvalContexts.back().isDiscardedStatementContext())
20222 return false;
20223
20224 switch (ExprEvalContexts.back().Context) {
20229 // The argument will never be evaluated, so don't complain.
20230 break;
20231
20234 // Relevant diagnostics should be produced by constant evaluation.
20235 break;
20236
20239 return DiagIfReachable(Loc, Stmts, PD);
20240 }
20241
20242 return false;
20243}
20244
20246 const PartialDiagnostic &PD) {
20247 return DiagRuntimeBehavior(
20248 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
20249 PD);
20250}
20251
20253 CallExpr *CE, FunctionDecl *FD) {
20254 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20255 return false;
20256
20257 // If we're inside a decltype's expression, don't check for a valid return
20258 // type or construct temporaries until we know whether this is the last call.
20259 if (ExprEvalContexts.back().ExprContext ==
20261 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20262 return false;
20263 }
20264
20265 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20266 FunctionDecl *FD;
20267 CallExpr *CE;
20268
20269 public:
20270 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20271 : FD(FD), CE(CE) { }
20272
20273 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20274 if (!FD) {
20275 S.Diag(Loc, diag::err_call_incomplete_return)
20276 << T << CE->getSourceRange();
20277 return;
20278 }
20279
20280 S.Diag(Loc, diag::err_call_function_incomplete_return)
20281 << CE->getSourceRange() << FD << T;
20282 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20283 << FD->getDeclName();
20284 }
20285 } Diagnoser(FD, CE);
20286
20287 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20288 return true;
20289
20290 return false;
20291}
20292
20293// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20294// will prevent this condition from triggering, which is what we want.
20297
20298 unsigned diagnostic = diag::warn_condition_is_assignment;
20299 bool IsOrAssign = false;
20300
20301 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20302 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20303 return;
20304
20305 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20306
20307 // Greylist some idioms by putting them into a warning subcategory.
20308 if (ObjCMessageExpr *ME
20309 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20310 Selector Sel = ME->getSelector();
20311
20312 // self = [<foo> init...]
20313 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20314 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20315
20316 // <foo> = [<bar> nextObject]
20317 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20318 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20319 }
20320
20321 Loc = Op->getOperatorLoc();
20322 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20323 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20324 return;
20325
20326 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20327 Loc = Op->getOperatorLoc();
20328 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20329 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20330 else {
20331 // Not an assignment.
20332 return;
20333 }
20334
20335 Diag(Loc, diagnostic) << E->getSourceRange();
20336
20339 Diag(Loc, diag::note_condition_assign_silence)
20341 << FixItHint::CreateInsertion(Close, ")");
20342
20343 if (IsOrAssign)
20344 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20346 else
20347 Diag(Loc, diag::note_condition_assign_to_comparison)
20349}
20350
20352 // Don't warn if the parens came from a macro.
20353 SourceLocation parenLoc = ParenE->getBeginLoc();
20354 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20355 return;
20356 // Don't warn for dependent expressions.
20357 if (ParenE->isTypeDependent())
20358 return;
20359
20360 Expr *E = ParenE->IgnoreParens();
20361 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
20362 return;
20363
20364 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20365 if (opE->getOpcode() == BO_EQ &&
20366 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20367 == Expr::MLV_Valid) {
20368 SourceLocation Loc = opE->getOperatorLoc();
20369
20370 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20371 SourceRange ParenERange = ParenE->getSourceRange();
20372 Diag(Loc, diag::note_equality_comparison_silence)
20373 << FixItHint::CreateRemoval(ParenERange.getBegin())
20374 << FixItHint::CreateRemoval(ParenERange.getEnd());
20375 Diag(Loc, diag::note_equality_comparison_to_assign)
20377 }
20378}
20379
20381 bool IsConstexpr) {
20383 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20385
20387 if (result.isInvalid()) return ExprError();
20388 E = result.get();
20389
20390 if (!E->isTypeDependent()) {
20391 if (getLangOpts().CPlusPlus)
20392 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20393
20395 if (ERes.isInvalid())
20396 return ExprError();
20397 E = ERes.get();
20398
20399 QualType T = E->getType();
20400 if (!T->isScalarType()) { // C99 6.8.4.1p1
20401 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20402 << T << E->getSourceRange();
20403 return ExprError();
20404 }
20405 CheckBoolLikeConversion(E, Loc);
20406 }
20407
20408 return E;
20409}
20410
20412 Expr *SubExpr, ConditionKind CK,
20413 bool MissingOK) {
20414 // MissingOK indicates whether having no condition expression is valid
20415 // (for loop) or invalid (e.g. while loop).
20416 if (!SubExpr)
20417 return MissingOK ? ConditionResult() : ConditionError();
20418
20419 ExprResult Cond;
20420 switch (CK) {
20422 Cond = CheckBooleanCondition(Loc, SubExpr);
20423 break;
20424
20426 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20427 break;
20428
20430 Cond = CheckSwitchCondition(Loc, SubExpr);
20431 break;
20432 }
20433 if (Cond.isInvalid()) {
20434 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20435 {SubExpr}, PreferredConditionType(CK));
20436 if (!Cond.get())
20437 return ConditionError();
20438 }
20439 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20441 if (!FullExpr.get())
20442 return ConditionError();
20443
20444 return ConditionResult(*this, nullptr, FullExpr,
20446}
20447
20448namespace {
20449 /// A visitor for rebuilding a call to an __unknown_any expression
20450 /// to have an appropriate type.
20451 struct RebuildUnknownAnyFunction
20452 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20453
20454 Sema &S;
20455
20456 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20457
20458 ExprResult VisitStmt(Stmt *S) {
20459 llvm_unreachable("unexpected statement!");
20460 }
20461
20462 ExprResult VisitExpr(Expr *E) {
20463 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20464 << E->getSourceRange();
20465 return ExprError();
20466 }
20467
20468 /// Rebuild an expression which simply semantically wraps another
20469 /// expression which it shares the type and value kind of.
20470 template <class T> ExprResult rebuildSugarExpr(T *E) {
20471 ExprResult SubResult = Visit(E->getSubExpr());
20472 if (SubResult.isInvalid()) return ExprError();
20473
20474 Expr *SubExpr = SubResult.get();
20475 E->setSubExpr(SubExpr);
20476 E->setType(SubExpr->getType());
20477 E->setValueKind(SubExpr->getValueKind());
20478 assert(E->getObjectKind() == OK_Ordinary);
20479 return E;
20480 }
20481
20482 ExprResult VisitParenExpr(ParenExpr *E) {
20483 return rebuildSugarExpr(E);
20484 }
20485
20486 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20487 return rebuildSugarExpr(E);
20488 }
20489
20490 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20491 ExprResult SubResult = Visit(E->getSubExpr());
20492 if (SubResult.isInvalid()) return ExprError();
20493
20494 Expr *SubExpr = SubResult.get();
20495 E->setSubExpr(SubExpr);
20496 E->setType(S.Context.getPointerType(SubExpr->getType()));
20497 assert(E->isPRValue());
20498 assert(E->getObjectKind() == OK_Ordinary);
20499 return E;
20500 }
20501
20502 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20503 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20504
20505 E->setType(VD->getType());
20506
20507 assert(E->isPRValue());
20508 if (S.getLangOpts().CPlusPlus &&
20509 !(isa<CXXMethodDecl>(VD) &&
20510 cast<CXXMethodDecl>(VD)->isInstance()))
20512
20513 return E;
20514 }
20515
20516 ExprResult VisitMemberExpr(MemberExpr *E) {
20517 return resolveDecl(E, E->getMemberDecl());
20518 }
20519
20520 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20521 return resolveDecl(E, E->getDecl());
20522 }
20523 };
20524}
20525
20526/// Given a function expression of unknown-any type, try to rebuild it
20527/// to have a function type.
20529 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20530 if (Result.isInvalid()) return ExprError();
20531 return S.DefaultFunctionArrayConversion(Result.get());
20532}
20533
20534namespace {
20535 /// A visitor for rebuilding an expression of type __unknown_anytype
20536 /// into one which resolves the type directly on the referring
20537 /// expression. Strict preservation of the original source
20538 /// structure is not a goal.
20539 struct RebuildUnknownAnyExpr
20540 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20541
20542 Sema &S;
20543
20544 /// The current destination type.
20545 QualType DestType;
20546
20547 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20548 : S(S), DestType(CastType) {}
20549
20550 ExprResult VisitStmt(Stmt *S) {
20551 llvm_unreachable("unexpected statement!");
20552 }
20553
20554 ExprResult VisitExpr(Expr *E) {
20555 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20556 << E->getSourceRange();
20557 return ExprError();
20558 }
20559
20560 ExprResult VisitCallExpr(CallExpr *E);
20561 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20562
20563 /// Rebuild an expression which simply semantically wraps another
20564 /// expression which it shares the type and value kind of.
20565 template <class T> ExprResult rebuildSugarExpr(T *E) {
20566 ExprResult SubResult = Visit(E->getSubExpr());
20567 if (SubResult.isInvalid()) return ExprError();
20568 Expr *SubExpr = SubResult.get();
20569 E->setSubExpr(SubExpr);
20570 E->setType(SubExpr->getType());
20571 E->setValueKind(SubExpr->getValueKind());
20572 assert(E->getObjectKind() == OK_Ordinary);
20573 return E;
20574 }
20575
20576 ExprResult VisitParenExpr(ParenExpr *E) {
20577 return rebuildSugarExpr(E);
20578 }
20579
20580 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20581 return rebuildSugarExpr(E);
20582 }
20583
20584 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20585 const PointerType *Ptr = DestType->getAs<PointerType>();
20586 if (!Ptr) {
20587 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20588 << E->getSourceRange();
20589 return ExprError();
20590 }
20591
20592 if (isa<CallExpr>(E->getSubExpr())) {
20593 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20594 << E->getSourceRange();
20595 return ExprError();
20596 }
20597
20598 assert(E->isPRValue());
20599 assert(E->getObjectKind() == OK_Ordinary);
20600 E->setType(DestType);
20601
20602 // Build the sub-expression as if it were an object of the pointee type.
20603 DestType = Ptr->getPointeeType();
20604 ExprResult SubResult = Visit(E->getSubExpr());
20605 if (SubResult.isInvalid()) return ExprError();
20606 E->setSubExpr(SubResult.get());
20607 return E;
20608 }
20609
20610 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20611
20612 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20613
20614 ExprResult VisitMemberExpr(MemberExpr *E) {
20615 return resolveDecl(E, E->getMemberDecl());
20616 }
20617
20618 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20619 return resolveDecl(E, E->getDecl());
20620 }
20621 };
20622}
20623
20624/// Rebuilds a call expression which yielded __unknown_anytype.
20625ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20626 Expr *CalleeExpr = E->getCallee();
20627
20628 enum FnKind {
20629 FK_MemberFunction,
20630 FK_FunctionPointer,
20631 FK_BlockPointer
20632 };
20633
20634 FnKind Kind;
20635 QualType CalleeType = CalleeExpr->getType();
20636 if (CalleeType == S.Context.BoundMemberTy) {
20637 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20638 Kind = FK_MemberFunction;
20639 CalleeType = Expr::findBoundMemberType(CalleeExpr);
20640 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20641 CalleeType = Ptr->getPointeeType();
20642 Kind = FK_FunctionPointer;
20643 } else {
20644 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20645 Kind = FK_BlockPointer;
20646 }
20647 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20648
20649 // Verify that this is a legal result type of a function.
20650 if (DestType->isArrayType() || DestType->isFunctionType()) {
20651 unsigned diagID = diag::err_func_returning_array_function;
20652 if (Kind == FK_BlockPointer)
20653 diagID = diag::err_block_returning_array_function;
20654
20655 S.Diag(E->getExprLoc(), diagID)
20656 << DestType->isFunctionType() << DestType;
20657 return ExprError();
20658 }
20659
20660 // Otherwise, go ahead and set DestType as the call's result.
20661 E->setType(DestType.getNonLValueExprType(S.Context));
20663 assert(E->getObjectKind() == OK_Ordinary);
20664
20665 // Rebuild the function type, replacing the result type with DestType.
20666 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20667 if (Proto) {
20668 // __unknown_anytype(...) is a special case used by the debugger when
20669 // it has no idea what a function's signature is.
20670 //
20671 // We want to build this call essentially under the K&R
20672 // unprototyped rules, but making a FunctionNoProtoType in C++
20673 // would foul up all sorts of assumptions. However, we cannot
20674 // simply pass all arguments as variadic arguments, nor can we
20675 // portably just call the function under a non-variadic type; see
20676 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20677 // However, it turns out that in practice it is generally safe to
20678 // call a function declared as "A foo(B,C,D);" under the prototype
20679 // "A foo(B,C,D,...);". The only known exception is with the
20680 // Windows ABI, where any variadic function is implicitly cdecl
20681 // regardless of its normal CC. Therefore we change the parameter
20682 // types to match the types of the arguments.
20683 //
20684 // This is a hack, but it is far superior to moving the
20685 // corresponding target-specific code from IR-gen to Sema/AST.
20686
20687 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20688 SmallVector<QualType, 8> ArgTypes;
20689 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20690 ArgTypes.reserve(E->getNumArgs());
20691 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20692 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20693 }
20694 ParamTypes = ArgTypes;
20695 }
20696 DestType = S.Context.getFunctionType(DestType, ParamTypes,
20697 Proto->getExtProtoInfo());
20698 } else {
20699 DestType = S.Context.getFunctionNoProtoType(DestType,
20700 FnType->getExtInfo());
20701 }
20702
20703 // Rebuild the appropriate pointer-to-function type.
20704 switch (Kind) {
20705 case FK_MemberFunction:
20706 // Nothing to do.
20707 break;
20708
20709 case FK_FunctionPointer:
20710 DestType = S.Context.getPointerType(DestType);
20711 break;
20712
20713 case FK_BlockPointer:
20714 DestType = S.Context.getBlockPointerType(DestType);
20715 break;
20716 }
20717
20718 // Finally, we can recurse.
20719 ExprResult CalleeResult = Visit(CalleeExpr);
20720 if (!CalleeResult.isUsable()) return ExprError();
20721 E->setCallee(CalleeResult.get());
20722
20723 // Bind a temporary if necessary.
20724 return S.MaybeBindToTemporary(E);
20725}
20726
20727ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20728 // Verify that this is a legal result type of a call.
20729 if (DestType->isArrayType() || DestType->isFunctionType()) {
20730 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20731 << DestType->isFunctionType() << DestType;
20732 return ExprError();
20733 }
20734
20735 // Rewrite the method result type if available.
20736 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20737 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20738 Method->setReturnType(DestType);
20739 }
20740
20741 // Change the type of the message.
20742 E->setType(DestType.getNonReferenceType());
20744
20745 return S.MaybeBindToTemporary(E);
20746}
20747
20748ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20749 // The only case we should ever see here is a function-to-pointer decay.
20750 if (E->getCastKind() == CK_FunctionToPointerDecay) {
20751 assert(E->isPRValue());
20752 assert(E->getObjectKind() == OK_Ordinary);
20753
20754 E->setType(DestType);
20755
20756 // Rebuild the sub-expression as the pointee (function) type.
20757 DestType = DestType->castAs<PointerType>()->getPointeeType();
20758
20759 ExprResult Result = Visit(E->getSubExpr());
20760 if (!Result.isUsable()) return ExprError();
20761
20762 E->setSubExpr(Result.get());
20763 return E;
20764 } else if (E->getCastKind() == CK_LValueToRValue) {
20765 assert(E->isPRValue());
20766 assert(E->getObjectKind() == OK_Ordinary);
20767
20768 assert(isa<BlockPointerType>(E->getType()));
20769
20770 E->setType(DestType);
20771
20772 // The sub-expression has to be a lvalue reference, so rebuild it as such.
20773 DestType = S.Context.getLValueReferenceType(DestType);
20774
20775 ExprResult Result = Visit(E->getSubExpr());
20776 if (!Result.isUsable()) return ExprError();
20777
20778 E->setSubExpr(Result.get());
20779 return E;
20780 } else {
20781 llvm_unreachable("Unhandled cast type!");
20782 }
20783}
20784
20785ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20786 ExprValueKind ValueKind = VK_LValue;
20787 QualType Type = DestType;
20788
20789 // We know how to make this work for certain kinds of decls:
20790
20791 // - functions
20792 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20793 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20794 DestType = Ptr->getPointeeType();
20795 ExprResult Result = resolveDecl(E, VD);
20796 if (Result.isInvalid()) return ExprError();
20797 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20798 VK_PRValue);
20799 }
20800
20801 if (!Type->isFunctionType()) {
20802 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20803 << VD << E->getSourceRange();
20804 return ExprError();
20805 }
20806 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20807 // We must match the FunctionDecl's type to the hack introduced in
20808 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20809 // type. See the lengthy commentary in that routine.
20810 QualType FDT = FD->getType();
20811 const FunctionType *FnType = FDT->castAs<FunctionType>();
20812 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20813 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20814 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20815 SourceLocation Loc = FD->getLocation();
20817 S.Context, FD->getDeclContext(), Loc, Loc,
20818 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20820 false /*isInlineSpecified*/, FD->hasPrototype(),
20821 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20822
20823 if (FD->getQualifier())
20824 NewFD->setQualifierInfo(FD->getQualifierLoc());
20825
20827 for (const auto &AI : FT->param_types()) {
20828 ParmVarDecl *Param =
20830 Param->setScopeInfo(0, Params.size());
20831 Params.push_back(Param);
20832 }
20833 NewFD->setParams(Params);
20834 DRE->setDecl(NewFD);
20835 VD = DRE->getDecl();
20836 }
20837 }
20838
20839 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20840 if (MD->isInstance()) {
20841 ValueKind = VK_PRValue;
20843 }
20844
20845 // Function references aren't l-values in C.
20846 if (!S.getLangOpts().CPlusPlus)
20847 ValueKind = VK_PRValue;
20848
20849 // - variables
20850 } else if (isa<VarDecl>(VD)) {
20851 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20852 Type = RefTy->getPointeeType();
20853 } else if (Type->isFunctionType()) {
20854 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20855 << VD << E->getSourceRange();
20856 return ExprError();
20857 }
20858
20859 // - nothing else
20860 } else {
20861 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20862 << VD << E->getSourceRange();
20863 return ExprError();
20864 }
20865
20866 // Modifying the declaration like this is friendly to IR-gen but
20867 // also really dangerous.
20868 VD->setType(DestType);
20869 E->setType(Type);
20870 E->setValueKind(ValueKind);
20871 return E;
20872}
20873
20877 // The type we're casting to must be either void or complete.
20878 if (!CastType->isVoidType() &&
20880 diag::err_typecheck_cast_to_incomplete))
20881 return ExprError();
20882
20883 // Rewrite the casted expression from scratch.
20884 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20885 if (!result.isUsable()) return ExprError();
20886
20887 CastExpr = result.get();
20888 VK = CastExpr->getValueKind();
20889 CastKind = CK_NoOp;
20890
20891 return CastExpr;
20892}
20893
20895 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20896}
20897
20899 Expr *arg, QualType &paramType) {
20900 // If the syntactic form of the argument is not an explicit cast of
20901 // any sort, just do default argument promotion.
20902 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20903 if (!castArg) {
20905 if (result.isInvalid()) return ExprError();
20906 paramType = result.get()->getType();
20907 return result;
20908 }
20909
20910 // Otherwise, use the type that was written in the explicit cast.
20911 assert(!arg->hasPlaceholderType());
20912 paramType = castArg->getTypeAsWritten();
20913
20914 // Copy-initialize a parameter of that type.
20915 InitializedEntity entity =
20917 /*consumed*/ false);
20918 return PerformCopyInitialization(entity, callLoc, arg);
20919}
20920
20922 Expr *orig = E;
20923 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20924 while (true) {
20925 E = E->IgnoreParenImpCasts();
20926 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20927 E = call->getCallee();
20928 diagID = diag::err_uncasted_call_of_unknown_any;
20929 } else {
20930 break;
20931 }
20932 }
20933
20934 SourceLocation loc;
20935 NamedDecl *d;
20936 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20937 loc = ref->getLocation();
20938 d = ref->getDecl();
20939 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20940 loc = mem->getMemberLoc();
20941 d = mem->getMemberDecl();
20942 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20943 diagID = diag::err_uncasted_call_of_unknown_any;
20944 loc = msg->getSelectorStartLoc();
20945 d = msg->getMethodDecl();
20946 if (!d) {
20947 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20948 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20949 << orig->getSourceRange();
20950 return ExprError();
20951 }
20952 } else {
20953 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20954 << E->getSourceRange();
20955 return ExprError();
20956 }
20957
20958 S.Diag(loc, diagID) << d << orig->getSourceRange();
20959
20960 // Never recoverable.
20961 return ExprError();
20962}
20963
20966 // C cannot handle TypoExpr nodes on either side of a binop because it
20967 // doesn't handle dependent types properly, so make sure any TypoExprs have
20968 // been dealt with before checking the operands.
20970 if (!Result.isUsable()) return ExprError();
20971 E = Result.get();
20972 }
20973
20974 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20975 if (!placeholderType) return E;
20976
20977 switch (placeholderType->getKind()) {
20978 case BuiltinType::UnresolvedTemplate: {
20979 auto *ULE = cast<UnresolvedLookupExpr>(E);
20980 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
20981 // There's only one FoundDecl for UnresolvedTemplate type. See
20982 // BuildTemplateIdExpr.
20983 NamedDecl *Temp = *ULE->decls_begin();
20984 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
20985
20986 if (NestedNameSpecifierLoc Loc = ULE->getQualifierLoc(); Loc.hasQualifier())
20987 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
20988 << Loc.getNestedNameSpecifier() << NameInfo.getName().getAsString()
20989 << Loc.getSourceRange() << IsTypeAliasTemplateDecl;
20990 else
20991 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
20992 << "" << NameInfo.getName().getAsString() << ULE->getSourceRange()
20993 << IsTypeAliasTemplateDecl;
20994 Diag(Temp->getLocation(), diag::note_referenced_type_template)
20995 << IsTypeAliasTemplateDecl;
20996
20997 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
20998 }
20999
21000 // Overloaded expressions.
21001 case BuiltinType::Overload: {
21002 // Try to resolve a single function template specialization.
21003 // This is obligatory.
21006 return Result;
21007
21008 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21009 // leaves Result unchanged on failure.
21010 Result = E;
21012 return Result;
21013
21014 // If that failed, try to recover with a call.
21015 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21016 /*complain*/ true);
21017 return Result;
21018 }
21019
21020 // Bound member functions.
21021 case BuiltinType::BoundMember: {
21022 ExprResult result = E;
21023 const Expr *BME = E->IgnoreParens();
21024 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21025 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21026 if (isa<CXXPseudoDestructorExpr>(BME)) {
21027 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21028 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21029 if (ME->getMemberNameInfo().getName().getNameKind() ==
21031 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21032 }
21033 tryToRecoverWithCall(result, PD,
21034 /*complain*/ true);
21035 return result;
21036 }
21037
21038 // ARC unbridged casts.
21039 case BuiltinType::ARCUnbridgedCast: {
21040 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
21041 ObjC().diagnoseARCUnbridgedCast(realCast);
21042 return realCast;
21043 }
21044
21045 // Expressions of unknown type.
21046 case BuiltinType::UnknownAny:
21047 return diagnoseUnknownAnyExpr(*this, E);
21048
21049 // Pseudo-objects.
21050 case BuiltinType::PseudoObject:
21051 return PseudoObject().checkRValue(E);
21052
21053 case BuiltinType::BuiltinFn: {
21054 // Accept __noop without parens by implicitly converting it to a call expr.
21055 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21056 if (DRE) {
21057 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21058 unsigned BuiltinID = FD->getBuiltinID();
21059 if (BuiltinID == Builtin::BI__noop) {
21060 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21061 CK_BuiltinFnToFnPtr)
21062 .get();
21063 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21066 }
21067
21068 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21069 // Any use of these other than a direct call is ill-formed as of C++20,
21070 // because they are not addressable functions. In earlier language
21071 // modes, warn and force an instantiation of the real body.
21072 Diag(E->getBeginLoc(),
21074 ? diag::err_use_of_unaddressable_function
21075 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21076 if (FD->isImplicitlyInstantiable()) {
21077 // Require a definition here because a normal attempt at
21078 // instantiation for a builtin will be ignored, and we won't try
21079 // again later. We assume that the definition of the template
21080 // precedes this use.
21082 /*Recursive=*/false,
21083 /*DefinitionRequired=*/true,
21084 /*AtEndOfTU=*/false);
21085 }
21086 // Produce a properly-typed reference to the function.
21087 CXXScopeSpec SS;
21088 SS.Adopt(DRE->getQualifierLoc());
21089 TemplateArgumentListInfo TemplateArgs;
21090 DRE->copyTemplateArgumentsInto(TemplateArgs);
21091 return BuildDeclRefExpr(
21092 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21093 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21094 DRE->getTemplateKeywordLoc(),
21095 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21096 }
21097 }
21098
21099 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21100 return ExprError();
21101 }
21102
21103 case BuiltinType::IncompleteMatrixIdx:
21104 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
21105 ->getRowIdx()
21106 ->getBeginLoc(),
21107 diag::err_matrix_incomplete_index);
21108 return ExprError();
21109
21110 // Expressions of unknown type.
21111 case BuiltinType::ArraySection:
21112 Diag(E->getBeginLoc(), diag::err_array_section_use)
21113 << cast<ArraySectionExpr>(E)->isOMPArraySection();
21114 return ExprError();
21115
21116 // Expressions of unknown type.
21117 case BuiltinType::OMPArrayShaping:
21118 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21119
21120 case BuiltinType::OMPIterator:
21121 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21122
21123 // Everything else should be impossible.
21124#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21125 case BuiltinType::Id:
21126#include "clang/Basic/OpenCLImageTypes.def"
21127#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21128 case BuiltinType::Id:
21129#include "clang/Basic/OpenCLExtensionTypes.def"
21130#define SVE_TYPE(Name, Id, SingletonId) \
21131 case BuiltinType::Id:
21132#include "clang/Basic/AArch64SVEACLETypes.def"
21133#define PPC_VECTOR_TYPE(Name, Id, Size) \
21134 case BuiltinType::Id:
21135#include "clang/Basic/PPCTypes.def"
21136#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21137#include "clang/Basic/RISCVVTypes.def"
21138#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21139#include "clang/Basic/WebAssemblyReferenceTypes.def"
21140#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
21141#include "clang/Basic/AMDGPUTypes.def"
21142#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21143#include "clang/Basic/HLSLIntangibleTypes.def"
21144#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21145#define PLACEHOLDER_TYPE(Id, SingletonId)
21146#include "clang/AST/BuiltinTypes.def"
21147 break;
21148 }
21149
21150 llvm_unreachable("invalid placeholder type!");
21151}
21152
21154 if (E->isTypeDependent())
21155 return true;
21158 return false;
21159}
21160
21162 ArrayRef<Expr *> SubExprs, QualType T) {
21163 if (!Context.getLangOpts().RecoveryAST)
21164 return ExprError();
21165
21166 if (isSFINAEContext())
21167 return ExprError();
21168
21169 if (T.isNull() || T->isUndeducedType() ||
21170 !Context.getLangOpts().RecoveryASTType)
21171 // We don't know the concrete type, fallback to dependent type.
21173
21174 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21175}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3443
NodeId Parent
Definition: ASTDiff.cpp:191
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
static bool isObjCPointer(const MemRegion *R)
Defines enum values for all the target-independent builtin functions.
const Decl * D
IndirectLocalPath & Path
Expr * E
Defines the C++ template declaration subclasses.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Defines the clang::Expr interface and subclasses for C++ expressions.
unsigned Iter
Definition: HTMLLogger.cpp:153
LangStandard::Kind Std
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Target Target
Definition: MachO.h:51
llvm::MachO::Record Record
Definition: MachO.h:31
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
Defines the clang::Preprocessor interface.
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
uint32_t Id
Definition: SemaARM.cpp:1134
This file declares semantic analysis for CUDA constructs.
CastType
Definition: SemaCast.cpp:48
static Sema::AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
Definition: SemaExpr.cpp:9120
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
Definition: SemaExpr.cpp:17730
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, IdentifierInfo *UDSuffix, SourceLocation UDSuffixLoc, ArrayRef< Expr * > Args, SourceLocation LitEndLoc)
BuildCookedLiteralOperatorCall - A user-defined literal was found.
Definition: SemaExpr.cpp:1940
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.
Definition: SemaExpr.cpp:15309
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...
Definition: SemaExpr.cpp:10004
static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind, bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the captured region.
Definition: SemaExpr.cpp:18681
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:10762
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...
Definition: SemaExpr.cpp:15058
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
Definition: SemaExpr.cpp:6132
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:10681
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...
Definition: SemaExpr.cpp:8691
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, bool AcceptInvalid)
Diagnoses obvious problems with the use of the given declaration as an expression.
Definition: SemaExpr.cpp:3157
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
Definition: SemaExpr.cpp:8145
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",...
Definition: SemaExpr.cpp:8351
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.
Definition: SemaExpr.cpp:11728
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:10726
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:11678
static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn)
Definition: SemaExpr.cpp:5795
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
Definition: SemaExpr.cpp:2225
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:14534
static void DetectPrecisionLossInComplexDivision(Sema &S, SourceLocation OpLoc, Expr *Operand)
Definition: SemaExpr.cpp:15240
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:18068
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
Definition: SemaExpr.cpp:13284
@ NCCK_Block
Definition: SemaExpr.cpp:13284
@ NCCK_None
Definition: SemaExpr.cpp:13284
@ NCCK_Lambda
Definition: SemaExpr.cpp:13284
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...
Definition: SemaExpr.cpp:9893
static bool isVector(QualType QT, QualType ElementType)
This helper function returns true if QT is a vector type that has element type ElementType.
Definition: SemaExpr.cpp:9169
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:6064
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,...
Definition: SemaExpr.cpp:2635
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(Sema &SemaRef, ValueDecl *D, Expr *E)
Definition: SemaExpr.cpp:19917
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18533
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:16793
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.
Definition: SemaExpr.cpp:8595
static Decl * getPredefinedExprDecl(DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
Definition: SemaExpr.cpp:1924
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:16676
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
Definition: SemaExpr.cpp:13859
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
Definition: SemaExpr.cpp:4719
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12140
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
Definition: SemaExpr.cpp:14434
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
Definition: SemaExpr.cpp:4334
static bool ExprLooksBoolean(const Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
Definition: SemaExpr.cpp:8670
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
Definition: SemaExpr.cpp:17917
static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr, SourceLocation OpLoc, bool IsBuiltin)
DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
Definition: SemaExpr.cpp:14590
static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
diagnoseStringPlusInt - Emit a warning when adding an integer to a string literal.
Definition: SemaExpr.cpp:10848
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
Definition: SemaExpr.cpp:7988
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19717
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
Definition: SemaExpr.cpp:3182
static bool checkCondition(Sema &S, const Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
Definition: SemaExpr.cpp:7954
static bool checkForArray(const Expr *E)
Definition: SemaExpr.cpp:11770
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
Definition: SemaExpr.cpp:6407
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
Definition: SemaExpr.cpp:13481
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19963
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.
Definition: SemaExpr.cpp:9942
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
Definition: SemaExpr.cpp:19685
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:14416
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
Definition: SemaExpr.cpp:17580
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:12015
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...
Definition: SemaExpr.cpp:8625
static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS, BinaryOperatorKind Opc, QualType ResultTy, ExprValueKind VK, ExprObjectKind OK, bool IsCompAssign, SourceLocation OpLoc, FPOptionsOverride FPFeatures)
Definition: SemaExpr.cpp:14688
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
Definition: SemaExpr.cpp:1310
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
Definition: SemaExpr.cpp:6297
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.
Definition: SemaExpr.cpp:9557
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.
Definition: SemaExpr.cpp:8269
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
Definition: SemaExpr.cpp:7975
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
Definition: SemaExpr.cpp:10693
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:14673
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
Definition: SemaExpr.cpp:4776
static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8896
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
Definition: SemaExpr.cpp:17622
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...
Definition: SemaExpr.cpp:15149
static void emitEmptyLookupTypoDiagnostic(const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, DeclarationName Typo, SourceLocation TypoLoc, ArrayRef< Expr * > Args, unsigned DiagnosticID, unsigned DiagnosticSuggestID)
Definition: SemaExpr.cpp:2360
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...
Definition: SemaExpr.cpp:13964
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:8214
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.
Definition: SemaExpr.cpp:8323
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10520
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
Definition: SemaExpr.cpp:11829
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...
Definition: SemaExpr.cpp:4211
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
Definition: SemaExpr.cpp:10568
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
Definition: SemaExpr.cpp:3474
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
Definition: SemaExpr.cpp:5754
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition: SemaExpr.cpp:145
static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType)
Definition: SemaExpr.cpp:11217
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4118
static Sema::AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
Definition: SemaExpr.cpp:9069
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 ...
Definition: SemaExpr.cpp:1267
static void MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
Definition: SemaExpr.cpp:18360
static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Emit a warning when adding a char literal to a string.
Definition: SemaExpr.cpp:10878
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:13545
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:14066
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:161
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...
Definition: SemaExpr.cpp:17948
static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
Returns false if the pointers are converted to a composite type, true otherwise.
Definition: SemaExpr.cpp:11579
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
Definition: SemaExpr.cpp:15206
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
Definition: SemaExpr.cpp:14126
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle conversions with GCC complex int extension.
Definition: SemaExpr.cpp:1360
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
Definition: SemaExpr.cpp:4790
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...
Definition: SemaExpr.cpp:10051
static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool RefersToCapturedVariable, const Sema::TryCaptureKind Kind, SourceLocation EllipsisLoc, const bool IsTopScope, Sema &S, bool Invalid)
Capture the given variable in the lambda.
Definition: SemaExpr.cpp:18721
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the left hand of a '||' expr.
Definition: SemaExpr.cpp:15113
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition: SemaExpr.cpp:558
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
Definition: SemaExpr.cpp:8725
static OdrUseContext isOdrUseContext(Sema &SemaRef)
Are we within a context in which references to resolved functions or to variables result in odr-use?
Definition: SemaExpr.cpp:18036
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...
Definition: SemaExpr.cpp:13356
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
Definition: SemaExpr.cpp:3605
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
Definition: SemaExpr.cpp:13334
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:18477
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
Definition: SemaExpr.cpp:10740
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4163
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:11412
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12058
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:20921
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...
Definition: SemaExpr.cpp:1932
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
Definition: SemaExpr.cpp:8389
OriginalExprKind
Definition: SemaExpr.cpp:13475
@ OEK_Variable
Definition: SemaExpr.cpp:13476
@ OEK_LValue
Definition: SemaExpr.cpp:13478
@ OEK_Member
Definition: SemaExpr.cpp:13477
static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var, SourceLocation Loc, const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const bool Nested, Sema &S, bool Invalid)
Definition: SemaExpr.cpp:18613
static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmethic conversion with floating point types.
Definition: SemaExpr.cpp:1217
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
Definition: SemaExpr.cpp:10668
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.
Definition: SemaExpr.cpp:11318
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
Definition: SemaExpr.cpp:18436
static FieldDecl * FindFieldDeclInstantiationPattern(const ASTContext &Ctx, FieldDecl *Field)
Definition: SemaExpr.cpp:5563
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
Definition: SemaExpr.cpp:1292
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
Definition: SemaExpr.cpp:10484
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:13271
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...
Definition: SemaExpr.cpp:11786
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.
Definition: SemaExpr.cpp:18854
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:6366
static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4148
static Sema::AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, SourceLocation Loc)
Definition: SemaExpr.cpp:8917
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4136
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
Definition: SemaExpr.cpp:15134
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
Definition: SemaExpr.cpp:4809
static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc, Sema::ArithConvKind ACK)
Check that the usual arithmetic conversions can be performed on this pair of expressions that might b...
Definition: SemaExpr.cpp:1492
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
Definition: SemaExpr.cpp:10929
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:6324
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
Definition: SemaExpr.cpp:1406
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4193
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
Definition: SemaExpr.cpp:10710
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,...
Definition: SemaExpr.cpp:8184
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:11976
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
Definition: SemaExpr.cpp:12840
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
Definition: SemaExpr.cpp:8303
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:8610
@ ConstMethod
Definition: SemaExpr.cpp:13347
@ ConstUnknown
Definition: SemaExpr.cpp:13349
@ ConstVariable
Definition: SemaExpr.cpp:13345
@ NestedConstMember
Definition: SemaExpr.cpp:13348
@ ConstMember
Definition: SemaExpr.cpp:13346
@ ConstFunction
Definition: SemaExpr.cpp:13344
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...
Definition: SemaExpr.cpp:1111
static std::pair< ExprResult, ExprResult > CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:14721
static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R, SourceLocation OpLoc)
Check if a bitwise-& is performed on an Objective-C pointer.
Definition: SemaExpr.cpp:14632
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition: SemaExpr.cpp:583
static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn)
Given a function expression of unknown-any type, try to rebuild it to have a function type.
Definition: SemaExpr.cpp:20528
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, ExprResult &IntExpr, QualType FloatTy, QualType IntTy, bool ConvertFloat, bool ConvertInt)
Handle arithmetic conversion from integer to float.
Definition: SemaExpr.cpp:1186
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
Definition: SemaExpr.cpp:11631
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, QualType ShorterType, QualType LongerType, bool PromotePrecision)
Definition: SemaExpr.cpp:1139
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...
Definition: SemaExpr.cpp:6224
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
Definition: SemaExpr.cpp:19888
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind)
Definition: SemaExpr.cpp:1900
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition: SemaExpr.cpp:107
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, QualType RHSTy)
handleFixedPointConversion - Fixed point operations between fixed point types and integers or other f...
Definition: SemaExpr.cpp:1453
static QualType handleComplexConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
Definition: SemaExpr.cpp:1162
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:13928
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
Definition: SemaExpr.cpp:18828
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:10658
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
Definition: SemaExpr.cpp:11568
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.
Definition: SemaExpr.cpp:14744
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:11618
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:13285
static QualType checkConditionalBlockPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both block pointers.
Definition: SemaExpr.cpp:8119
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15178
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:15164
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:11608
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
Definition: SemaExpr.cpp:15101
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
Definition: SemaExpr.cpp:4400
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...
Definition: SemaExpr.cpp:9963
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18514
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:15488
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
Definition: SemaExpr.cpp:13673
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13080
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 ...
Definition: SemaExpr.cpp:19302
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
Definition: SemaExpr.cpp:17982
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:11211
static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Check the validity of a binary arithmetic operation w.r.t.
Definition: SemaExpr.cpp:10794
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:7499
This file declares semantic analysis for HLSL constructs.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
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.
SourceLocation Begin
@ Open
The standard open() call: int open(const char *path, int oflag, ...);.
__device__ int
#define bool
Definition: amdgpuintrin.h:20
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APSInt & getInt()
Definition: APValue.h:465
bool hasValue() const
Definition: APValue.h:441
bool isInt() const
Definition: APValue.h:443
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
virtual void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D)
Invoked when a function is implicitly instantiated.
Definition: ASTConsumer.h:83
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
CanQualType AccumTy
Definition: ASTContext.h:1173
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2915
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
CanQualType ARCUnbridgedCastTy
Definition: ASTContext.h:1191
CanQualType LongTy
Definition: ASTContext.h:1169
unsigned getIntWidth(QualType T) const
CanQualType Int128Ty
Definition: ASTContext.h:1169
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
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.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
QualType getBuiltinVaListType() const
Retrieve the type of the __builtin_va_list type.
Definition: ASTContext.h:2251
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:684
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 getRecordType(const RecordDecl *Decl) 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 getBuiltinMSVaListType() const
Retrieve the type of the __builtin_ms_va_list type.
Definition: ASTContext.h:2265
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
Definition: ASTContext.h:1173
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
Definition: ASTContext.h:1172
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2716
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2732
CanQualType DoubleTy
Definition: ASTContext.h:1172
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
Definition: ASTContext.h:1172
CanQualType Char16Ty
Definition: ASTContext.h:1167
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType VoidPtrTy
Definition: ASTContext.h:1187
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
Definition: ASTContext.h:1188
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
CanQualType WideCharTy
Definition: ASTContext.h:1164
IdentifierTable & Idents
Definition: ASTContext.h:680
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:682
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:834
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
const QualType GetHigherPrecisionFPType(QualType ElementType) const
Definition: ASTContext.h:802
bool typesAreBlockPointerCompatible(QualType, QualType)
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
llvm::SetVector< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
Definition: ASTContext.h:1241
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
Definition: ASTContext.h:1161
QualType getIntTypeForBitwidth(unsigned DestWidth, unsigned Signed) const
getIntTypeForBitwidth - sets integer QualTy according to specified details: bitwidth,...
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
CanQualType Float128Ty
Definition: ASTContext.h:1172
CanQualType UnsignedLongTy
Definition: ASTContext.h:1170
llvm::DenseSet< const FunctionDecl * > CUDAImplicitHostDeviceFunUsedByDevice
Keep track of CUDA/HIP implicit host device functions used on device side in device compilation.
Definition: ASTContext.h:1245
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
TypeInfo getTypeInfo(const Type *T) const
Get the size and alignment of the specified complete type in bits.
CanQualType ShortFractTy
Definition: ASTContext.h:1176
QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const
Return a type for a constant array for a string literal of the specified element type and length.
QualType getCorrespondingSaturatedType(QualType Ty) const
CanQualType BoundMemberTy
Definition: ASTContext.h:1188
CanQualType CharTy
Definition: ASTContext.h:1162
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
Definition: ASTContext.h:1169
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
Definition: ASTContext.h:1237
CanQualType PseudoObjectTy
Definition: ASTContext.h:1191
CanQualType Float16Ty
Definition: ASTContext.h:1186
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2289
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
Definition: ASTContext.h:1188
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false, bool IsConditionalOperator=false)
static bool isObjCNSObjectType(QualType Ty)
Return true if this is an NSObject object with its NSObject attribute set.
Definition: ASTContext.h:2462
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2763
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.
Definition: ASTContext.h:2482
CanQualType BuiltinFnTy
Definition: ASTContext.h:1190
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1160
CanQualType UnsignedCharTy
Definition: ASTContext.h:1170
CanQualType UnsignedIntTy
Definition: ASTContext.h:1170
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
QualType getObjCClassRedefinitionType() const
Retrieve the type that Class has been defined to, which may be different from the built-in Class if C...
Definition: ASTContext.h:2004
CanQualType UnknownAnyTy
Definition: ASTContext.h:1189
FieldDecl * getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) const
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1171
QualType getCommonSugaredType(QualType X, QualType Y, bool Unqualified=false)
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.
Definition: ASTContext.h:1681
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
CanQualType ShortTy
Definition: ASTContext.h:1169
llvm::APFixedPoint getFixedPointMax(QualType Ty) const
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
CanQualType FractTy
Definition: ASTContext.h:1176
CanQualType LongAccumTy
Definition: ASTContext.h:1174
CanQualType Char32Ty
Definition: ASTContext.h:1168
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
CanQualType LongFractTy
Definition: ASTContext.h:1176
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1199
std::optional< CharUnits > getTypeSizeInCharsIfKnown(QualType Ty) const
Definition: ASTContext.h:2501
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 ...
CanQualType LongLongTy
Definition: ASTContext.h:1169
QualType getCorrespondingSignedType(QualType T) const
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1920
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
CanQualType getSignedSizeType() const
Return the unique signed counterpart of the integer type corresponding to size_t.
QualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
Definition: ASTContext.h:2132
unsigned char getFixedPointScale(QualType Ty) const
QualType adjustStringLiteralBaseType(QualType StrLTy) const
CanQualType Char8Ty
Definition: ASTContext.h:1166
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
CanQualType HalfTy
Definition: ASTContext.h:1184
bool isDependenceAllowed() const
Definition: ASTContext.h:840
QualType getConstantMatrixType(QualType ElementType, unsigned NumRows, unsigned NumColumns) const
Return the unique reference to the matrix type of the specified element type and size.
QualType isPromotableBitField(Expr *E) const
Whether this is a promotable bitfield reference according to C99 6.3.1.1p2, bullet 2 (and GCC extensi...
bool isSentinelNullExpr(const Expr *E)
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2486
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:4421
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2718
Wrapper for source info for arrays.
Definition: TypeLoc.h:1592
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3591
QualType getElementType() const
Definition: Type.h:3589
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition: Expr.h:6475
Attr - This represents one attribute.
Definition: Attr.h:43
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6556
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4324
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3909
Expr * getLHS() const
Definition: Expr.h:3959
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2189
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:4009
bool isComparisonOp() const
Definition: Expr.h:4010
StringRef getOpcodeStr() const
Definition: Expr.h:3975
bool isRelationalOp() const
Definition: Expr.h:4004
SourceLocation getOperatorLoc() const
Definition: Expr.h:3951
bool isCompoundAssignmentOp() const
Definition: Expr.h:4053
bool isMultiplicativeOp() const
Definition: Expr.h:3994
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:2142
bool isShiftOp() const
Definition: Expr.h:3998
Expr * getRHS() const
Definition: Expr.h:3961
bool isEqualityOp() const
Definition: Expr.h:4007
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:4895
bool isBitwiseOp() const
Definition: Expr.h:4001
bool isAdditiveOp() const
Definition: Expr.h:3996
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:2214
Opcode getOpcode() const
Definition: Expr.h:3954
bool isAssignmentOp() const
Definition: Expr.h:4048
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2151
static bool isBitwiseOp(Opcode Opc)
Definition: Expr.h:4000
A binding in a decomposition declaration.
Definition: DeclCXX.h:4125
A class which contains all the information about a particular captured value.
Definition: Decl.h:4480
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4474
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.cpp:5252
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition: Decl.h:4556
void setBlockMissingReturnType(bool val=true)
Definition: Decl.h:4613
void setIsVariadic(bool value)
Definition: Decl.h:4550
SourceLocation getCaretLocation() const
Definition: Decl.h:4547
void setBody(CompoundStmt *B)
Definition: Decl.h:4554
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:4560
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition: Decl.cpp:5263
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5439
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6414
Pointer to a block type.
Definition: Type.h:3408
This class is used for builtin types like 'int'.
Definition: Type.h:3034
bool isSVEBool() const
Definition: Type.h:3111
Kind getKind() const
Definition: Type.h:3082
bool hasPtrArgsOrResult(unsigned ID) const
Determines whether this builtin has a result or any arguments which are pointer types.
Definition: Builtins.h:207
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
bool isImmediate(unsigned ID) const
Returns true if this is an immediate (consteval) function.
Definition: Builtins.h:282
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:194
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:180
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:186
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:1906
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...
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2553
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2880
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition: DeclCXX.cpp:2996
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2318
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1268
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition: ExprCXX.cpp:1018
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1375
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:1072
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:1533
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2817
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
bool isVirtual() const
Definition: DeclCXX.h:2133
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2204
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:2387
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:81
SourceLocation getOperatorLoc() const
Returns the location of the operator symbol in the expression.
Definition: ExprCXX.h:149
SourceRange getSourceRange() const
Definition: ExprCXX.h:161
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:1237
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:607
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:614
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:2024
bool hasDefinition() const
Definition: DeclCXX.h:572
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:210
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:215
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:123
SourceRange getRange() const
Definition: DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:84
bool isSet() const
Deprecated.
Definition: DeclSpec.h:228
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:149
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:95
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:213
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:208
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:129
Represents the this expression in C++.
Definition: ExprCXX.h:1152
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2874
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3068
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3081
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:1492
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:3047
void computeDependence()
Compute and set dependence bits.
Definition: Expr.h:3087
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:3055
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:3058
void setNumArgsUnsafe(unsigned NewNumArgs)
Bluntly set a new number of arguments without doing any checks whatsoever.
Definition: Expr.h:3109
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition: Expr.h:3100
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:3547
const char * getCastKindName() const
Definition: Expr.h:3595
CharLiteralParser - Perform interpretation and semantic analysis of a character literal.
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
unsigned getValue() const
Definition: Expr.h:1615
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4641
void mergeFrom(CleanupInfo Rhs)
Definition: CleanupInfo.h:38
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
bool cleanupsHaveSideEffects() const
Definition: CleanupInfo.h:26
bool exprNeedsCleanups() const
Definition: CleanupInfo.h:24
Complex values, per C99 6.2.5p11.
Definition: Type.h:3145
QualType getElementType() const
Definition: Type.h:3155
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:4917
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3477
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1628
bool body_empty() const
Definition: Stmt.h:1672
Stmt * getStmtExprResult()
Definition: Stmt.h:1750
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4262
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3615
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3671
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3691
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1077
static ConstantResultStorageKind getStorageKind(const APValue &Value)
Definition: Expr.cpp:302
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition: Expr.cpp:378
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1127
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:350
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4232
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4253
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4250
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4582
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:1293
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1368
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2218
bool isRequiresExprBody() const
Definition: DeclBase.h:2174
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1334
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1854
bool isRecord() const
Definition: DeclBase.h:2169
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1990
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1768
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1637
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:2016
bool isFunctionOrMethod() const
Definition: DeclBase.h:2141
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1285
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1404
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition: Expr.h:1370
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition: Expr.h:1414
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1463
void setDecl(ValueDecl *NewD)
Definition: Expr.cpp:544
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition: Expr.h:1418
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
DeclarationNameInfo getNameInfo() const
Definition: Expr.h:1337
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: Expr.h:1386
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:488
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier,...
Definition: Expr.h:1348
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition: Expr.h:1352
ValueDecl * getDecl()
Definition: Expr.h:1333
SourceLocation getLocation() const
Definition: Expr.h:1341
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1360
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
T * getAttr() const
Definition: DeclBase.h:576
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:596
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:745
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:151
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:564
bool isInvalidDecl() const
Definition: DeclBase.h:591
SourceLocation getLocation() const
Definition: DeclBase.h:442
void setReferenced(bool R=true)
Definition: DeclBase.h:626
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1038
DeclContext * getDeclContext()
Definition: DeclBase.h:451
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:907
bool hasAttr() const
Definition: DeclBase.h:580
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:967
Kind getKind() const
Definition: DeclBase.h:445
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.
bool isIdentifier() const
Predicate functions for querying what type of name this is.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:786
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1989
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:800
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
DeclaratorContext getContext() const
Definition: DeclSpec.h:2075
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2086
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2333
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:531
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:939
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:713
Recursive AST visitor that supports extension via dynamic dispatch.
virtual bool TraverseTemplateArgument(const TemplateArgument &Arg)
Recursively visit a template argument and dispatch to the appropriate method for the argument type.
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2354
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2368
Represents a reference to #emded data.
Definition: Expr.h:4916
RAII object that enters a new expression evaluation context.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:6098
EnumDecl * getDecl() const
Definition: Type.h:6105
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3799
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:3826
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1446
This represents one expression.
Definition: Expr.h:110
LValueClassification
Definition: Expr.h:282
@ LV_ArrayTemporary
Definition: Expr.h:292
@ LV_ClassTemporary
Definition: Expr.h:291
@ LV_MemberFunction
Definition: Expr.h:289
@ LV_IncompleteVoidType
Definition: Expr.h:285
@ LV_Valid
Definition: Expr.h:283
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 isGLValue() const
Definition: Expr.h:280
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:3117
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...
static QualType findBoundMemberType(const Expr *expr)
Given an expression of bound-member type, find the type of the member.
Definition: Expr.cpp:3046
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:3095
void setType(QualType t)
Definition: Expr.h:143
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:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition: Expr.h:239
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:3090
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3078
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition: Expr.cpp:3099
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3086
bool isPRValue() const
Definition: Expr.h:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition: Expr.cpp:3310
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:826
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition: Expr.h:822
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:830
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
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:3587
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:221
bool isIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3070
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition: Expr.h:797
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:806
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:809
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition: Expr.h:812
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition: Expr.h:799
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:3963
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition: Expr.cpp:266
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:454
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
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:4215
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
Definition: Expr.h:457
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:469
isModifiableLvalueResult
Definition: Expr.h:297
@ MLV_DuplicateVectorComponents
Definition: Expr.h:301
@ MLV_LValueCast
Definition: Expr.h:303
@ MLV_InvalidMessageExpression
Definition: Expr.h:312
@ MLV_ConstQualifiedField
Definition: Expr.h:306
@ MLV_InvalidExpression
Definition: Expr.h:302
@ MLV_IncompleteType
Definition: Expr.h:304
@ MLV_Valid
Definition: Expr.h:298
@ MLV_ConstQualified
Definition: Expr.h:305
@ MLV_NoSetterProperty
Definition: Expr.h:309
@ MLV_ArrayTemporary
Definition: Expr.h:314
@ MLV_SubObjCPropertySetting
Definition: Expr.h:311
@ MLV_ConstAddrSpace
Definition: Expr.h:307
@ MLV_MemberFunction
Definition: Expr.h:310
@ MLV_NotObjectType
Definition: Expr.h:299
@ MLV_ArrayType
Definition: Expr.h:308
@ MLV_ClassTemporary
Definition: Expr.h:313
@ MLV_IncompleteVoidType
Definition: Expr.h:300
QualType getType() const
Definition: Expr.h:142
bool isOrdinaryOrBitFieldObject() const
Definition: Expr.h:448
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition: Expr.h:427
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:136
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:6354
ExtVectorType - Extended vector type.
Definition: Type.h:4126
Represents difference between two FPOptions values.
Definition: LangOptions.h:978
bool isFPConstrained() const
Definition: LangOptions.h:906
RoundingMode getRoundingMode() const
Definition: LangOptions.h:912
Represents a member of a struct/union/class.
Definition: Decl.h:3033
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3124
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3194
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3250
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:75
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:138
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:127
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:101
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:995
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1074
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:1044
const Expr * getSubExpr() const
Definition: Expr.h:1057
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:1935
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2672
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3723
bool isImmediateFunction() const
Definition: Decl.cpp:3295
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3883
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3638
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3741
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2796
QualType getReturnType() const
Definition: Decl.h:2720
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2371
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3498
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, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2124
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2808
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3989
bool isConsteval() const
Definition: Decl.h:2410
size_t param_size() const
Definition: Decl.h:2665
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3163
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition: Decl.cpp:3899
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition: Decl.h:2756
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4654
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5102
QualType desugar() const
Definition: Type.h:5646
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5568
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5382
bool isParamConsumed(unsigned I) const
Definition: Type.h:5582
unsigned getNumParams() const
Definition: Type.h:5355
QualType getParamType(unsigned i) const
Definition: Type.h:5357
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5479
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5366
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5362
ArrayRef< QualType > param_types() const
Definition: Type.h:5511
Declaration of a template function.
Definition: DeclTemplate.h:959
unsigned getNumParams() const
Definition: TypeLoc.h:1531
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1537
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1483
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1540
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1475
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4432
bool getCmseNSCall() const
Definition: Type.h:4482
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4506
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition: Type.h:4360
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
ExtInfo getExtInfo() const
Definition: Type.h:4655
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4651
QualType getReturnType() const
Definition: Type.h:4643
bool getCmseNSCallAttr() const
Definition: Type.h:4653
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4667
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4716
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:4515
One of these records is kept for each identifier that is lexed.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
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:1717
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3724
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2082
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:567
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3321
Describes an C or C++ initializer list.
Definition: Expr.h:5088
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.
Describes the sequence of initializations required to initialize a given object or reference with a s...
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.
Definition: SemaInit.cpp:7584
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:973
Represents the declaration of a label.
Definition: Decl.h:503
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
@ CX_Promoted
Implementation of complex division using algebraic formulas at higher precision.
Definition: LangOptions.h:461
FPEvalMethodKind
Possible float expression evaluation method choices.
Definition: LangOptions.h:299
@ FEM_Extended
Use extended type for fp arithmetic.
Definition: LangOptions.h:308
@ FEM_Double
Use the type double for fp arithmetic.
Definition: LangOptions.h:306
@ FEM_UnsetOnCommandLine
Used only for FE option processing; this is only used to indicate that the user did not specify an ex...
Definition: LangOptions.h:313
@ FEM_Source
Use the declared type for fp arithmetic.
Definition: LangOptions.h:304
@ 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...
Definition: LangOptions.h:499
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:534
bool isSubscriptPointerArithmetic() const
Definition: LangOptions.h:667
bool isSignedOverflowDefined() const
Definition: LangOptions.h:663
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:63
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:1023
static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Characters, const SourceManager &SM, const LangOptions &LangOpts)
AdvanceToTokenCharacter - If the current SourceLocation specifies a location at the start of a token,...
Definition: Lexer.h:399
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping '\' and " characters and ii) ...
Definition: Lexer.cpp:309
Represents the results of name lookup.
Definition: Lookup.h:46
bool wasNotFoundInCurrentInstantiation() const
Determine whether no result was found because we could not search into dependent base classes of the ...
Definition: Lookup.h:495
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:605
DeclClass * getAsSingle() const
Definition: Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition: Lookup.h:475
void setLookupName(DeclarationName Name)
Sets the name to look up.
Definition: Lookup.h:270
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
Definition: SemaLookup.cpp:484
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:664
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:568
bool isAmbiguous() const
Definition: Lookup.h:324
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:331
CXXRecordDecl * getNamingClass() const
Returns the 'naming class' for this lookup, i.e.
Definition: Lookup.h:452
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:275
void setNamingClass(CXXRecordDecl *Record)
Sets the 'naming class' for this lookup.
Definition: Lookup.h:457
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:575
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:634
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:265
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:255
A global _GUID constant.
Definition: DeclCXX.h:4307
MS property subscript expression.
Definition: ExprCXX.h:1004
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition: Expr.h:2796
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: Type.h:4196
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4210
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3236
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3425
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3319
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:1762
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3454
Expr * getBase() const
Definition: Expr.h:3313
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:642
This represents a decl that may have a name.
Definition: Decl.h:253
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:466
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1668
bool isExternallyVisible() const
Definition: Decl.h:412
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:376
Represent a C++ namespace.
Definition: Decl.h:551
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
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:1153
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1527
ivar_iterator ivar_begin() const
Definition: DeclObjC.h:1452
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:350
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7524
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition: ExprObjC.h:1487
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1951
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:549
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: ExprObjC.h:595
SourceLocation getLocation() const
Definition: ExprObjC.h:592
SourceLocation getOpLoc() const
Definition: ExprObjC.h:600
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:579
bool isArrow() const
Definition: ExprObjC.h:587
SourceLocation getEndLoc() const LLVM_READONLY
Definition: ExprObjC.h:598
const Expr * getBase() const
Definition: ExprObjC.h:583
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:941
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:418
ArrayRef< ParmVarDecl * > parameters() const
Definition: DeclObjC.h:373
QualType getReturnType() const
Definition: DeclObjC.h:329
bool isClassMethod() const
Definition: DeclObjC.h:434
Represents a pointer to an Objective C object.
Definition: Type.h:7580
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1833
qual_range quals() const
Definition: Type.h:7699
Represents a class type in Objective C.
Definition: Type.h:7326
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:177
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2083
bool allowsSizeofAlignof() const
Does this runtime allow sizeof or alignof on object types?
Definition: ObjCRuntime.h:332
bool allowsPointerArithmetic() const
Does this runtime allow pointer arithmetic on objects?
Definition: ObjCRuntime.h:340
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr * > exprs, SourceLocation RParenLoc)
Definition: Expr.cpp:1665
Helper class for OffsetOfExpr.
Definition: Expr.h:2413
void * getAsOpaquePtr() const
Definition: Ownership.h:90
static OpaquePtr getFromOpaquePtr(void *P)
Definition: Ownership.h:91
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition: Overload.h:1008
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1012
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1185
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:2983
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3044
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2170
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2191
const Expr * getSubExpr() const
Definition: Expr.h:2187
bool isProducedByFoldExpansion() const
Definition: Expr.h:2212
Expr * getExpr(unsigned Init)
Definition: Expr.h:5896
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4767
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5894
Represents a parameter to a function.
Definition: Decl.h:1725
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1854
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1758
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1858
QualType getOriginalType() const
Definition: Decl.cpp:2931
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:2922
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3023
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
QualType getPointeeType() const
Definition: Type.h:3208
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition: Expr.cpp:638
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition: Expr.cpp:678
SourceLocation getLastFPEvalPragmaLocation() const
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token's location and length to ...
LangOptions::FPEvalMethodKind getCurrentFPEvalMethod() const
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
uint8_t getSpellingOfSingleCharacterNumericConstant(const Token &Tok, bool *Invalid=nullptr) const
Given a Token Tok that is a numeric constant with length 1, return the value of constant as an unsign...
SourceManager & getSourceManager() const
bool isMacroDefined(StringRef Id)
const TargetInfo & getTargetInfo() const
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
bool isCodeCompletionEnabled() const
Determine if we are performing code completion.
IdentifierTable & getIdentifierTable()
const LangOptions & getLangOpts() const
DiagnosticsEngine & getDiagnostics() const
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6546
A (possibly-)qualified type.
Definition: Type.h:929
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:8015
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8020
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:8078
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3521
@ DK_nontrivial_c_struct
Definition: Type.h:1524
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2867
bool isAddressSpaceOverlapping(QualType T, const ASTContext &Ctx) const
Returns true if address space qualifiers overlap with T address space qualifiers.
Definition: Type.h:1411
QualType withConst() const
Definition: Type.h:1154
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7931
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8057
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:8072
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7971
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:2649
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1433
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:8134
QualType getCanonicalType() const
Definition: Type.h:7983
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8025
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2885
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:1174
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C.
Definition: Type.h:8141
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8004
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:8052
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition: Type.cpp:1663
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1531
bool isCanonical() const
Definition: Type.h:7988
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1304
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1327
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2641
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: Type.h:8114
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7963
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:8066
The collection of all-type qualifiers we support.
Definition: Type.h:324
unsigned getCVRQualifiers() const
Definition: Type.h:481
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:488
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:354
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:357
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:360
void removeObjCLifetime()
Definition: Type.h:544
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:720
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: Type.h:701
void removeAddressSpace()
Definition: Type.h:589
void setAddressSpace(LangAS space)
Definition: Type.h:584
ObjCLifetime getObjCLifetime() const
Definition: Type.h:538
Qualifiers withoutObjCLifetime() const
Definition: Type.h:526
Qualifiers withoutObjCGCAttr() const
Definition: Type.h:521
LangAS getAddressSpace() const
Definition: Type.h:564
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:743
Represents a struct/union/class.
Definition: Decl.h:4148
field_range fields() const
Definition: Decl.h:4354
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
RecordDecl * getDecl() const
Definition: Type.h:6082
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition: Expr.cpp:5218
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:215
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
unsigned getFlags() const
getFlags - Return the flags for this scope.
Definition: Scope.h:263
@ ContinueScope
This is a while, do, for, which can have continue statements embedded into it.
Definition: Scope.h:59
@ ControlScope
The controlling scope in a if/switch/while/for statement.
Definition: Scope.h:66
@ BreakScope
This is a while, do, switch, for, etc that can have break statements embedded into it.
Definition: Scope.h:55
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:63
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool isUnarySelector() const
A generic diagnostic builder for errors which may or may not be deferred.
Definition: SemaBase.h:110
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaBase.cpp:32
Sema & SemaRef
Definition: SemaBase.h:40
void RecordImplicitHostDeviceFuncUsedByDevice(const FunctionDecl *FD)
Record FD if it is a CUDA/HIP implicit host device function used on device side in device compilation...
Definition: SemaCUDA.cpp:704
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:134
bool CheckCall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition: SemaCUDA.cpp:880
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition: SemaCUDA.h:120
ExprResult ActOnOutParamExpr(ParmVarDecl *Param, Expr *Arg)
Definition: SemaHLSL.cpp:2425
void emitLogicalOperatorFixIt(Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Definition: SemaHLSL.cpp:632
QualType handleVectorBinOpConversion(ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Definition: SemaHLSL.cpp:565
ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose=true, bool DiagnoseCFAudited=false, BinaryOperatorKind Opc=BO_PtrMemD)
Checks for invalid conversions and casts between retainable pointers and other pointer kinds for ARC ...
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures.
Definition: SemaObjC.h:854
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
Definition: SemaObjC.cpp:1260
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
Definition: SemaObjC.cpp:1161
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...
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
ExprResult ActOnArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, Expr *Length, SourceLocation RBLoc)
Checks and creates an Array Section used in an OpenACC construct/clause.
ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig)
Given the potential call expression Call, determine if there is a specialization via the OpenMP decla...
void tryCaptureOpenMPLambdas(ValueDecl *V)
Function tries to capture lambda's captured variables in the OpenMP region before the original lambda...
OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) const
Check if the specified variable is used in 'private' clause.
VarDecl * isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo=false, unsigned StopAt=0)
Check if the specified variable is used in one of the private clauses (private, firstprivate,...
ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc)
bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const
Return true if the provided declaration VD should be captured by reference.
bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified variable is captured by 'target' directive.
bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, unsigned CaptureLevel) const
Check if the specified global variable must be captured by outer capture regions.
bool isInOpenMPDeclareTargetContext() const
Return true inside OpenMP declare target region.
Definition: SemaOpenMP.h:371
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
const ValueDecl * getOpenMPDeclareMapperVarName() const
ExprResult checkAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS)
ExprResult checkIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op)
Check an increment or decrement of a pseudo-object expression.
ExprResult checkRValue(Expr *E)
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8041
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:12118
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7222
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T)
Definition: SemaExpr.cpp:17134
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:17140
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:463
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...
Definition: SemaExpr.cpp:14555
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6394
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition: Sema.h:7794
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:13127
void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:731
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
Definition: SemaExpr.cpp:15821
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:7844
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15498
bool isAlwaysConstantEvaluatedContext() const
Definition: Sema.h:7762
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:868
bool isAttrContext() const
Definition: Sema.h:6462
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Definition: SemaDecl.cpp:15177
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:7837
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8983
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition: Sema.h:9022
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:8991
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:412
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19647
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13158
VariadicCallType
Definition: Sema.h:2308
@ VariadicDoesNotApply
Definition: Sema.h:2313
@ VariadicFunction
Definition: Sema.h:2309
@ VariadicMethod
Definition: Sema.h:2311
@ VariadicConstructor
Definition: Sema.h:2312
@ VariadicBlock
Definition: Sema.h:2310
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2452
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:7040
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
@ NTCUC_CompoundLiteral
Definition: Sema.h:3631
@ NTCUC_Assignment
Definition: Sema.h:3629
@ NTCUC_FunctionReturn
Definition: Sema.h:3621
@ NTCUC_LValueToRValueVolatile
Definition: Sema.h:3635
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)
Definition: SemaExpr.cpp:7544
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.
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...
Definition: SemaExpr.cpp:2338
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition: Sema.h:1125
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:15840
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.
Definition: SemaExpr.cpp:17452
void ActOnStmtExprError()
Definition: SemaExpr.cpp:15846
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false, ArrayRef< const Expr * > StopAt={})
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
Definition: SemaExpr.cpp:20164
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
Definition: SemaExpr.cpp:1557
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
Definition: SemaExpr.cpp:12167
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
Definition: SemaDecl.cpp:16415
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition: Sema.h:855
SemaCUDA & CUDA()
Definition: Sema.h:1070
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17387
ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr=false)
CheckBooleanCondition - Diagnose problems involving the use of the given expression as a boolean cond...
Definition: SemaExpr.cpp:20380
ConditionKind
Definition: Sema.h:7344
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
@ Switch
An integral condition for a 'switch' statement.
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2676
bool needsRebuildOfDefaultArgOrInit() const
Definition: Sema.h:7782
SourceLocation LocationOfExcessPrecisionNotSatisfied
Definition: Sema.h:7924
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:848
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2290
Preprocessor & getPreprocessor() const
Definition: Sema.h:530
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition: Sema.h:6440
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2159
QualType GetSignedSizelessVectorType(QualType V)
Definition: SemaExpr.cpp:12726
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:7913
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3538
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition: Sema.h:7825
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)
Definition: SemaExpr.cpp:18430
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=NoFold)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:17145
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
Definition: SemaExpr.cpp:6682
QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion, bool AllowBoolOperation, bool ReportInvalid)
type checking for vector binary operators.
Definition: SemaExpr.cpp:10143
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:1658
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types? I.e.
Definition: SemaExpr.cpp:7518
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)
Definition: SemaExpr.cpp:15859
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.
bool CheckConceptUseInDefinition(ConceptDecl *Concept, SourceLocation Loc)
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16502
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition: Sema.h:6452
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:1568
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
Definition: SemaExpr.cpp:784
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
ExprResult CheckUnevaluatedOperand(Expr *E)
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
Definition: SemaExpr.cpp:1042
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Look for instances where it is likely the comma operator is confused with another operator.
Definition: SemaExpr.cpp:13879
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Definition: SemaExpr.cpp:4998
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
std::vector< Token > ExpandFunctionLocalPredefinedMacros(ArrayRef< Token > Toks)
Definition: SemaExpr.cpp:1999
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
Definition: SemaExpr.cpp:7628
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:14159
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15164
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:1102
ASTContext & Context
Definition: Sema.h:908
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:7749
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
Definition: SemaCast.cpp:2700
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12962
QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS)
the following "Check" methods will return a valid/converted QualType or a null QualType (indicating a...
Definition: SemaExpr.cpp:9833
bool DiagIfReachable(SourceLocation Loc, ArrayRef< const Stmt * > Stmts, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the statements's reachability analysis.
Definition: SemaExpr.cpp:20175
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:11504
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:528
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...
Definition: SemaExpr.cpp:7893
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)
Definition: SemaExpr.cpp:21153
SemaObjC & ObjC()
Definition: Sema.h:1110
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
Definition: SemaExpr.cpp:12997
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:2668
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....
AllowFoldKind
Definition: Sema.h:7236
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1497
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19660
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:752
bool isImmediateFunctionContext() const
Definition: Sema.h:7774
ASTContext & getASTContext() const
Definition: Sema.h:531
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition: SemaExpr.cpp:762
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)
Definition: SemaExpr.cpp:15777
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.
Definition: SemaExpr.cpp:18930
void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var)
Mark a variable referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:19908
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
Definition: SemaExpr.cpp:15295
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()
Definition: SemaExpr.cpp:17820
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9576
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:690
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition: SemaExpr.cpp:867
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
Definition: SemaExpr.cpp:3486
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
Definition: SemaExpr.cpp:6199
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3101
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)
Definition: SemaExpr.cpp:7054
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:15827
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:5599
@ None
This is not a defaultable comparison operator.
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:7909
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:13043
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:816
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1573
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2204
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)
Definition: SemaExpr.cpp:16115
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 *.
Definition: SemaExpr.cpp:1671
AssumedTemplateKind
Definition: Sema.h:11104
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
Definition: SemaExpr.cpp:1969
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:507
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...
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition: Sema.h:671
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:7809
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition: SemaStmt.cpp:420
FPOptions & getCurFPFeatures()
Definition: Sema.h:526
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition: Sema.h:7907
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20411
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:81
@ UPPC_Block
Block expression.
Definition: Sema.h:13950
const LangOptions & getLangOpts() const
Definition: Sema.h:524
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)
TypoExpr * CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
QualType CheckCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12194
CastKind PrepareScalarCast(ExprResult &src, QualType destType)
Prepares for a scalar cast, performing all the necessary stages except the final cast and returning t...
Definition: SemaExpr.cpp:7292
SemaOpenACC & OpenACC()
Definition: Sema.h:1115
ReuseLambdaContextDecl_t
Definition: Sema.h:6524
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.
Definition: SemaDecl.cpp:6573
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void MarkExpressionAsImmediateEscalating(Expr *E)
Definition: SemaExpr.cpp:17483
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
Definition: SemaExpr.cpp:2252
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.
Definition: SemaExpr.cpp:20049
Preprocessor & PP
Definition: Sema.h:907
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:10939
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5710
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.
Definition: SemaExpr.cpp:6475
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
Definition: SemaExpr.cpp:14131
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
Definition: SemaExpr.cpp:16776
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
Definition: SemaExpr.cpp:4711
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:1978
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
Definition: SemaExpr.cpp:7533
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.
const LangOptions & LangOpts
Definition: Sema.h:906
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
Definition: SemaExpr.cpp:15929
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2404
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.
Definition: SemaExpr.cpp:6732
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17504
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:7547
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:6029
SemaHLSL & HLSL()
Definition: Sema.h:1075
void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor)
Define the specified inheriting constructor.
void CheckUnusedVolatileAssignment(Expr *E)
Check whether E, which is either a discarded-value expression or an unevaluated operand,...
Definition: SemaExpr.cpp:17468
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition: Sema.h:15153
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:205
@ OperatorInExpression
The '<=>' operator was used in an expression and a builtin operator was selected.
bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid)
Determine whether the use of this declaration is valid, without emitting diagnostics.
Definition: SemaExpr.cpp:73
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:20059
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.
Definition: SemaExpr.cpp:9857
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:6473
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:6055
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1580
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl=nullptr)
Retrieve a version of the type 'T' that is elaborated by Keyword, qualified by the nested-name-specif...
Definition: SemaType.cpp:9531
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:13527
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:936
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
Definition: SemaExpr.cpp:15740
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:782
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)
Definition: SemaCast.cpp:3351
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:939
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
Definition: SemaExpr.cpp:3638
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
Definition: SemaExpr.cpp:10406
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.
Definition: SemaExpr.cpp:9628
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...
Definition: SemaStmt.cpp:1708
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:6470
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition: Sema.cpp:2142
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:640
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3189
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition: Sema.h:7778
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
Definition: SemaExpr.cpp:7279
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 *.
Definition: SemaExpr.cpp:1639
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
Definition: SemaExpr.cpp:16291
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7669
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2359
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1043
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:7530
ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path)
Check a cast of an unknown-any type.
Definition: SemaExpr.cpp:20874
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:12142
@ VAK_Invalid
Definition: Sema.h:7533
@ VAK_Valid
Definition: Sema.h:7529
@ VAK_ValidInCXX11
Definition: Sema.h:7530
@ VAK_MSVCUndefined
Definition: Sema.h:7532
@ VAK_Undefined
Definition: Sema.h:7531
SemaOpenCL & OpenCL()
Definition: Sema.h:1120
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5787
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:13536
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:16658
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...
Definition: SemaExpr.cpp:7915
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.
void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T)
Mark all of the declarations referenced within a particular AST node as referenced.
Definition: SemaExpr.cpp:20110
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:7770
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1548
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:7573
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition: Sema.h:7617
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition: Sema.h:7583
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition: Sema.h:7641
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition: Sema.h:7646
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition: Sema.h:7633
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:7612
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:7591
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition: Sema.h:7650
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:7575
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition: Sema.h:7602
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:7654
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition: Sema.h:7587
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition: Sema.h:7596
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:7608
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition: Sema.h:7629
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition: Sema.h:7623
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition: Sema.h:7579
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition: Sema.h:7637
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
Definition: SemaDecl.cpp:8427
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition: Sema.h:7392
@ ACK_Arithmetic
An arithmetic operation.
Definition: Sema.h:7394
@ ACK_CompAssign
A compound assignment expression.
Definition: Sema.h:7402
@ ACK_BitwiseOp
A bitwise operation.
Definition: Sema.h:7396
@ ACK_Conditional
A conditional (?:) operator.
Definition: Sema.h:7400
@ ACK_Comparison
A comparison.
Definition: Sema.h:7398
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20008
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
Definition: SemaExpr.cpp:2896
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4109
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16743
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition: Sema.h:6282
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20964
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17367
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:13483
SourceManager & getSourceManager() const
Definition: Sema.h:529
TryCaptureKind
Definition: Sema.h:6586
@ TryCapture_Implicit
Definition: Sema.h:6587
@ TryCapture_ExplicitByRef
Definition: Sema.h:6589
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
Definition: SemaExpr.cpp:6710
bool CheckVecStepExpr(Expr *E)
Definition: SemaExpr.cpp:4390
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 ?: operation.
Definition: SemaExpr.cpp:8776
QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
CheckVectorCompareOperands - vector comparisons are a clang extension that operates on extended vecto...
Definition: SemaExpr.cpp:12738
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide)
Definition: SemaExpr.cpp:10581
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
Definition: SemaExpr.cpp:19624
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13718
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...
@ NTCUK_Destruct
Definition: Sema.h:3647
@ NTCUK_Copy
Definition: Sema.h:3648
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition: Sema.h:7923
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20245
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5487
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7563
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
Definition: SemaExpr.cpp:7600
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition: Sema.cpp:2190
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 ?: under C++ semantics.
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:6280
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:216
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.
Definition: SemaDecl.cpp:8262
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....
Definition: SemaExpr.cpp:2048
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14938
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
Definition: SemaExpr.cpp:15271
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)
Definition: SemaExpr.cpp:7702
@ CTK_ErrorRecovery
Definition: Sema.h:9377
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2344
bool isConstantEvaluatedContext() const
Definition: Sema.h:2144
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 mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3083
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12567
ASTConsumer & Consumer
Definition: Sema.h:909
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:4220
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:6477
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:121
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:944
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:13519
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5120
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3534
ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, StringLiteral *BinaryData)
Definition: SemaExpr.cpp:16784
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
Definition: SemaExpr.cpp:12683
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.
Definition: SemaExpr.cpp:8403
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition: Sema.h:6224
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ DiscardedStatement
The current expression occurs within a discarded statement.
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range)
Definition: SemaCast.cpp:2050
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.
Definition: SemaExpr.cpp:6703
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
Definition: SemaExpr.cpp:4617
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5703
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.
Definition: SemaExpr.cpp:20252
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
Definition: SemaExpr.cpp:4227
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16495
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
Definition: SemaType.cpp:5816
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9068
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:871
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:20894
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.
Definition: SemaExpr.cpp:19256
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:7737
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:7760
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr)
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17897
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:19248
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7910
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1308
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
Definition: SemaExpr.cpp:7649
SourceManager & SourceMgr
Definition: Sema.h:911
@ TemplateNameIsRequired
Definition: Sema.h:11081
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
Definition: SemaExpr.cpp:4703
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
Definition: SemaExpr.cpp:7810
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.
Definition: SemaExpr.cpp:2393
DiagnosticsEngine & Diags
Definition: Sema.h:910
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:525
FPOptions CurFPFeatures
Definition: Sema.h:904
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:516
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
Definition: SemaLambda.cpp:691
bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType)
Are the two types lax-compatible vector types? That is, given that one of them is a vector,...
Definition: SemaExpr.cpp:7586
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9718
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
Definition: SemaExpr.cpp:3598
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5581
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
Definition: SemaExpr.cpp:20295
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
void PopDeclContext()
Definition: SemaDecl.cpp:1315
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13094
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:6059
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:15854
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...
Definition: SemaExpr.cpp:997
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
Definition: SemaExpr.cpp:6074
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12799
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8879
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
Definition: SemaDecl.cpp:13113
ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope)
ActOnBlockStmtExpr - This is called when the body of a block statement literal was successfully compl...
Definition: SemaExpr.cpp:16301
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:562
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
Definition: SemaExpr.cpp:20030
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...
Definition: SemaExpr.cpp:16812
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,...
Definition: SemaExpr.cpp:18078
ExprResult ActOnStmtExprResult(ExprResult E)
Definition: SemaExpr.cpp:15898
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4756
bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef< Expr * > Args, SmallVectorImpl< Expr * > &AllArgs, VariadicCallType CallType=VariadicDoesNotApply, bool AllowExplicit=false, bool IsListInitialization=false)
GatherArgumentsForCall - Collector argument expressions for various form of call prototypes.
Definition: SemaExpr.cpp:5953
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
Definition: SemaLambda.cpp:282
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
Definition: SemaExpr.cpp:20351
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1961
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21161
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15345
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3672
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
Definition: SemaExpr.cpp:2969
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7254
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:16153
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
Definition: SemaExpr.cpp:4829
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
Definition: SemaExpr.cpp:14768
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9154
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
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.
Definition: SemaExpr.cpp:6437
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...
Definition: SemaExpr.cpp:4686
QualType PreferredConditionType(ConditionKind K) const
Definition: Sema.h:7490
void clearDelayedTypo(TypoExpr *TE)
Clears the state of the given TypoExpr.
@ LOLR_ErrorNoDiagnostic
The lookup found no match but no diagnostic was issued.
Definition: Sema.h:9036
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition: Sema.h:9042
@ LOLR_Error
The lookup resulted in an error.
Definition: Sema.h:9034
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition: Sema.h:9039
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition: Sema.h:9050
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition: Sema.h:9046
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:16182
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:10620
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
std::pair< ValueDecl *, SourceLocation > PendingImplicitInstantiation
An entity for which implicit template instantiation is required.
Definition: Sema.h:13515
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.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2750
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 ...
Definition: SemaDecl.cpp:15823
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...
Definition: SemaDecl.cpp:13365
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:11062
static ConditionResult ConditionError()
Definition: Sema.h:7331
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ActOnConvertVectorExpr - create a new convert-vector expression from the provided arguments.
Definition: SemaExpr.cpp:6724
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
const TypoExprState & getTypoExprState(TypoExpr *TE) const
ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType)
Type-check an expression that's being passed to an __unknown_anytype parameter.
Definition: SemaExpr.cpp:20898
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 ...
Definition: SemaExpr.cpp:5813
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:16096
SemaPseudoObject & PseudoObject()
Definition: Sema.h:1135
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2335
FullExprArg MakeFullExpr(Expr *Arg)
Definition: Sema.h:7287
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy)
Definition: SemaCast.cpp:2713
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:17905
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7186
bool isCheckingDefaultArgumentOrInitializer() const
Definition: Sema.h:7786
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr, bool SkipImmediateInvocations=true)
Instantiate or parse a C++ default argument expression as necessary.
Definition: SemaExpr.cpp:5332
ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl=nullptr, bool RecoverUncorrectedTypos=false, llvm::function_ref< ExprResult(Expr *)> Filter=[](Expr *E) -> ExprResult { return E;})
Process any TypoExprs in the given Expr and its children, generating diagnostics as appropriate and r...
void DiagnoseImmediateEscalatingReason(FunctionDecl *FD)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8261
void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType)
FinalizeVarWithDestructor - Prepare for calling destructor on the constructed variable.
ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc)
Definition: SemaExpr.cpp:5006
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)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4810
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition: Overload.h:292
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:303
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:383
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:4466
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:185
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:357
StmtClass getStmtClass() const
Definition: Stmt.h:1380
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:333
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
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:1778
unsigned getLength() const
Definition: Expr.h:1895
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1870
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1187
StringRef getString() const
Definition: Expr.h:1855
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3667
bool isUnion() const
Definition: Decl.h:3770
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3788
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
Exposes information about the current target.
Definition: TargetInfo.h:220
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:320
virtual size_t getMaxBitIntWidth() const
Definition: TargetInfo.h:682
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
Definition: TargetInfo.h:1002
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:286
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:478
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:519
IntType getSizeType() const
Definition: TargetInfo.h:377
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:529
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1583
virtual bool supportsExtendIntArgs() const
Whether the option -fextend-arguments={32,64} is supported on the target.
Definition: TargetInfo.h:1676
virtual BuiltinVaListKind getBuiltinVaListKind() const =0
Returns the kind of __builtin_va_list type that should be used with this target.
bool hasBuiltinMSVaList() const
Returns whether or not type __builtin_ms_va_list type is available on this target.
Definition: TargetInfo.h:1042
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
unsigned getIntMaxTWidth() const
Return the size of intmax_t and uintmax_t for this target, in bits.
Definition: TargetInfo.h:879
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:524
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1493
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:399
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
Token - This structure provides full information about a lexed token.
Definition: Token.h:36
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition: Token.h:132
unsigned getLength() const
Definition: Token.h:135
void setKind(tok::TokenKind K)
Definition: Token.h:95
tok::TokenKind getKind() const
Definition: Token.h:94
void setLocation(SourceLocation L)
Definition: Token.h:140
void startToken()
Reset all flags to cleared.
Definition: Token.h:177
void setIdentifierInfo(IdentifierInfo *II)
Definition: Token.h:196
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Represents a declaration of a type.
Definition: Decl.h:3370
const Type * getTypeForDecl() const
Definition: Decl.h:3395
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3398
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:206
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:153
SourceRange getLocalSourceRange() const
Get the local source range.
Definition: TypeLoc.h:159
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2715
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7902
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7913
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1828
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2441
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1916
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition: Type.h:8571
bool isBlockPointerType() const
Definition: Type.h:8200
bool isVoidType() const
Definition: Type.h:8510
bool isBooleanType() const
Definition: Type.h:8638
bool isFunctionReferenceType() const
Definition: Type.h:8233
bool isObjCBuiltinType() const
Definition: Type.h:8379
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:1933
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8688
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:773
bool isIncompleteArrayType() const
Definition: Type.h:8266
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:8486
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:710
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2105
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:8668
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:2055
bool isVoidPointerType() const
Definition: Type.cpp:698
const ComplexType * getAsComplexIntegerType() const
Definition: Type.cpp:731
bool isArrayType() const
Definition: Type.h:8258
bool isCharType() const
Definition: Type.cpp:2123
bool isFunctionPointerType() const
Definition: Type.h:8226
bool isArithmeticType() const
Definition: Type.cpp:2315
bool isConstantMatrixType() const
Definition: Type.h:8320
bool isPointerType() const
Definition: Type.h:8186
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8550
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2517
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8800
bool isReferenceType() const
Definition: Type.h:8204
bool isSignedFixedPointType() const
Return true if this is a fixed point type that is signed according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8591
bool isEnumeralType() const
Definition: Type.h:8290
bool isScalarType() const
Definition: Type.h:8609
bool isVariableArrayType() const
Definition: Type.h:8270
bool isSizelessBuiltinType() const
Definition: Type.cpp:2475
bool isClkEventT() const
Definition: Type.h:8401
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2554
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2092
bool isObjCQualifiedIdType() const
Definition: Type.h:8349
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8625
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2270
bool isExtVectorType() const
Definition: Type.h:8302
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2159
bool isExtVectorBoolType() const
Definition: Type.h:8306
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2593
bool isImageType() const
Definition: Type.h:8413
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:8504
bool isPipeType() const
Definition: Type.h:8420
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isBitIntType() const
Definition: Type.h:8424
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8479
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8282
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool isAnyComplexType() const
Definition: Type.h:8294
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8563
bool isHalfType() const
Definition: Type.h:8514
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8579
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2361
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:2330
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:8492
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2220
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2501
bool isQueueT() const
Definition: Type.h:8405
bool isMemberPointerType() const
Definition: Type.h:8240
bool isAtomicType() const
Definition: Type.h:8341
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:8651
bool isObjCIdType() const
Definition: Type.h:8361
bool isMatrixType() const
Definition: Type.h:8316
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2724
bool isComplexIntegerType() const
Definition: Type.cpp:716
bool isUnscopedEnumerationType() const
Definition: Type.cpp:2116
bool isObjCObjectType() const
Definition: Type.h:8332
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:4958
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8786
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:5048
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8644
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2396
bool isFunctionType() const
Definition: Type.h:8182
bool isObjCObjectPointerType() const
Definition: Type.h:8328
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2292
bool isMemberFunctionPointerType() const
Definition: Type.h:8244
bool isUnsignedFixedPointType() const
Return true if this is a fixed point type that is unsigned according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8605
bool isVectorType() const
Definition: Type.h:8298
bool isObjCQualifiedClassType() const
Definition: Type.h:8355
bool isObjCClassType() const
Definition: Type.h:8367
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2300
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2541
ScalarTypeKind
Definition: Type.h:2679
@ STK_FloatingComplex
Definition: Type.h:2688
@ STK_Floating
Definition: Type.h:2686
@ STK_BlockPointer
Definition: Type.h:2681
@ STK_Bool
Definition: Type.h:2684
@ STK_ObjCObjectPointer
Definition: Type.h:2682
@ STK_FixedPoint
Definition: Type.h:2689
@ STK_IntegralComplex
Definition: Type.h:2687
@ STK_CPointer
Definition: Type.h:2680
@ STK_Integral
Definition: Type.h:2685
@ STK_MemberPointer
Definition: Type.h:2683
bool isFloatingType() const
Definition: Type.cpp:2283
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:2230
bool isAnyPointerType() const
Definition: Type.h:8194
bool isRealType() const
Definition: Type.cpp:2306
TypeClass getTypeClass() const
Definition: Type.h:2341
bool isSubscriptableVectorType() const
Definition: Type.h:8312
bool isSamplerT() const
Definition: Type.h:8393
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
bool isNullPtrType() const
Definition: Type.h:8543
bool isRecordType() const
Definition: Type.h:8286
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4763
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2513
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.
bool isOverloaded() const
NamedDecl * getFoundDecl() const
Get the correction declaration found by name lookup (before we looked through using shadow declaratio...
TypoExpr - Internal placeholder for expressions where typo correction still needs to be performed and...
Definition: Expr.h:6837
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2622
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2232
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition: Expr.h:2281
Expr * getSubExpr() const
Definition: Expr.h:2277
Opcode getOpcode() const
Definition: Expr.h:2272
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1425
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:4952
bool isIncrementDecrementOp() const
Definition: Expr.h:2333
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4364
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1028
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3203
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:419
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3943
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition: ExprCXX.cpp:1666
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:1628
A set of unresolved declarations.
Definition: UnresolvedSet.h:62
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:637
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:4750
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
void setType(QualType newType)
Definition: Decl.h:683
QualType getType() const
Definition: Decl.h:682
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3392
QualType getType() const
Definition: Value.cpp:234
Represents a variable declaration or definition.
Definition: Decl.h:882
bool hasInit() const
Definition: Decl.cpp:2387
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2246
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1522
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1177
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:2458
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:2883
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1495
const Expr * getInit() const
Definition: Decl.h:1319
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1168
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1135
@ TLS_None
Not a TLS variable.
Definition: Decl.h:902
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1246
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2364
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:2500
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:2776
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1213
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:2755
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2874
Declaration of a variable template.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3808
Expr * getSizeExpr() const
Definition: Type.h:3827
Represents a GCC generic vector type.
Definition: Type.h:4034
unsigned getNumElements() const
Definition: Type.h:4049
VectorKind getVectorKind() const
Definition: Type.h:4054
QualType getElementType() const
Definition: Type.h:4048
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:790
Scope * TheScope
TheScope - This is the scope for the block itself, which contains arguments etc.
Definition: ScopeInfo.h:796
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition: ScopeInfo.h:800
ValueDecl * getVariable() const
Definition: ScopeInfo.h:675
bool isBlockCapture() const
Definition: ScopeInfo.h:656
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:686
void markUsed(bool IsODRUse)
Definition: ScopeInfo.h:668
bool isInvalid() const
Definition: ScopeInfo.h:661
bool isThisCapture() const
Definition: ScopeInfo.h:649
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition: ScopeInfo.h:695
bool isCopyCapture() const
Definition: ScopeInfo.h:654
bool isNested() const
Definition: ScopeInfo.h:659
Retains information about a captured region.
Definition: ScopeInfo.h:816
unsigned short CapRegionKind
The kind of captured region.
Definition: ScopeInfo.h:831
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:745
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:732
bool ContainsUnexpandedParameterPack
Whether this contains an unexpanded parameter pack.
Definition: ScopeInfo.h:728
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
unsigned CXXThisCaptureIndex
CXXThisCaptureIndex - The (index+1) of the capture of 'this'; zero if 'this' is not captured.
Definition: ScopeInfo.h:718
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition: ScopeInfo.h:758
llvm::DenseMap< ValueDecl *, unsigned > CaptureMap
CaptureMap - A map of captured variables to (index+1) into Captures.
Definition: ScopeInfo.h:714
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:755
bool isVLATypeCaptured(const VariableArrayType *VAT) const
Determine whether the given variable-array type has been captured.
Definition: ScopeInfo.cpp:228
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:737
Capture & getCapture(ValueDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition: ScopeInfo.h:771
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:104
void recordUseOfWeak(const ExprT *E, bool IsRead=true)
Record that a weak object was accessed.
Definition: ScopeInfo.h:1087
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
Definition: ScopeInfo.cpp:160
void addBlock(const BlockDecl *BD)
Definition: ScopeInfo.h:493
llvm::SmallVector< AddrLabelExpr *, 4 > AddrLabels
The set of GNU address of label extension "&&label".
Definition: ScopeInfo.h:246
bool HasOMPDeclareReductionCombiner
True if current scope is for OpenMP declare reduction combiner.
Definition: ScopeInfo.h:135
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:884
bool lambdaCaptureShouldBeConst() const
Definition: ScopeInfo.cpp:251
void addPotentialCapture(Expr *VarExpr)
Add a variable that might potentially be captured by the lambda and therefore the enclosing lambdas.
Definition: ScopeInfo.h:989
void addPotentialThisCapture(SourceLocation Loc)
Definition: ScopeInfo.h:995
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:871
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition: ScopeInfo.h:892
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:879
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:874
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition: TokenKinds.h:89
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
Definition: OperatorKinds.h:21
@ OO_None
Not an overloaded operator.
Definition: OperatorKinds.h:22
bool isa(CodeGen::Address addr)
Definition: Address.h:328
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:212
@ CPlusPlus23
Definition: LangStandard.h:60
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:58
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
bool isTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:77
CUDAFunctionTarget
Definition: Cuda.h:145
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:336
@ Nullable
Values of this type can be null.
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
@ NonNull
Values of this type can never be null.
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:149
@ OK_VectorComponent
A vector component is an element or range of elements on a vector.
Definition: Specifiers.h:157
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition: Specifiers.h:161
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:151
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:154
@ OK_MatrixComponent
A matrix component is a single element of a matrix.
Definition: Specifiers.h:169
BinaryOperatorKind
@ 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.
@ IK_TemplateId
A template-id, e.g., f<int>.
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition: OpenMPKinds.h:28
std::optional< ComparisonCategoryType > getComparisonCategoryForBuiltinCmp(QualType T)
Get the comparison category that should be used when comparing values of type T.
@ CR_OpenMP
Definition: CapturedStmt.h:19
@ SC_Extern
Definition: Specifiers.h:251
@ SC_Register
Definition: Specifiers.h:257
@ SC_None
Definition: Specifiers.h:250
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:51
unsigned toTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:81
ExprResult ExprEmpty()
Definition: Ownership.h:271
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Result
The result type of a method or function.
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition: Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:139
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition: Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition: Overload.h:202
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:112
@ ICK_Identity
Identity conversion (no conversion)
Definition: Overload.h:106
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:109
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition: Overload.h:136
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:115
UnaryOperatorKind
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 ...
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
ExprResult ExprError()
Definition: Ownership.h:264
@ AR_Unavailable
Definition: DeclBase.h:76
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
CastKind
CastKind - The kind of operation required for a conversion.
AssignmentAction
Definition: Sema.h:210
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:91
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
const char * getTraitSpelling(ExpressionTrait T) LLVM_READONLY
Return the spelling of the type trait TT. Never null.
const FunctionProtoType * T
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition: Overload.h:270
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:276
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:284
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:273
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:280
StringLiteralKind
Definition: Expr.h:1749
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_X86VectorCall
Definition: Specifiers.h:283
@ CC_X86StdCall
Definition: Specifiers.h:280
@ CC_X86FastCall
Definition: Specifiers.h:281
@ AltiVecBool
is AltiVec 'vector bool ...'
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
@ AltiVecVector
is AltiVec vector
@ AltiVecPixel
is AltiVec 'vector Pixel'
@ Neon
is ARM Neon vector
@ Generic
not a target-specific vector type
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
SourceLocIdentKind
Definition: Expr.h:4797
@ None
No keyword precedes the qualified type name.
@ Other
Other implicit parameter.
PredefinedIdentKind
Definition: Expr.h:1975
@ Implicit
An implicit conversion.
CharacterLiteralKind
Definition: Expr.h:1589
@ AS_none
Definition: Specifiers.h:127
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition: Specifiers.h:173
@ NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition: Specifiers.h:183
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:177
@ NOUR_None
This is an odr-use.
Definition: Specifiers.h:175
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition: Specifiers.h:180
#define false
Definition: stdbool.h:26
ExprResult TransformSourceLocExpr(SourceLocExpr *E)
Definition: SemaExpr.cpp:5465
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
Definition: SemaExpr.cpp:5462
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
Definition: SemaExpr.cpp:5447
ExprResult TransformBlockExpr(BlockExpr *E)
Definition: SemaExpr.cpp:5457
ExprResult TransformLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5456
bool VisitSourceLocExpr(SourceLocExpr *E) override
Definition: SemaExpr.cpp:5421
bool VisitCXXConstructExpr(CXXConstructExpr *E) override
Definition: SemaExpr.cpp:5411
bool VisitCallExpr(CallExpr *E) override
Definition: SemaExpr.cpp:5405
const ASTContext & Context
Definition: SemaExpr.cpp:5398
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override
Definition: SemaExpr.cpp:5440
bool VisitLambdaExpr(LambdaExpr *E) override
Definition: SemaExpr.cpp:5432
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override
Definition: SemaExpr.cpp:5436
ImmediateCallVisitor(const ASTContext &Ctx)
Definition: SemaExpr.cpp:5399
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:4886
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:642
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:644
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:630
bool HasUndefinedBehavior
Whether the evaluation hit undefined behavior.
Definition: Expr.h:614
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:609
Extra information about a function prototype.
Definition: Type.h:5187
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5188
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:12670
Data structure used to record current or nested expression evaluation contexts.
Definition: Sema.h:6286
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition: Sema.h:6320
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition: Sema.h:6366
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition: Sema.h:6325
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:6333
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition: Sema.h:6329
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition: Sema.h:6339
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:6305
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:6343
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition: Sema.h:6291
unsigned NumTypos
The number of typos encountered during this expression evaluation context (i.e.
Definition: Sema.h:6299
ExpressionEvaluationContext Context
The expression evaluation context.
Definition: Sema.h:6288
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition: Sema.h:6295
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7851
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
uint64_t Width
Definition: ASTContext.h:159
Describes an entity that is being assigned.