clang 21.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/// UsualUnaryFPConversions - Promotes floating-point types according to the
780/// current language semantics.
782 QualType Ty = E->getType();
783 assert(!Ty.isNull() && "UsualUnaryFPConversions - missing type");
784
785 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
786 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
787 (getLangOpts().getFPEvalMethod() !=
790 switch (EvalMethod) {
791 default:
792 llvm_unreachable("Unrecognized float evaluation method");
793 break;
795 llvm_unreachable("Float evaluation method should be set by now");
796 break;
799 // Widen the expression to double.
800 return Ty->isComplexType()
803 CK_FloatingComplexCast)
804 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
805 break;
808 // Widen the expression to long double.
809 return Ty->isComplexType()
812 CK_FloatingComplexCast)
814 CK_FloatingCast);
815 break;
816 }
817 }
818
819 // Half FP have to be promoted to float unless it is natively supported
820 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
821 return ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast);
822
823 return E;
824}
825
826/// UsualUnaryConversions - Performs various conversions that are common to most
827/// operators (C99 6.3). The conversions of array and function types are
828/// sometimes suppressed. For example, the array->pointer conversion doesn't
829/// apply if the array is an argument to the sizeof or address (&) operators.
830/// In these instances, this routine should *not* be called.
832 // First, convert to an r-value.
834 if (Res.isInvalid())
835 return ExprError();
836
837 // Promote floating-point types.
838 Res = UsualUnaryFPConversions(Res.get());
839 if (Res.isInvalid())
840 return ExprError();
841 E = Res.get();
842
843 QualType Ty = E->getType();
844 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
845
846 // Try to perform integral promotions if the object has a theoretically
847 // promotable type.
849 // C99 6.3.1.1p2:
850 //
851 // The following may be used in an expression wherever an int or
852 // unsigned int may be used:
853 // - an object or expression with an integer type whose integer
854 // conversion rank is less than or equal to the rank of int
855 // and unsigned int.
856 // - A bit-field of type _Bool, int, signed int, or unsigned int.
857 //
858 // If an int can represent all values of the original type, the
859 // value is converted to an int; otherwise, it is converted to an
860 // unsigned int. These are called the integer promotions. All
861 // other types are unchanged by the integer promotions.
862
864 if (!PTy.isNull()) {
865 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
866 return E;
867 }
870 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
871 return E;
872 }
873 }
874 return E;
875}
876
877/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
878/// do not have a prototype. Arguments that have type float or __fp16
879/// are promoted to double. All other argument types are converted by
880/// UsualUnaryConversions().
882 QualType Ty = E->getType();
883 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
884
886 if (Res.isInvalid())
887 return ExprError();
888 E = Res.get();
889
890 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
891 // promote to double.
892 // Note that default argument promotion applies only to float (and
893 // half/fp16); it does not apply to _Float16.
894 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
895 if (BTy && (BTy->getKind() == BuiltinType::Half ||
896 BTy->getKind() == BuiltinType::Float)) {
897 if (getLangOpts().OpenCL &&
898 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
899 if (BTy->getKind() == BuiltinType::Half) {
900 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
901 }
902 } else {
903 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
904 }
905 }
906 if (BTy &&
907 getLangOpts().getExtendIntArgs() ==
912 E = (Ty->isUnsignedIntegerType())
913 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
914 .get()
915 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
917 "Unexpected typesize for LongLongTy");
918 }
919
920 // C++ performs lvalue-to-rvalue conversion as a default argument
921 // promotion, even on class types, but note:
922 // C++11 [conv.lval]p2:
923 // When an lvalue-to-rvalue conversion occurs in an unevaluated
924 // operand or a subexpression thereof the value contained in the
925 // referenced object is not accessed. Otherwise, if the glvalue
926 // has a class type, the conversion copy-initializes a temporary
927 // of type T from the glvalue and the result of the conversion
928 // is a prvalue for the temporary.
929 // FIXME: add some way to gate this entire thing for correctness in
930 // potentially potentially evaluated contexts.
934 E->getExprLoc(), E);
935 if (Temp.isInvalid())
936 return ExprError();
937 E = Temp.get();
938 }
939
940 // C++ [expr.call]p7, per CWG722:
941 // An argument that has (possibly cv-qualified) type std::nullptr_t is
942 // converted to void* ([conv.ptr]).
943 // (This does not apply to C23 nullptr)
945 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
946
947 return E;
948}
949
951 if (Ty->isIncompleteType()) {
952 // C++11 [expr.call]p7:
953 // After these conversions, if the argument does not have arithmetic,
954 // enumeration, pointer, pointer to member, or class type, the program
955 // is ill-formed.
956 //
957 // Since we've already performed null pointer conversion, array-to-pointer
958 // decay and function-to-pointer decay, the only such type in C++ is cv
959 // void. This also handles initializer lists as variadic arguments.
960 if (Ty->isVoidType())
961 return VAK_Invalid;
962
963 if (Ty->isObjCObjectType())
964 return VAK_Invalid;
965 return VAK_Valid;
966 }
967
969 return VAK_Invalid;
970
971 if (Context.getTargetInfo().getTriple().isWasm() &&
973 return VAK_Invalid;
974 }
975
976 if (Ty.isCXX98PODType(Context))
977 return VAK_Valid;
978
979 // C++11 [expr.call]p7:
980 // Passing a potentially-evaluated argument of class type (Clause 9)
981 // having a non-trivial copy constructor, a non-trivial move constructor,
982 // or a non-trivial destructor, with no corresponding parameter,
983 // is conditionally-supported with implementation-defined semantics.
986 if (!Record->hasNonTrivialCopyConstructor() &&
987 !Record->hasNonTrivialMoveConstructor() &&
988 !Record->hasNonTrivialDestructor())
989 return VAK_ValidInCXX11;
990
991 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
992 return VAK_Valid;
993
994 if (Ty->isObjCObjectType())
995 return VAK_Invalid;
996
998 return VAK_Valid;
999
1000 if (getLangOpts().MSVCCompat)
1001 return VAK_MSVCUndefined;
1002
1004 return VAK_Valid;
1005
1006 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
1007 // permitted to reject them. We should consider doing so.
1008 return VAK_Undefined;
1009}
1010
1012 // Don't allow one to pass an Objective-C interface to a vararg.
1013 const QualType &Ty = E->getType();
1014 VarArgKind VAK = isValidVarArgType(Ty);
1015
1016 // Complain about passing non-POD types through varargs.
1017 switch (VAK) {
1018 case VAK_ValidInCXX11:
1020 E->getBeginLoc(), nullptr,
1021 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1022 [[fallthrough]];
1023 case VAK_Valid:
1024 if (Ty->isRecordType()) {
1025 // This is unlikely to be what the user intended. If the class has a
1026 // 'c_str' member function, the user probably meant to call that.
1027 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1028 PDiag(diag::warn_pass_class_arg_to_vararg)
1029 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1030 }
1031 break;
1032
1033 case VAK_Undefined:
1034 case VAK_MSVCUndefined:
1035 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1036 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1037 << getLangOpts().CPlusPlus11 << Ty << CT);
1038 break;
1039
1040 case VAK_Invalid:
1042 Diag(E->getBeginLoc(),
1043 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1044 << Ty << CT;
1045 else if (Ty->isObjCObjectType())
1046 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1047 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1048 << Ty << CT);
1049 else
1050 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1051 << isa<InitListExpr>(E) << Ty << CT;
1052 break;
1053 }
1054}
1055
1057 FunctionDecl *FDecl) {
1058 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1059 // Strip the unbridged-cast placeholder expression off, if applicable.
1060 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1061 (CT == VariadicMethod ||
1062 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1064
1065 // Otherwise, do normal placeholder checking.
1066 } else {
1068 if (ExprRes.isInvalid())
1069 return ExprError();
1070 E = ExprRes.get();
1071 }
1072 }
1073
1075 if (ExprRes.isInvalid())
1076 return ExprError();
1077
1078 // Copy blocks to the heap.
1079 if (ExprRes.get()->getType()->isBlockPointerType())
1080 maybeExtendBlockObject(ExprRes);
1081
1082 E = ExprRes.get();
1083
1084 // Diagnostics regarding non-POD argument types are
1085 // emitted along with format string checking in Sema::CheckFunctionCall().
1087 // Turn this into a trap.
1088 CXXScopeSpec SS;
1089 SourceLocation TemplateKWLoc;
1090 UnqualifiedId Name;
1091 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1092 E->getBeginLoc());
1093 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1094 /*HasTrailingLParen=*/true,
1095 /*IsAddressOfOperand=*/false);
1096 if (TrapFn.isInvalid())
1097 return ExprError();
1098
1099 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1100 E->getEndLoc());
1101 if (Call.isInvalid())
1102 return ExprError();
1103
1104 ExprResult Comma =
1105 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1106 if (Comma.isInvalid())
1107 return ExprError();
1108 return Comma.get();
1109 }
1110
1111 if (!getLangOpts().CPlusPlus &&
1113 diag::err_call_incomplete_argument))
1114 return ExprError();
1115
1116 return E;
1117}
1118
1119/// Convert complex integers to complex floats and real integers to
1120/// real floats as required for complex arithmetic. Helper function of
1121/// UsualArithmeticConversions()
1122///
1123/// \return false if the integer expression is an integer type and is
1124/// successfully converted to the (complex) float type.
1126 ExprResult &ComplexExpr,
1127 QualType IntTy,
1128 QualType ComplexTy,
1129 bool SkipCast) {
1130 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1131 if (SkipCast) return false;
1132 if (IntTy->isIntegerType()) {
1133 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1134 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1135 } else {
1136 assert(IntTy->isComplexIntegerType());
1137 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1138 CK_IntegralComplexToFloatingComplex);
1139 }
1140 return false;
1141}
1142
1143// This handles complex/complex, complex/float, or float/complex.
1144// When both operands are complex, the shorter operand is converted to the
1145// type of the longer, and that is the type of the result. This corresponds
1146// to what is done when combining two real floating-point operands.
1147// The fun begins when size promotion occur across type domains.
1148// From H&S 6.3.4: When one operand is complex and the other is a real
1149// floating-point type, the less precise type is converted, within it's
1150// real or complex domain, to the precision of the other type. For example,
1151// when combining a "long double" with a "double _Complex", the
1152// "double _Complex" is promoted to "long double _Complex".
1154 QualType ShorterType,
1155 QualType LongerType,
1156 bool PromotePrecision) {
1157 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1159 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1160
1161 if (PromotePrecision) {
1162 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1163 Shorter =
1164 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1165 } else {
1166 if (LongerIsComplex)
1167 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1168 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1169 }
1170 }
1171 return Result;
1172}
1173
1174/// Handle arithmetic conversion with complex types. Helper function of
1175/// UsualArithmeticConversions()
1177 ExprResult &RHS, QualType LHSType,
1178 QualType RHSType, bool IsCompAssign) {
1179 // Handle (complex) integer types.
1180 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1181 /*SkipCast=*/false))
1182 return LHSType;
1183 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1184 /*SkipCast=*/IsCompAssign))
1185 return RHSType;
1186
1187 // Compute the rank of the two types, regardless of whether they are complex.
1188 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1189 if (Order < 0)
1190 // Promote the precision of the LHS if not an assignment.
1191 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1192 /*PromotePrecision=*/!IsCompAssign);
1193 // Promote the precision of the RHS unless it is already the same as the LHS.
1194 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1195 /*PromotePrecision=*/Order > 0);
1196}
1197
1198/// Handle arithmetic conversion from integer to float. Helper function
1199/// of UsualArithmeticConversions()
1201 ExprResult &IntExpr,
1202 QualType FloatTy, QualType IntTy,
1203 bool ConvertFloat, bool ConvertInt) {
1204 if (IntTy->isIntegerType()) {
1205 if (ConvertInt)
1206 // Convert intExpr to the lhs floating point type.
1207 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1208 CK_IntegralToFloating);
1209 return FloatTy;
1210 }
1211
1212 // Convert both sides to the appropriate complex float.
1213 assert(IntTy->isComplexIntegerType());
1214 QualType result = S.Context.getComplexType(FloatTy);
1215
1216 // _Complex int -> _Complex float
1217 if (ConvertInt)
1218 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1219 CK_IntegralComplexToFloatingComplex);
1220
1221 // float -> _Complex float
1222 if (ConvertFloat)
1223 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1224 CK_FloatingRealToComplex);
1225
1226 return result;
1227}
1228
1229/// Handle arithmethic conversion with floating point types. Helper
1230/// function of UsualArithmeticConversions()
1232 ExprResult &RHS, QualType LHSType,
1233 QualType RHSType, bool IsCompAssign) {
1234 bool LHSFloat = LHSType->isRealFloatingType();
1235 bool RHSFloat = RHSType->isRealFloatingType();
1236
1237 // N1169 4.1.4: If one of the operands has a floating type and the other
1238 // operand has a fixed-point type, the fixed-point operand
1239 // is converted to the floating type [...]
1240 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1241 if (LHSFloat)
1242 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1243 else if (!IsCompAssign)
1244 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1245 return LHSFloat ? LHSType : RHSType;
1246 }
1247
1248 // If we have two real floating types, convert the smaller operand
1249 // to the bigger result.
1250 if (LHSFloat && RHSFloat) {
1251 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1252 if (order > 0) {
1253 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1254 return LHSType;
1255 }
1256
1257 assert(order < 0 && "illegal float comparison");
1258 if (!IsCompAssign)
1259 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1260 return RHSType;
1261 }
1262
1263 if (LHSFloat) {
1264 // Half FP has to be promoted to float unless it is natively supported
1265 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1266 LHSType = S.Context.FloatTy;
1267
1268 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1269 /*ConvertFloat=*/!IsCompAssign,
1270 /*ConvertInt=*/ true);
1271 }
1272 assert(RHSFloat);
1273 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1274 /*ConvertFloat=*/ true,
1275 /*ConvertInt=*/!IsCompAssign);
1276}
1277
1278/// Diagnose attempts to convert between __float128, __ibm128 and
1279/// long double if there is no support for such conversion.
1280/// Helper function of UsualArithmeticConversions().
1281static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1282 QualType RHSType) {
1283 // No issue if either is not a floating point type.
1284 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1285 return false;
1286
1287 // No issue if both have the same 128-bit float semantics.
1288 auto *LHSComplex = LHSType->getAs<ComplexType>();
1289 auto *RHSComplex = RHSType->getAs<ComplexType>();
1290
1291 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1292 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1293
1294 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1295 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1296
1297 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1298 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1299 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1300 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1301 return false;
1302
1303 return true;
1304}
1305
1306typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1307
1308namespace {
1309/// These helper callbacks are placed in an anonymous namespace to
1310/// permit their use as function template parameters.
1311ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1312 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1313}
1314
1315ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1316 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1317 CK_IntegralComplexCast);
1318}
1319}
1320
1321/// Handle integer arithmetic conversions. Helper function of
1322/// UsualArithmeticConversions()
1323template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1325 ExprResult &RHS, QualType LHSType,
1326 QualType RHSType, bool IsCompAssign) {
1327 // The rules for this case are in C99 6.3.1.8
1328 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1329 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1330 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1331 if (LHSSigned == RHSSigned) {
1332 // Same signedness; use the higher-ranked type
1333 if (order >= 0) {
1334 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1335 return LHSType;
1336 } else if (!IsCompAssign)
1337 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1338 return RHSType;
1339 } else if (order != (LHSSigned ? 1 : -1)) {
1340 // The unsigned type has greater than or equal rank to the
1341 // signed type, so use the unsigned type
1342 if (RHSSigned) {
1343 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1344 return LHSType;
1345 } else if (!IsCompAssign)
1346 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1347 return RHSType;
1348 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1349 // The two types are different widths; if we are here, that
1350 // means the signed type is larger than the unsigned type, so
1351 // use the signed type.
1352 if (LHSSigned) {
1353 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1354 return LHSType;
1355 } else if (!IsCompAssign)
1356 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1357 return RHSType;
1358 } else {
1359 // The signed type is higher-ranked than the unsigned type,
1360 // but isn't actually any bigger (like unsigned int and long
1361 // on most 32-bit systems). Use the unsigned type corresponding
1362 // to the signed type.
1363 QualType result =
1364 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1365 RHS = (*doRHSCast)(S, RHS.get(), result);
1366 if (!IsCompAssign)
1367 LHS = (*doLHSCast)(S, LHS.get(), result);
1368 return result;
1369 }
1370}
1371
1372/// Handle conversions with GCC complex int extension. Helper function
1373/// of UsualArithmeticConversions()
1375 ExprResult &RHS, QualType LHSType,
1376 QualType RHSType,
1377 bool IsCompAssign) {
1378 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1379 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1380
1381 if (LHSComplexInt && RHSComplexInt) {
1382 QualType LHSEltType = LHSComplexInt->getElementType();
1383 QualType RHSEltType = RHSComplexInt->getElementType();
1384 QualType ScalarType =
1385 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1386 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1387
1388 return S.Context.getComplexType(ScalarType);
1389 }
1390
1391 if (LHSComplexInt) {
1392 QualType LHSEltType = LHSComplexInt->getElementType();
1393 QualType ScalarType =
1394 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1395 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1397 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1398 CK_IntegralRealToComplex);
1399
1400 return ComplexType;
1401 }
1402
1403 assert(RHSComplexInt);
1404
1405 QualType RHSEltType = RHSComplexInt->getElementType();
1406 QualType ScalarType =
1407 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1408 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1410
1411 if (!IsCompAssign)
1412 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1413 CK_IntegralRealToComplex);
1414 return ComplexType;
1415}
1416
1417/// Return the rank of a given fixed point or integer type. The value itself
1418/// doesn't matter, but the values must be increasing with proper increasing
1419/// rank as described in N1169 4.1.1.
1420static unsigned GetFixedPointRank(QualType Ty) {
1421 const auto *BTy = Ty->getAs<BuiltinType>();
1422 assert(BTy && "Expected a builtin type.");
1423
1424 switch (BTy->getKind()) {
1425 case BuiltinType::ShortFract:
1426 case BuiltinType::UShortFract:
1427 case BuiltinType::SatShortFract:
1428 case BuiltinType::SatUShortFract:
1429 return 1;
1430 case BuiltinType::Fract:
1431 case BuiltinType::UFract:
1432 case BuiltinType::SatFract:
1433 case BuiltinType::SatUFract:
1434 return 2;
1435 case BuiltinType::LongFract:
1436 case BuiltinType::ULongFract:
1437 case BuiltinType::SatLongFract:
1438 case BuiltinType::SatULongFract:
1439 return 3;
1440 case BuiltinType::ShortAccum:
1441 case BuiltinType::UShortAccum:
1442 case BuiltinType::SatShortAccum:
1443 case BuiltinType::SatUShortAccum:
1444 return 4;
1445 case BuiltinType::Accum:
1446 case BuiltinType::UAccum:
1447 case BuiltinType::SatAccum:
1448 case BuiltinType::SatUAccum:
1449 return 5;
1450 case BuiltinType::LongAccum:
1451 case BuiltinType::ULongAccum:
1452 case BuiltinType::SatLongAccum:
1453 case BuiltinType::SatULongAccum:
1454 return 6;
1455 default:
1456 if (BTy->isInteger())
1457 return 0;
1458 llvm_unreachable("Unexpected fixed point or integer type");
1459 }
1460}
1461
1462/// handleFixedPointConversion - Fixed point operations between fixed
1463/// point types and integers or other fixed point types do not fall under
1464/// usual arithmetic conversion since these conversions could result in loss
1465/// of precsision (N1169 4.1.4). These operations should be calculated with
1466/// the full precision of their result type (N1169 4.1.6.2.1).
1468 QualType RHSTy) {
1469 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1470 "Expected at least one of the operands to be a fixed point type");
1471 assert((LHSTy->isFixedPointOrIntegerType() ||
1472 RHSTy->isFixedPointOrIntegerType()) &&
1473 "Special fixed point arithmetic operation conversions are only "
1474 "applied to ints or other fixed point types");
1475
1476 // If one operand has signed fixed-point type and the other operand has
1477 // unsigned fixed-point type, then the unsigned fixed-point operand is
1478 // converted to its corresponding signed fixed-point type and the resulting
1479 // type is the type of the converted operand.
1480 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1482 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1484
1485 // The result type is the type with the highest rank, whereby a fixed-point
1486 // conversion rank is always greater than an integer conversion rank; if the
1487 // type of either of the operands is a saturating fixedpoint type, the result
1488 // type shall be the saturating fixed-point type corresponding to the type
1489 // with the highest rank; the resulting value is converted (taking into
1490 // account rounding and overflow) to the precision of the resulting type.
1491 // Same ranks between signed and unsigned types are resolved earlier, so both
1492 // types are either signed or both unsigned at this point.
1493 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1494 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1495
1496 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1497
1499 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1500
1501 return ResultTy;
1502}
1503
1504/// Check that the usual arithmetic conversions can be performed on this pair of
1505/// expressions that might be of enumeration type.
1508 Sema::ArithConvKind ACK) {
1509 // C++2a [expr.arith.conv]p1:
1510 // If one operand is of enumeration type and the other operand is of a
1511 // different enumeration type or a floating-point type, this behavior is
1512 // deprecated ([depr.arith.conv.enum]).
1513 //
1514 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1515 // Eventually we will presumably reject these cases (in C++23 onwards?).
1517 R = RHS->getEnumCoercedType(Context);
1518 bool LEnum = L->isUnscopedEnumerationType(),
1519 REnum = R->isUnscopedEnumerationType();
1520 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1521 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1522 (REnum && L->isFloatingType())) {
1523 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::err_arith_conv_enum_float_cxx26
1525 ? diag::warn_arith_conv_enum_float_cxx20
1526 : diag::warn_arith_conv_enum_float)
1527 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1528 << L << R;
1529 } else if (!IsCompAssign && LEnum && REnum &&
1531 unsigned DiagID;
1532 // In C++ 26, usual arithmetic conversions between 2 different enum types
1533 // are ill-formed.
1534 if (getLangOpts().CPlusPlus26)
1535 DiagID = diag::err_conv_mixed_enum_types_cxx26;
1536 else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1537 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1538 // If either enumeration type is unnamed, it's less likely that the
1539 // user cares about this, but this situation is still deprecated in
1540 // C++2a. Use a different warning group.
1541 DiagID = getLangOpts().CPlusPlus20
1542 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1543 : diag::warn_arith_conv_mixed_anon_enum_types;
1544 } else if (ACK == Sema::ACK_Conditional) {
1545 // Conditional expressions are separated out because they have
1546 // historically had a different warning flag.
1547 DiagID = getLangOpts().CPlusPlus20
1548 ? diag::warn_conditional_mixed_enum_types_cxx20
1549 : diag::warn_conditional_mixed_enum_types;
1550 } else if (ACK == Sema::ACK_Comparison) {
1551 // Comparison expressions are separated out because they have
1552 // historically had a different warning flag.
1553 DiagID = getLangOpts().CPlusPlus20
1554 ? diag::warn_comparison_mixed_enum_types_cxx20
1555 : diag::warn_comparison_mixed_enum_types;
1556 } else {
1557 DiagID = getLangOpts().CPlusPlus20
1558 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1559 : diag::warn_arith_conv_mixed_enum_types;
1560 }
1561 Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1562 << (int)ACK << L << R;
1563 }
1564}
1565
1566/// UsualArithmeticConversions - Performs various conversions that are common to
1567/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1568/// routine returns the first non-arithmetic type found. The client is
1569/// responsible for emitting appropriate error diagnostics.
1572 ArithConvKind ACK) {
1573 checkEnumArithmeticConversions(LHS.get(), RHS.get(), Loc, ACK);
1574
1575 if (ACK != ACK_CompAssign) {
1576 LHS = UsualUnaryConversions(LHS.get());
1577 if (LHS.isInvalid())
1578 return QualType();
1579 }
1580
1581 RHS = UsualUnaryConversions(RHS.get());
1582 if (RHS.isInvalid())
1583 return QualType();
1584
1585 // For conversion purposes, we ignore any qualifiers.
1586 // For example, "const float" and "float" are equivalent.
1587 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1588 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1589
1590 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1591 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1592 LHSType = AtomicLHS->getValueType();
1593
1594 // If both types are identical, no conversion is needed.
1595 if (Context.hasSameType(LHSType, RHSType))
1596 return Context.getCommonSugaredType(LHSType, RHSType);
1597
1598 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1599 // The caller can deal with this (e.g. pointer + int).
1600 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1601 return QualType();
1602
1603 // Apply unary and bitfield promotions to the LHS's type.
1604 QualType LHSUnpromotedType = LHSType;
1605 if (Context.isPromotableIntegerType(LHSType))
1606 LHSType = Context.getPromotedIntegerType(LHSType);
1607 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1608 if (!LHSBitfieldPromoteTy.isNull())
1609 LHSType = LHSBitfieldPromoteTy;
1610 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1611 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1612
1613 // If both types are identical, no conversion is needed.
1614 if (Context.hasSameType(LHSType, RHSType))
1615 return Context.getCommonSugaredType(LHSType, RHSType);
1616
1617 // At this point, we have two different arithmetic types.
1618
1619 // Diagnose attempts to convert between __ibm128, __float128 and long double
1620 // where such conversions currently can't be handled.
1621 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1622 return QualType();
1623
1624 // Handle complex types first (C99 6.3.1.8p1).
1625 if (LHSType->isComplexType() || RHSType->isComplexType())
1626 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1627 ACK == ACK_CompAssign);
1628
1629 // Now handle "real" floating types (i.e. float, double, long double).
1630 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1631 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1632 ACK == ACK_CompAssign);
1633
1634 // Handle GCC complex int extension.
1635 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1636 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1637 ACK == ACK_CompAssign);
1638
1639 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1640 return handleFixedPointConversion(*this, LHSType, RHSType);
1641
1642 // Finally, we have two differing integer types.
1643 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1644 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1645}
1646
1647//===----------------------------------------------------------------------===//
1648// Semantic Analysis for various Expression Types
1649//===----------------------------------------------------------------------===//
1650
1651
1653 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1654 bool PredicateIsExpr, void *ControllingExprOrType,
1655 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1656 unsigned NumAssocs = ArgTypes.size();
1657 assert(NumAssocs == ArgExprs.size());
1658
1659 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1660 for (unsigned i = 0; i < NumAssocs; ++i) {
1661 if (ArgTypes[i])
1662 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1663 else
1664 Types[i] = nullptr;
1665 }
1666
1667 // If we have a controlling type, we need to convert it from a parsed type
1668 // into a semantic type and then pass that along.
1669 if (!PredicateIsExpr) {
1670 TypeSourceInfo *ControllingType;
1671 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1672 &ControllingType);
1673 assert(ControllingType && "couldn't get the type out of the parser");
1674 ControllingExprOrType = ControllingType;
1675 }
1676
1678 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1679 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1680 delete [] Types;
1681 return ER;
1682}
1683
1685 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1686 bool PredicateIsExpr, void *ControllingExprOrType,
1688 unsigned NumAssocs = Types.size();
1689 assert(NumAssocs == Exprs.size());
1690 assert(ControllingExprOrType &&
1691 "Must have either a controlling expression or a controlling type");
1692
1693 Expr *ControllingExpr = nullptr;
1694 TypeSourceInfo *ControllingType = nullptr;
1695 if (PredicateIsExpr) {
1696 // Decay and strip qualifiers for the controlling expression type, and
1697 // handle placeholder type replacement. See committee discussion from WG14
1698 // DR423.
1702 reinterpret_cast<Expr *>(ControllingExprOrType));
1703 if (R.isInvalid())
1704 return ExprError();
1705 ControllingExpr = R.get();
1706 } else {
1707 // The extension form uses the type directly rather than converting it.
1708 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1709 if (!ControllingType)
1710 return ExprError();
1711 }
1712
1713 bool TypeErrorFound = false,
1714 IsResultDependent = ControllingExpr
1715 ? ControllingExpr->isTypeDependent()
1716 : ControllingType->getType()->isDependentType(),
1717 ContainsUnexpandedParameterPack =
1718 ControllingExpr
1719 ? ControllingExpr->containsUnexpandedParameterPack()
1720 : ControllingType->getType()->containsUnexpandedParameterPack();
1721
1722 // The controlling expression is an unevaluated operand, so side effects are
1723 // likely unintended.
1724 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1725 ControllingExpr->HasSideEffects(Context, false))
1726 Diag(ControllingExpr->getExprLoc(),
1727 diag::warn_side_effects_unevaluated_context);
1728
1729 for (unsigned i = 0; i < NumAssocs; ++i) {
1730 if (Exprs[i]->containsUnexpandedParameterPack())
1731 ContainsUnexpandedParameterPack = true;
1732
1733 if (Types[i]) {
1734 if (Types[i]->getType()->containsUnexpandedParameterPack())
1735 ContainsUnexpandedParameterPack = true;
1736
1737 if (Types[i]->getType()->isDependentType()) {
1738 IsResultDependent = true;
1739 } else {
1740 // We relax the restriction on use of incomplete types and non-object
1741 // types with the type-based extension of _Generic. Allowing incomplete
1742 // objects means those can be used as "tags" for a type-safe way to map
1743 // to a value. Similarly, matching on function types rather than
1744 // function pointer types can be useful. However, the restriction on VM
1745 // types makes sense to retain as there are open questions about how
1746 // the selection can be made at compile time.
1747 //
1748 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1749 // complete object type other than a variably modified type."
1750 unsigned D = 0;
1751 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1752 D = diag::err_assoc_type_incomplete;
1753 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1754 D = diag::err_assoc_type_nonobject;
1755 else if (Types[i]->getType()->isVariablyModifiedType())
1756 D = diag::err_assoc_type_variably_modified;
1757 else if (ControllingExpr) {
1758 // Because the controlling expression undergoes lvalue conversion,
1759 // array conversion, and function conversion, an association which is
1760 // of array type, function type, or is qualified can never be
1761 // reached. We will warn about this so users are less surprised by
1762 // the unreachable association. However, we don't have to handle
1763 // function types; that's not an object type, so it's handled above.
1764 //
1765 // The logic is somewhat different for C++ because C++ has different
1766 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1767 // If T is a non-class type, the type of the prvalue is the cv-
1768 // unqualified version of T. Otherwise, the type of the prvalue is T.
1769 // The result of these rules is that all qualified types in an
1770 // association in C are unreachable, and in C++, only qualified non-
1771 // class types are unreachable.
1772 //
1773 // NB: this does not apply when the first operand is a type rather
1774 // than an expression, because the type form does not undergo
1775 // conversion.
1776 unsigned Reason = 0;
1777 QualType QT = Types[i]->getType();
1778 if (QT->isArrayType())
1779 Reason = 1;
1780 else if (QT.hasQualifiers() &&
1781 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1782 Reason = 2;
1783
1784 if (Reason)
1785 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1786 diag::warn_unreachable_association)
1787 << QT << (Reason - 1);
1788 }
1789
1790 if (D != 0) {
1791 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1792 << Types[i]->getTypeLoc().getSourceRange()
1793 << Types[i]->getType();
1794 TypeErrorFound = true;
1795 }
1796
1797 // C11 6.5.1.1p2 "No two generic associations in the same generic
1798 // selection shall specify compatible types."
1799 for (unsigned j = i+1; j < NumAssocs; ++j)
1800 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1801 Context.typesAreCompatible(Types[i]->getType(),
1802 Types[j]->getType())) {
1803 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1804 diag::err_assoc_compatible_types)
1805 << Types[j]->getTypeLoc().getSourceRange()
1806 << Types[j]->getType()
1807 << Types[i]->getType();
1808 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1809 diag::note_compat_assoc)
1810 << Types[i]->getTypeLoc().getSourceRange()
1811 << Types[i]->getType();
1812 TypeErrorFound = true;
1813 }
1814 }
1815 }
1816 }
1817 if (TypeErrorFound)
1818 return ExprError();
1819
1820 // If we determined that the generic selection is result-dependent, don't
1821 // try to compute the result expression.
1822 if (IsResultDependent) {
1823 if (ControllingExpr)
1824 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1825 Types, Exprs, DefaultLoc, RParenLoc,
1826 ContainsUnexpandedParameterPack);
1827 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1828 Exprs, DefaultLoc, RParenLoc,
1829 ContainsUnexpandedParameterPack);
1830 }
1831
1832 SmallVector<unsigned, 1> CompatIndices;
1833 unsigned DefaultIndex = -1U;
1834 // Look at the canonical type of the controlling expression in case it was a
1835 // deduced type like __auto_type. However, when issuing diagnostics, use the
1836 // type the user wrote in source rather than the canonical one.
1837 for (unsigned i = 0; i < NumAssocs; ++i) {
1838 if (!Types[i])
1839 DefaultIndex = i;
1840 else if (ControllingExpr &&
1842 ControllingExpr->getType().getCanonicalType(),
1843 Types[i]->getType()))
1844 CompatIndices.push_back(i);
1845 else if (ControllingType &&
1847 ControllingType->getType().getCanonicalType(),
1848 Types[i]->getType()))
1849 CompatIndices.push_back(i);
1850 }
1851
1852 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1853 TypeSourceInfo *ControllingType) {
1854 // We strip parens here because the controlling expression is typically
1855 // parenthesized in macro definitions.
1856 if (ControllingExpr)
1857 ControllingExpr = ControllingExpr->IgnoreParens();
1858
1859 SourceRange SR = ControllingExpr
1860 ? ControllingExpr->getSourceRange()
1861 : ControllingType->getTypeLoc().getSourceRange();
1862 QualType QT = ControllingExpr ? ControllingExpr->getType()
1863 : ControllingType->getType();
1864
1865 return std::make_pair(SR, QT);
1866 };
1867
1868 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1869 // type compatible with at most one of the types named in its generic
1870 // association list."
1871 if (CompatIndices.size() > 1) {
1872 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1873 SourceRange SR = P.first;
1874 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1875 << SR << P.second << (unsigned)CompatIndices.size();
1876 for (unsigned I : CompatIndices) {
1877 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1878 diag::note_compat_assoc)
1879 << Types[I]->getTypeLoc().getSourceRange()
1880 << Types[I]->getType();
1881 }
1882 return ExprError();
1883 }
1884
1885 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1886 // its controlling expression shall have type compatible with exactly one of
1887 // the types named in its generic association list."
1888 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1889 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1890 SourceRange SR = P.first;
1891 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1892 return ExprError();
1893 }
1894
1895 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1896 // type name that is compatible with the type of the controlling expression,
1897 // then the result expression of the generic selection is the expression
1898 // in that generic association. Otherwise, the result expression of the
1899 // generic selection is the expression in the default generic association."
1900 unsigned ResultIndex =
1901 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1902
1903 if (ControllingExpr) {
1905 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1906 ContainsUnexpandedParameterPack, ResultIndex);
1907 }
1909 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1910 ContainsUnexpandedParameterPack, ResultIndex);
1911}
1912
1914 switch (Kind) {
1915 default:
1916 llvm_unreachable("unexpected TokenKind");
1917 case tok::kw___func__:
1918 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
1919 case tok::kw___FUNCTION__:
1921 case tok::kw___FUNCDNAME__:
1922 return PredefinedIdentKind::FuncDName; // [MS]
1923 case tok::kw___FUNCSIG__:
1924 return PredefinedIdentKind::FuncSig; // [MS]
1925 case tok::kw_L__FUNCTION__:
1926 return PredefinedIdentKind::LFunction; // [MS]
1927 case tok::kw_L__FUNCSIG__:
1928 return PredefinedIdentKind::LFuncSig; // [MS]
1929 case tok::kw___PRETTY_FUNCTION__:
1931 }
1932}
1933
1934/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1935/// to determine the value of a PredefinedExpr. This can be either a
1936/// block, lambda, captured statement, function, otherwise a nullptr.
1938 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))
1939 DC = DC->getParent();
1940 return cast_or_null<Decl>(DC);
1941}
1942
1943/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1944/// location of the token and the offset of the ud-suffix within it.
1946 unsigned Offset) {
1947 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1948 S.getLangOpts());
1949}
1950
1951/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1952/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1954 IdentifierInfo *UDSuffix,
1955 SourceLocation UDSuffixLoc,
1956 ArrayRef<Expr*> Args,
1957 SourceLocation LitEndLoc) {
1958 assert(Args.size() <= 2 && "too many arguments for literal operator");
1959
1960 QualType ArgTy[2];
1961 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1962 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1963 if (ArgTy[ArgIdx]->isArrayType())
1964 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1965 }
1966
1967 DeclarationName OpName =
1969 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1970 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1971
1972 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1973 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1974 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1975 /*AllowStringTemplatePack*/ false,
1976 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1977 return ExprError();
1978
1979 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1980}
1981
1983 // StringToks needs backing storage as it doesn't hold array elements itself
1984 std::vector<Token> ExpandedToks;
1985 if (getLangOpts().MicrosoftExt)
1986 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
1987
1988 StringLiteralParser Literal(StringToks, PP,
1990 if (Literal.hadError)
1991 return ExprError();
1992
1993 SmallVector<SourceLocation, 4> StringTokLocs;
1994 for (const Token &Tok : StringToks)
1995 StringTokLocs.push_back(Tok.getLocation());
1996
1998 Context, Literal.GetString(), StringLiteralKind::Unevaluated, false, {},
1999 &StringTokLocs[0], StringTokLocs.size());
2000
2001 if (!Literal.getUDSuffix().empty()) {
2002 SourceLocation UDSuffixLoc =
2003 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2004 Literal.getUDSuffixOffset());
2005 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2006 }
2007
2008 return Lit;
2009}
2010
2011std::vector<Token>
2013 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2014 // local macros that expand to string literals that may be concatenated.
2015 // These macros are expanded here (in Sema), because StringLiteralParser
2016 // (in Lex) doesn't know the enclosing function (because it hasn't been
2017 // parsed yet).
2018 assert(getLangOpts().MicrosoftExt);
2019
2020 // Note: Although function local macros are defined only inside functions,
2021 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2022 // expansion of macros into empty string literals without additional checks.
2023 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2024 if (!CurrentDecl)
2025 CurrentDecl = Context.getTranslationUnitDecl();
2026
2027 std::vector<Token> ExpandedToks;
2028 ExpandedToks.reserve(Toks.size());
2029 for (const Token &Tok : Toks) {
2030 if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
2031 assert(tok::isStringLiteral(Tok.getKind()));
2032 ExpandedToks.emplace_back(Tok);
2033 continue;
2034 }
2035 if (isa<TranslationUnitDecl>(CurrentDecl))
2036 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2037 // Stringify predefined expression
2038 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2039 << Tok.getKind();
2040 SmallString<64> Str;
2041 llvm::raw_svector_ostream OS(Str);
2042 Token &Exp = ExpandedToks.emplace_back();
2043 Exp.startToken();
2044 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2045 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2046 OS << 'L';
2047 Exp.setKind(tok::wide_string_literal);
2048 } else {
2049 Exp.setKind(tok::string_literal);
2050 }
2051 OS << '"'
2053 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2054 << '"';
2055 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2056 }
2057 return ExpandedToks;
2058}
2059
2062 assert(!StringToks.empty() && "Must have at least one string!");
2063
2064 // StringToks needs backing storage as it doesn't hold array elements itself
2065 std::vector<Token> ExpandedToks;
2066 if (getLangOpts().MicrosoftExt)
2067 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2068
2069 StringLiteralParser Literal(StringToks, PP);
2070 if (Literal.hadError)
2071 return ExprError();
2072
2073 SmallVector<SourceLocation, 4> StringTokLocs;
2074 for (const Token &Tok : StringToks)
2075 StringTokLocs.push_back(Tok.getLocation());
2076
2077 QualType CharTy = Context.CharTy;
2079 if (Literal.isWide()) {
2080 CharTy = Context.getWideCharType();
2082 } else if (Literal.isUTF8()) {
2083 if (getLangOpts().Char8)
2084 CharTy = Context.Char8Ty;
2085 else if (getLangOpts().C23)
2086 CharTy = Context.UnsignedCharTy;
2088 } else if (Literal.isUTF16()) {
2089 CharTy = Context.Char16Ty;
2091 } else if (Literal.isUTF32()) {
2092 CharTy = Context.Char32Ty;
2094 } else if (Literal.isPascal()) {
2095 CharTy = Context.UnsignedCharTy;
2096 }
2097
2098 // Warn on u8 string literals before C++20 and C23, whose type
2099 // was an array of char before but becomes an array of char8_t.
2100 // In C++20, it cannot be used where a pointer to char is expected.
2101 // In C23, it might have an unexpected value if char was signed.
2102 if (Kind == StringLiteralKind::UTF8 &&
2104 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2105 : !getLangOpts().C23)) {
2106 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2107 ? diag::warn_cxx20_compat_utf8_string
2108 : diag::warn_c23_compat_utf8_string);
2109
2110 // Create removals for all 'u8' prefixes in the string literal(s). This
2111 // ensures C++20/C23 compatibility (but may change the program behavior when
2112 // built by non-Clang compilers for which the execution character set is
2113 // not always UTF-8).
2114 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2115 SourceLocation RemovalDiagLoc;
2116 for (const Token &Tok : StringToks) {
2117 if (Tok.getKind() == tok::utf8_string_literal) {
2118 if (RemovalDiagLoc.isInvalid())
2119 RemovalDiagLoc = Tok.getLocation();
2121 Tok.getLocation(),
2122 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2124 }
2125 }
2126 Diag(RemovalDiagLoc, RemovalDiag);
2127 }
2128
2129 QualType StrTy =
2130 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2131
2132 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2133 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2134 Kind, Literal.Pascal, StrTy,
2135 &StringTokLocs[0],
2136 StringTokLocs.size());
2137 if (Literal.getUDSuffix().empty())
2138 return Lit;
2139
2140 // We're building a user-defined literal.
2141 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2142 SourceLocation UDSuffixLoc =
2143 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2144 Literal.getUDSuffixOffset());
2145
2146 // Make sure we're allowed user-defined literals here.
2147 if (!UDLScope)
2148 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2149
2150 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2151 // operator "" X (str, len)
2152 QualType SizeType = Context.getSizeType();
2153
2154 DeclarationName OpName =
2156 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2157 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2158
2159 QualType ArgTy[] = {
2160 Context.getArrayDecayedType(StrTy), SizeType
2161 };
2162
2163 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2164 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2165 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2166 /*AllowStringTemplatePack*/ true,
2167 /*DiagnoseMissing*/ true, Lit)) {
2168
2169 case LOLR_Cooked: {
2170 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2171 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2172 StringTokLocs[0]);
2173 Expr *Args[] = { Lit, LenArg };
2174
2175 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2176 }
2177
2178 case LOLR_Template: {
2179 TemplateArgumentListInfo ExplicitArgs;
2180 TemplateArgument Arg(Lit);
2181 TemplateArgumentLocInfo ArgInfo(Lit);
2182 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2183 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2184 &ExplicitArgs);
2185 }
2186
2188 TemplateArgumentListInfo ExplicitArgs;
2189
2190 unsigned CharBits = Context.getIntWidth(CharTy);
2191 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2192 llvm::APSInt Value(CharBits, CharIsUnsigned);
2193
2194 TemplateArgument TypeArg(CharTy);
2196 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2197
2198 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2199 Value = Lit->getCodeUnit(I);
2200 TemplateArgument Arg(Context, Value, CharTy);
2202 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2203 }
2204 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2205 &ExplicitArgs);
2206 }
2207 case LOLR_Raw:
2209 llvm_unreachable("unexpected literal operator lookup result");
2210 case LOLR_Error:
2211 return ExprError();
2212 }
2213 llvm_unreachable("unexpected literal operator lookup result");
2214}
2215
2219 const CXXScopeSpec *SS) {
2220 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2221 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2222}
2223
2226 const DeclarationNameInfo &NameInfo,
2227 const CXXScopeSpec *SS, NamedDecl *FoundD,
2228 SourceLocation TemplateKWLoc,
2229 const TemplateArgumentListInfo *TemplateArgs) {
2232 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2233 TemplateArgs);
2234}
2235
2236// CUDA/HIP: Check whether a captured reference variable is referencing a
2237// host variable in a device or host device lambda.
2239 VarDecl *VD) {
2240 if (!S.getLangOpts().CUDA || !VD->hasInit())
2241 return false;
2242 assert(VD->getType()->isReferenceType());
2243
2244 // Check whether the reference variable is referencing a host variable.
2245 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2246 if (!DRE)
2247 return false;
2248 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2249 if (!Referee || !Referee->hasGlobalStorage() ||
2250 Referee->hasAttr<CUDADeviceAttr>())
2251 return false;
2252
2253 // Check whether the current function is a device or host device lambda.
2254 // Check whether the reference variable is a capture by getDeclContext()
2255 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2256 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2257 if (MD && MD->getParent()->isLambda() &&
2258 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2259 VD->getDeclContext() != MD)
2260 return true;
2261
2262 return false;
2263}
2264
2266 // A declaration named in an unevaluated operand never constitutes an odr-use.
2268 return NOUR_Unevaluated;
2269
2270 // C++2a [basic.def.odr]p4:
2271 // A variable x whose name appears as a potentially-evaluated expression e
2272 // is odr-used by e unless [...] x is a reference that is usable in
2273 // constant expressions.
2274 // CUDA/HIP:
2275 // If a reference variable referencing a host variable is captured in a
2276 // device or host device lambda, the value of the referee must be copied
2277 // to the capture and the reference variable must be treated as odr-use
2278 // since the value of the referee is not known at compile time and must
2279 // be loaded from the captured.
2280 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2281 if (VD->getType()->isReferenceType() &&
2282 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2284 VD->isUsableInConstantExpressions(Context))
2285 return NOUR_Constant;
2286 }
2287
2288 // All remaining non-variable cases constitute an odr-use. For variables, we
2289 // need to wait and see how the expression is used.
2290 return NOUR_None;
2291}
2292
2295 const DeclarationNameInfo &NameInfo,
2296 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2297 SourceLocation TemplateKWLoc,
2298 const TemplateArgumentListInfo *TemplateArgs) {
2299 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2300 NeedToCaptureVariable(D, NameInfo.getLoc());
2301
2303 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2304 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2306
2307 // C++ [except.spec]p17:
2308 // An exception-specification is considered to be needed when:
2309 // - in an expression, the function is the unique lookup result or
2310 // the selected member of a set of overloaded functions.
2311 //
2312 // We delay doing this until after we've built the function reference and
2313 // marked it as used so that:
2314 // a) if the function is defaulted, we get errors from defining it before /
2315 // instead of errors from computing its exception specification, and
2316 // b) if the function is a defaulted comparison, we can use the body we
2317 // build when defining it as input to the exception specification
2318 // computation rather than computing a new body.
2319 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2320 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2321 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2323 }
2324 }
2325
2326 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2328 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2330
2331 const auto *FD = dyn_cast<FieldDecl>(D);
2332 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2333 FD = IFD->getAnonField();
2334 if (FD) {
2335 UnusedPrivateFields.remove(FD);
2336 // Just in case we're building an illegal pointer-to-member.
2337 if (FD->isBitField())
2339 }
2340
2341 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2342 // designates a bit-field.
2343 if (const auto *BD = dyn_cast<BindingDecl>(D))
2344 if (const auto *BE = BD->getBinding())
2345 E->setObjectKind(BE->getObjectKind());
2346
2347 return E;
2348}
2349
2350void
2353 DeclarationNameInfo &NameInfo,
2354 const TemplateArgumentListInfo *&TemplateArgs) {
2355 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2356 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2357 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2358
2359 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2360 Id.TemplateId->NumArgs);
2361 translateTemplateArguments(TemplateArgsPtr, Buffer);
2362
2363 TemplateName TName = Id.TemplateId->Template.get();
2364 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2365 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2366 TemplateArgs = &Buffer;
2367 } else {
2368 NameInfo = GetNameFromUnqualifiedId(Id);
2369 TemplateArgs = nullptr;
2370 }
2371}
2372
2374 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2376 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2377 DeclContext *Ctx =
2378 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2379 if (!TC) {
2380 // Emit a special diagnostic for failed member lookups.
2381 // FIXME: computing the declaration context might fail here (?)
2382 if (Ctx)
2383 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2384 << SS.getRange();
2385 else
2386 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2387 return;
2388 }
2389
2390 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2391 bool DroppedSpecifier =
2392 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2393 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2394 ? diag::note_implicit_param_decl
2395 : diag::note_previous_decl;
2396 if (!Ctx)
2397 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2398 SemaRef.PDiag(NoteID));
2399 else
2400 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2401 << Typo << Ctx << DroppedSpecifier
2402 << SS.getRange(),
2403 SemaRef.PDiag(NoteID));
2404}
2405
2407 // During a default argument instantiation the CurContext points
2408 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2409 // function parameter list, hence add an explicit check.
2410 bool isDefaultArgument =
2411 !CodeSynthesisContexts.empty() &&
2412 CodeSynthesisContexts.back().Kind ==
2414 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2415 bool isInstance = CurMethod && CurMethod->isInstance() &&
2416 R.getNamingClass() == CurMethod->getParent() &&
2417 !isDefaultArgument;
2418
2419 // There are two ways we can find a class-scope declaration during template
2420 // instantiation that we did not find in the template definition: if it is a
2421 // member of a dependent base class, or if it is declared after the point of
2422 // use in the same class. Distinguish these by comparing the class in which
2423 // the member was found to the naming class of the lookup.
2424 unsigned DiagID = diag::err_found_in_dependent_base;
2425 unsigned NoteID = diag::note_member_declared_at;
2427 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2428 : diag::err_found_later_in_class;
2429 } else if (getLangOpts().MSVCCompat) {
2430 DiagID = diag::ext_found_in_dependent_base;
2431 NoteID = diag::note_dependent_member_use;
2432 }
2433
2434 if (isInstance) {
2435 // Give a code modification hint to insert 'this->'.
2436 Diag(R.getNameLoc(), DiagID)
2437 << R.getLookupName()
2438 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2440 } else {
2441 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2442 // they're not shadowed).
2443 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2444 }
2445
2446 for (const NamedDecl *D : R)
2447 Diag(D->getLocation(), NoteID);
2448
2449 // Return true if we are inside a default argument instantiation
2450 // and the found name refers to an instance member function, otherwise
2451 // the caller will try to create an implicit member call and this is wrong
2452 // for default arguments.
2453 //
2454 // FIXME: Is this special case necessary? We could allow the caller to
2455 // diagnose this.
2456 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2457 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2458 return true;
2459 }
2460
2461 // Tell the callee to try to recover.
2462 return false;
2463}
2464
2467 TemplateArgumentListInfo *ExplicitTemplateArgs,
2468 ArrayRef<Expr *> Args, DeclContext *LookupCtx,
2469 TypoExpr **Out) {
2470 DeclarationName Name = R.getLookupName();
2471
2472 unsigned diagnostic = diag::err_undeclared_var_use;
2473 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2474 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2475 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2476 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2477 diagnostic = diag::err_undeclared_use;
2478 diagnostic_suggest = diag::err_undeclared_use_suggest;
2479 }
2480
2481 // If the original lookup was an unqualified lookup, fake an
2482 // unqualified lookup. This is useful when (for example) the
2483 // original lookup would not have found something because it was a
2484 // dependent name.
2485 DeclContext *DC =
2486 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2487 while (DC) {
2488 if (isa<CXXRecordDecl>(DC)) {
2489 if (ExplicitTemplateArgs) {
2491 R, S, SS, Context.getRecordType(cast<CXXRecordDecl>(DC)),
2492 /*EnteringContext*/ false, TemplateNameIsRequired,
2493 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2494 return true;
2495 } else {
2496 LookupQualifiedName(R, DC);
2497 }
2498
2499 if (!R.empty()) {
2500 // Don't give errors about ambiguities in this lookup.
2502
2503 // If there's a best viable function among the results, only mention
2504 // that one in the notes.
2505 OverloadCandidateSet Candidates(R.getNameLoc(),
2507 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2509 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2510 OR_Success) {
2511 R.clear();
2512 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2513 R.resolveKind();
2514 }
2515
2517 }
2518
2519 R.clear();
2520 }
2521
2522 DC = DC->getLookupParent();
2523 }
2524
2525 // We didn't find anything, so try to correct for a typo.
2526 TypoCorrection Corrected;
2527 if (S && Out) {
2528 SourceLocation TypoLoc = R.getNameLoc();
2529 assert(!ExplicitTemplateArgs &&
2530 "Diagnosing an empty lookup with explicit template args!");
2531 *Out = CorrectTypoDelayed(
2532 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2533 [=](const TypoCorrection &TC) {
2534 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2535 diagnostic, diagnostic_suggest);
2536 },
2537 nullptr, CTK_ErrorRecovery, LookupCtx);
2538 if (*Out)
2539 return true;
2540 } else if (S && (Corrected =
2542 &SS, CCC, CTK_ErrorRecovery, LookupCtx))) {
2543 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2544 bool DroppedSpecifier =
2545 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2546 R.setLookupName(Corrected.getCorrection());
2547
2548 bool AcceptableWithRecovery = false;
2549 bool AcceptableWithoutRecovery = false;
2550 NamedDecl *ND = Corrected.getFoundDecl();
2551 if (ND) {
2552 if (Corrected.isOverloaded()) {
2556 for (NamedDecl *CD : Corrected) {
2557 if (FunctionTemplateDecl *FTD =
2558 dyn_cast<FunctionTemplateDecl>(CD))
2560 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2561 Args, OCS);
2562 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2563 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2565 Args, OCS);
2566 }
2567 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2568 case OR_Success:
2569 ND = Best->FoundDecl;
2570 Corrected.setCorrectionDecl(ND);
2571 break;
2572 default:
2573 // FIXME: Arbitrarily pick the first declaration for the note.
2574 Corrected.setCorrectionDecl(ND);
2575 break;
2576 }
2577 }
2578 R.addDecl(ND);
2579 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2580 CXXRecordDecl *Record = nullptr;
2581 if (Corrected.getCorrectionSpecifier()) {
2582 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2583 Record = Ty->getAsCXXRecordDecl();
2584 }
2585 if (!Record)
2586 Record = cast<CXXRecordDecl>(
2589 }
2590
2591 auto *UnderlyingND = ND->getUnderlyingDecl();
2592 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2593 isa<FunctionTemplateDecl>(UnderlyingND);
2594 // FIXME: If we ended up with a typo for a type name or
2595 // Objective-C class name, we're in trouble because the parser
2596 // is in the wrong place to recover. Suggest the typo
2597 // correction, but don't make it a fix-it since we're not going
2598 // to recover well anyway.
2599 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2600 getAsTypeTemplateDecl(UnderlyingND) ||
2601 isa<ObjCInterfaceDecl>(UnderlyingND);
2602 } else {
2603 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2604 // because we aren't able to recover.
2605 AcceptableWithoutRecovery = true;
2606 }
2607
2608 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2609 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2610 ? diag::note_implicit_param_decl
2611 : diag::note_previous_decl;
2612 if (SS.isEmpty())
2613 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2614 PDiag(NoteID), AcceptableWithRecovery);
2615 else
2616 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2617 << Name << computeDeclContext(SS, false)
2618 << DroppedSpecifier << SS.getRange(),
2619 PDiag(NoteID), AcceptableWithRecovery);
2620
2621 // Tell the callee whether to try to recover.
2622 return !AcceptableWithRecovery;
2623 }
2624 }
2625 R.clear();
2626
2627 // Emit a special diagnostic for failed member lookups.
2628 // FIXME: computing the declaration context might fail here (?)
2629 if (!SS.isEmpty()) {
2630 Diag(R.getNameLoc(), diag::err_no_member)
2631 << Name << computeDeclContext(SS, false)
2632 << SS.getRange();
2633 return true;
2634 }
2635
2636 // Give up, we can't recover.
2637 Diag(R.getNameLoc(), diagnostic) << Name;
2638 return true;
2639}
2640
2641/// In Microsoft mode, if we are inside a template class whose parent class has
2642/// dependent base classes, and we can't resolve an unqualified identifier, then
2643/// assume the identifier is a member of a dependent base class. We can only
2644/// recover successfully in static methods, instance methods, and other contexts
2645/// where 'this' is available. This doesn't precisely match MSVC's
2646/// instantiation model, but it's close enough.
2647static Expr *
2649 DeclarationNameInfo &NameInfo,
2650 SourceLocation TemplateKWLoc,
2651 const TemplateArgumentListInfo *TemplateArgs) {
2652 // Only try to recover from lookup into dependent bases in static methods or
2653 // contexts where 'this' is available.
2654 QualType ThisType = S.getCurrentThisType();
2655 const CXXRecordDecl *RD = nullptr;
2656 if (!ThisType.isNull())
2657 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2658 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2659 RD = MD->getParent();
2660 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2661 return nullptr;
2662
2663 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2664 // is available, suggest inserting 'this->' as a fixit.
2665 SourceLocation Loc = NameInfo.getLoc();
2666 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2667 DB << NameInfo.getName() << RD;
2668
2669 if (!ThisType.isNull()) {
2670 DB << FixItHint::CreateInsertion(Loc, "this->");
2672 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2673 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2674 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2675 }
2676
2677 // Synthesize a fake NNS that points to the derived class. This will
2678 // perform name lookup during template instantiation.
2679 CXXScopeSpec SS;
2680 auto *NNS =
2681 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2682 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2684 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2685 TemplateArgs);
2686}
2687
2690 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2691 bool HasTrailingLParen, bool IsAddressOfOperand,
2693 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2694 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2695 "cannot be direct & operand and have a trailing lparen");
2696 if (SS.isInvalid())
2697 return ExprError();
2698
2699 TemplateArgumentListInfo TemplateArgsBuffer;
2700
2701 // Decompose the UnqualifiedId into the following data.
2702 DeclarationNameInfo NameInfo;
2703 const TemplateArgumentListInfo *TemplateArgs;
2704 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2705
2706 DeclarationName Name = NameInfo.getName();
2707 IdentifierInfo *II = Name.getAsIdentifierInfo();
2708 SourceLocation NameLoc = NameInfo.getLoc();
2709
2710 if (II && II->isEditorPlaceholder()) {
2711 // FIXME: When typed placeholders are supported we can create a typed
2712 // placeholder expression node.
2713 return ExprError();
2714 }
2715
2716 // This specially handles arguments of attributes appertains to a type of C
2717 // struct field such that the name lookup within a struct finds the member
2718 // name, which is not the case for other contexts in C.
2719 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2720 // See if this is reference to a field of struct.
2721 LookupResult R(*this, NameInfo, LookupMemberName);
2722 // LookupName handles a name lookup from within anonymous struct.
2723 if (LookupName(R, S)) {
2724 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2725 QualType type = VD->getType().getNonReferenceType();
2726 // This will eventually be translated into MemberExpr upon
2727 // the use of instantiated struct fields.
2728 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2729 }
2730 }
2731 }
2732
2733 // Perform the required lookup.
2734 LookupResult R(*this, NameInfo,
2738 if (TemplateKWLoc.isValid() || TemplateArgs) {
2739 // Lookup the template name again to correctly establish the context in
2740 // which it was found. This is really unfortunate as we already did the
2741 // lookup to determine that it was a template name in the first place. If
2742 // this becomes a performance hit, we can work harder to preserve those
2743 // results until we get here but it's likely not worth it.
2744 AssumedTemplateKind AssumedTemplate;
2745 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2746 /*EnteringContext=*/false, TemplateKWLoc,
2747 &AssumedTemplate))
2748 return ExprError();
2749
2751 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2752 IsAddressOfOperand, TemplateArgs);
2753 } else {
2754 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2755 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2756 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2757
2758 // If the result might be in a dependent base class, this is a dependent
2759 // id-expression.
2761 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2762 IsAddressOfOperand, TemplateArgs);
2763
2764 // If this reference is in an Objective-C method, then we need to do
2765 // some special Objective-C lookup, too.
2766 if (IvarLookupFollowUp) {
2767 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2768 if (E.isInvalid())
2769 return ExprError();
2770
2771 if (Expr *Ex = E.getAs<Expr>())
2772 return Ex;
2773 }
2774 }
2775
2776 if (R.isAmbiguous())
2777 return ExprError();
2778
2779 // This could be an implicitly declared function reference if the language
2780 // mode allows it as a feature.
2781 if (R.empty() && HasTrailingLParen && II &&
2782 getLangOpts().implicitFunctionsAllowed()) {
2783 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2784 if (D) R.addDecl(D);
2785 }
2786
2787 // Determine whether this name might be a candidate for
2788 // argument-dependent lookup.
2789 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2790
2791 if (R.empty() && !ADL) {
2792 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2793 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2794 TemplateKWLoc, TemplateArgs))
2795 return E;
2796 }
2797
2798 // Don't diagnose an empty lookup for inline assembly.
2799 if (IsInlineAsmIdentifier)
2800 return ExprError();
2801
2802 // If this name wasn't predeclared and if this is not a function
2803 // call, diagnose the problem.
2804 TypoExpr *TE = nullptr;
2805 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2806 : nullptr);
2807 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2808 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2809 "Typo correction callback misconfigured");
2810 if (CCC) {
2811 // Make sure the callback knows what the typo being diagnosed is.
2812 CCC->setTypoName(II);
2813 if (SS.isValid())
2814 CCC->setTypoNNS(SS.getScopeRep());
2815 }
2816 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2817 // a template name, but we happen to have always already looked up the name
2818 // before we get here if it must be a template name.
2819 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2820 {}, nullptr, &TE)) {
2821 if (TE && KeywordReplacement) {
2822 auto &State = getTypoExprState(TE);
2823 auto BestTC = State.Consumer->getNextCorrection();
2824 if (BestTC.isKeyword()) {
2825 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2826 if (State.DiagHandler)
2827 State.DiagHandler(BestTC);
2828 KeywordReplacement->startToken();
2829 KeywordReplacement->setKind(II->getTokenID());
2830 KeywordReplacement->setIdentifierInfo(II);
2831 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2832 // Clean up the state associated with the TypoExpr, since it has
2833 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2834 clearDelayedTypo(TE);
2835 // Signal that a correction to a keyword was performed by returning a
2836 // valid-but-null ExprResult.
2837 return (Expr*)nullptr;
2838 }
2839 State.Consumer->resetCorrectionStream();
2840 }
2841 return TE ? TE : ExprError();
2842 }
2843
2844 assert(!R.empty() &&
2845 "DiagnoseEmptyLookup returned false but added no results");
2846
2847 // If we found an Objective-C instance variable, let
2848 // LookupInObjCMethod build the appropriate expression to
2849 // reference the ivar.
2850 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2851 R.clear();
2852 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2853 // In a hopelessly buggy code, Objective-C instance variable
2854 // lookup fails and no expression will be built to reference it.
2855 if (!E.isInvalid() && !E.get())
2856 return ExprError();
2857 return E;
2858 }
2859 }
2860
2861 // This is guaranteed from this point on.
2862 assert(!R.empty() || ADL);
2863
2864 // Check whether this might be a C++ implicit instance member access.
2865 // C++ [class.mfct.non-static]p3:
2866 // When an id-expression that is not part of a class member access
2867 // syntax and not used to form a pointer to member is used in the
2868 // body of a non-static member function of class X, if name lookup
2869 // resolves the name in the id-expression to a non-static non-type
2870 // member of some class C, the id-expression is transformed into a
2871 // class member access expression using (*this) as the
2872 // postfix-expression to the left of the . operator.
2873 //
2874 // But we don't actually need to do this for '&' operands if R
2875 // resolved to a function or overloaded function set, because the
2876 // expression is ill-formed if it actually works out to be a
2877 // non-static member function:
2878 //
2879 // C++ [expr.ref]p4:
2880 // Otherwise, if E1.E2 refers to a non-static member function. . .
2881 // [t]he expression can be used only as the left-hand operand of a
2882 // member function call.
2883 //
2884 // There are other safeguards against such uses, but it's important
2885 // to get this right here so that we don't end up making a
2886 // spuriously dependent expression if we're inside a dependent
2887 // instance method.
2888 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2889 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2890 S);
2891
2892 if (TemplateArgs || TemplateKWLoc.isValid()) {
2893
2894 // In C++1y, if this is a variable template id, then check it
2895 // in BuildTemplateIdExpr().
2896 // The single lookup result must be a variable template declaration.
2897 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2898 Id.TemplateId->Kind == TNK_Var_template) {
2899 assert(R.getAsSingle<VarTemplateDecl>() &&
2900 "There should only be one declaration found.");
2901 }
2902
2903 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2904 }
2905
2906 return BuildDeclarationNameExpr(SS, R, ADL);
2907}
2908
2910 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2911 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
2912 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2913 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
2914
2915 if (R.isAmbiguous())
2916 return ExprError();
2917
2919 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2920 NameInfo, /*TemplateArgs=*/nullptr);
2921
2922 if (R.empty()) {
2923 // Don't diagnose problems with invalid record decl, the secondary no_member
2924 // diagnostic during template instantiation is likely bogus, e.g. if a class
2925 // is invalid because it's derived from an invalid base class, then missing
2926 // members were likely supposed to be inherited.
2928 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2929 if (CD->isInvalidDecl())
2930 return ExprError();
2931 Diag(NameInfo.getLoc(), diag::err_no_member)
2932 << NameInfo.getName() << DC << SS.getRange();
2933 return ExprError();
2934 }
2935
2936 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2937 // Diagnose a missing typename if this resolved unambiguously to a type in
2938 // a dependent context. If we can recover with a type, downgrade this to
2939 // a warning in Microsoft compatibility mode.
2940 unsigned DiagID = diag::err_typename_missing;
2941 if (RecoveryTSI && getLangOpts().MSVCCompat)
2942 DiagID = diag::ext_typename_missing;
2944 auto D = Diag(Loc, DiagID);
2945 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2946 << SourceRange(Loc, NameInfo.getEndLoc());
2947
2948 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2949 // context.
2950 if (!RecoveryTSI)
2951 return ExprError();
2952
2953 // Only issue the fixit if we're prepared to recover.
2954 D << FixItHint::CreateInsertion(Loc, "typename ");
2955
2956 // Recover by pretending this was an elaborated type.
2958 TypeLocBuilder TLB;
2959 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2960
2965
2966 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2967
2968 return ExprEmpty();
2969 }
2970
2971 // If necessary, build an implicit class member access.
2972 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2974 /*TemplateKWLoc=*/SourceLocation(),
2975 R, /*TemplateArgs=*/nullptr,
2976 /*S=*/nullptr);
2977
2978 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
2979}
2980
2983 NestedNameSpecifier *Qualifier,
2984 NamedDecl *FoundDecl,
2985 NamedDecl *Member) {
2986 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2987 if (!RD)
2988 return From;
2989
2990 QualType DestRecordType;
2991 QualType DestType;
2992 QualType FromRecordType;
2993 QualType FromType = From->getType();
2994 bool PointerConversions = false;
2995 if (isa<FieldDecl>(Member)) {
2996 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2997 auto FromPtrType = FromType->getAs<PointerType>();
2998 DestRecordType = Context.getAddrSpaceQualType(
2999 DestRecordType, FromPtrType
3000 ? FromType->getPointeeType().getAddressSpace()
3001 : FromType.getAddressSpace());
3002
3003 if (FromPtrType) {
3004 DestType = Context.getPointerType(DestRecordType);
3005 FromRecordType = FromPtrType->getPointeeType();
3006 PointerConversions = true;
3007 } else {
3008 DestType = DestRecordType;
3009 FromRecordType = FromType;
3010 }
3011 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3012 if (!Method->isImplicitObjectMemberFunction())
3013 return From;
3014
3015 DestType = Method->getThisType().getNonReferenceType();
3016 DestRecordType = Method->getFunctionObjectParameterType();
3017
3018 if (FromType->getAs<PointerType>()) {
3019 FromRecordType = FromType->getPointeeType();
3020 PointerConversions = true;
3021 } else {
3022 FromRecordType = FromType;
3023 DestType = DestRecordType;
3024 }
3025
3026 LangAS FromAS = FromRecordType.getAddressSpace();
3027 LangAS DestAS = DestRecordType.getAddressSpace();
3028 if (FromAS != DestAS) {
3029 QualType FromRecordTypeWithoutAS =
3030 Context.removeAddrSpaceQualType(FromRecordType);
3031 QualType FromTypeWithDestAS =
3032 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3033 if (PointerConversions)
3034 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3035 From = ImpCastExprToType(From, FromTypeWithDestAS,
3036 CK_AddressSpaceConversion, From->getValueKind())
3037 .get();
3038 }
3039 } else {
3040 // No conversion necessary.
3041 return From;
3042 }
3043
3044 if (DestType->isDependentType() || FromType->isDependentType())
3045 return From;
3046
3047 // If the unqualified types are the same, no conversion is necessary.
3048 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3049 return From;
3050
3051 SourceRange FromRange = From->getSourceRange();
3052 SourceLocation FromLoc = FromRange.getBegin();
3053
3054 ExprValueKind VK = From->getValueKind();
3055
3056 // C++ [class.member.lookup]p8:
3057 // [...] Ambiguities can often be resolved by qualifying a name with its
3058 // class name.
3059 //
3060 // If the member was a qualified name and the qualified referred to a
3061 // specific base subobject type, we'll cast to that intermediate type
3062 // first and then to the object in which the member is declared. That allows
3063 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3064 //
3065 // class Base { public: int x; };
3066 // class Derived1 : public Base { };
3067 // class Derived2 : public Base { };
3068 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3069 //
3070 // void VeryDerived::f() {
3071 // x = 17; // error: ambiguous base subobjects
3072 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3073 // }
3074 if (Qualifier && Qualifier->getAsType()) {
3075 QualType QType = QualType(Qualifier->getAsType(), 0);
3076 assert(QType->isRecordType() && "lookup done with non-record type");
3077
3078 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3079
3080 // In C++98, the qualifier type doesn't actually have to be a base
3081 // type of the object type, in which case we just ignore it.
3082 // Otherwise build the appropriate casts.
3083 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3084 CXXCastPath BasePath;
3085 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3086 FromLoc, FromRange, &BasePath))
3087 return ExprError();
3088
3089 if (PointerConversions)
3090 QType = Context.getPointerType(QType);
3091 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3092 VK, &BasePath).get();
3093
3094 FromType = QType;
3095 FromRecordType = QRecordType;
3096
3097 // If the qualifier type was the same as the destination type,
3098 // we're done.
3099 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3100 return From;
3101 }
3102 }
3103
3104 CXXCastPath BasePath;
3105 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3106 FromLoc, FromRange, &BasePath,
3107 /*IgnoreAccess=*/true))
3108 return ExprError();
3109
3110 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3111 VK, &BasePath);
3112}
3113
3115 const LookupResult &R,
3116 bool HasTrailingLParen) {
3117 // Only when used directly as the postfix-expression of a call.
3118 if (!HasTrailingLParen)
3119 return false;
3120
3121 // Never if a scope specifier was provided.
3122 if (SS.isNotEmpty())
3123 return false;
3124
3125 // Only in C++ or ObjC++.
3126 if (!getLangOpts().CPlusPlus)
3127 return false;
3128
3129 // Turn off ADL when we find certain kinds of declarations during
3130 // normal lookup:
3131 for (const NamedDecl *D : R) {
3132 // C++0x [basic.lookup.argdep]p3:
3133 // -- a declaration of a class member
3134 // Since using decls preserve this property, we check this on the
3135 // original decl.
3136 if (D->isCXXClassMember())
3137 return false;
3138
3139 // C++0x [basic.lookup.argdep]p3:
3140 // -- a block-scope function declaration that is not a
3141 // using-declaration
3142 // NOTE: we also trigger this for function templates (in fact, we
3143 // don't check the decl type at all, since all other decl types
3144 // turn off ADL anyway).
3145 if (isa<UsingShadowDecl>(D))
3146 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3148 return false;
3149
3150 // C++0x [basic.lookup.argdep]p3:
3151 // -- a declaration that is neither a function or a function
3152 // template
3153 // And also for builtin functions.
3154 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3155 // But also builtin functions.
3156 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3157 return false;
3158 } else if (!isa<FunctionTemplateDecl>(D))
3159 return false;
3160 }
3161
3162 return true;
3163}
3164
3165
3166/// Diagnoses obvious problems with the use of the given declaration
3167/// as an expression. This is only actually called for lookups that
3168/// were not overloaded, and it doesn't promise that the declaration
3169/// will in fact be used.
3171 bool AcceptInvalid) {
3172 if (D->isInvalidDecl() && !AcceptInvalid)
3173 return true;
3174
3175 if (isa<TypedefNameDecl>(D)) {
3176 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3177 return true;
3178 }
3179
3180 if (isa<ObjCInterfaceDecl>(D)) {
3181 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3182 return true;
3183 }
3184
3185 if (isa<NamespaceDecl>(D)) {
3186 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3187 return true;
3188 }
3189
3190 return false;
3191}
3192
3193// Certain multiversion types should be treated as overloaded even when there is
3194// only one result.
3196 assert(R.isSingleResult() && "Expected only a single result");
3197 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3198 return FD &&
3199 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3200}
3201
3203 LookupResult &R, bool NeedsADL,
3204 bool AcceptInvalidDecl) {
3205 // If this is a single, fully-resolved result and we don't need ADL,
3206 // just build an ordinary singleton decl ref.
3207 if (!NeedsADL && R.isSingleResult() &&
3211 R.getRepresentativeDecl(), nullptr,
3212 AcceptInvalidDecl);
3213
3214 // We only need to check the declaration if there's exactly one
3215 // result, because in the overloaded case the results can only be
3216 // functions and function templates.
3218 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3219 AcceptInvalidDecl))
3220 return ExprError();
3221
3222 // Otherwise, just build an unresolved lookup expression. Suppress
3223 // any lookup-related diagnostics; we'll hash these out later, when
3224 // we've picked a target.
3226
3229 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3230 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3231
3232 return ULE;
3233}
3234
3236 SourceLocation loc,
3237 ValueDecl *var);
3238
3240 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3241 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3242 bool AcceptInvalidDecl) {
3243 assert(D && "Cannot refer to a NULL declaration");
3244 assert(!isa<FunctionTemplateDecl>(D) &&
3245 "Cannot refer unambiguously to a function template");
3246
3247 SourceLocation Loc = NameInfo.getLoc();
3248 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3249 // Recovery from invalid cases (e.g. D is an invalid Decl).
3250 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3251 // diagnostics, as invalid decls use int as a fallback type.
3252 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3253 }
3254
3255 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3256 // Specifically diagnose references to class templates that are missing
3257 // a template argument list.
3258 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3259 return ExprError();
3260 }
3261
3262 // Make sure that we're referring to a value.
3263 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3264 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3265 Diag(D->getLocation(), diag::note_declared_at);
3266 return ExprError();
3267 }
3268
3269 // Check whether this declaration can be used. Note that we suppress
3270 // this check when we're going to perform argument-dependent lookup
3271 // on this function name, because this might not be the function
3272 // that overload resolution actually selects.
3273 if (DiagnoseUseOfDecl(D, Loc))
3274 return ExprError();
3275
3276 auto *VD = cast<ValueDecl>(D);
3277
3278 // Only create DeclRefExpr's for valid Decl's.
3279 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3280 return ExprError();
3281
3282 // Handle members of anonymous structs and unions. If we got here,
3283 // and the reference is to a class member indirect field, then this
3284 // must be the subject of a pointer-to-member expression.
3285 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3286 IndirectField && !IndirectField->isCXXClassMember())
3288 IndirectField);
3289
3290 QualType type = VD->getType();
3291 if (type.isNull())
3292 return ExprError();
3293 ExprValueKind valueKind = VK_PRValue;
3294
3295 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3296 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3297 // is expanded by some outer '...' in the context of the use.
3298 type = type.getNonPackExpansionType();
3299
3300 switch (D->getKind()) {
3301 // Ignore all the non-ValueDecl kinds.
3302#define ABSTRACT_DECL(kind)
3303#define VALUE(type, base)
3304#define DECL(type, base) case Decl::type:
3305#include "clang/AST/DeclNodes.inc"
3306 llvm_unreachable("invalid value decl kind");
3307
3308 // These shouldn't make it here.
3309 case Decl::ObjCAtDefsField:
3310 llvm_unreachable("forming non-member reference to ivar?");
3311
3312 // Enum constants are always r-values and never references.
3313 // Unresolved using declarations are dependent.
3314 case Decl::EnumConstant:
3315 case Decl::UnresolvedUsingValue:
3316 case Decl::OMPDeclareReduction:
3317 case Decl::OMPDeclareMapper:
3318 valueKind = VK_PRValue;
3319 break;
3320
3321 // Fields and indirect fields that got here must be for
3322 // pointer-to-member expressions; we just call them l-values for
3323 // internal consistency, because this subexpression doesn't really
3324 // exist in the high-level semantics.
3325 case Decl::Field:
3326 case Decl::IndirectField:
3327 case Decl::ObjCIvar:
3328 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3329 "building reference to field in C?");
3330
3331 // These can't have reference type in well-formed programs, but
3332 // for internal consistency we do this anyway.
3333 type = type.getNonReferenceType();
3334 valueKind = VK_LValue;
3335 break;
3336
3337 // Non-type template parameters are either l-values or r-values
3338 // depending on the type.
3339 case Decl::NonTypeTemplateParm: {
3340 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3341 type = reftype->getPointeeType();
3342 valueKind = VK_LValue; // even if the parameter is an r-value reference
3343 break;
3344 }
3345
3346 // [expr.prim.id.unqual]p2:
3347 // If the entity is a template parameter object for a template
3348 // parameter of type T, the type of the expression is const T.
3349 // [...] The expression is an lvalue if the entity is a [...] template
3350 // parameter object.
3351 if (type->isRecordType()) {
3352 type = type.getUnqualifiedType().withConst();
3353 valueKind = VK_LValue;
3354 break;
3355 }
3356
3357 // For non-references, we need to strip qualifiers just in case
3358 // the template parameter was declared as 'const int' or whatever.
3359 valueKind = VK_PRValue;
3360 type = type.getUnqualifiedType();
3361 break;
3362 }
3363
3364 case Decl::Var:
3365 case Decl::VarTemplateSpecialization:
3366 case Decl::VarTemplatePartialSpecialization:
3367 case Decl::Decomposition:
3368 case Decl::Binding:
3369 case Decl::OMPCapturedExpr:
3370 // In C, "extern void blah;" is valid and is an r-value.
3371 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3372 type->isVoidType()) {
3373 valueKind = VK_PRValue;
3374 break;
3375 }
3376 [[fallthrough]];
3377
3378 case Decl::ImplicitParam:
3379 case Decl::ParmVar: {
3380 // These are always l-values.
3381 valueKind = VK_LValue;
3382 type = type.getNonReferenceType();
3383
3384 // FIXME: Does the addition of const really only apply in
3385 // potentially-evaluated contexts? Since the variable isn't actually
3386 // captured in an unevaluated context, it seems that the answer is no.
3387 if (!isUnevaluatedContext()) {
3388 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3389 if (!CapturedType.isNull())
3390 type = CapturedType;
3391 }
3392 break;
3393 }
3394
3395 case Decl::Function: {
3396 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3399 valueKind = VK_PRValue;
3400 break;
3401 }
3402 }
3403
3404 const FunctionType *fty = type->castAs<FunctionType>();
3405
3406 // If we're referring to a function with an __unknown_anytype
3407 // result type, make the entire expression __unknown_anytype.
3408 if (fty->getReturnType() == Context.UnknownAnyTy) {
3410 valueKind = VK_PRValue;
3411 break;
3412 }
3413
3414 // Functions are l-values in C++.
3415 if (getLangOpts().CPlusPlus) {
3416 valueKind = VK_LValue;
3417 break;
3418 }
3419
3420 // C99 DR 316 says that, if a function type comes from a
3421 // function definition (without a prototype), that type is only
3422 // used for checking compatibility. Therefore, when referencing
3423 // the function, we pretend that we don't have the full function
3424 // type.
3425 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3427 fty->getExtInfo());
3428
3429 // Functions are r-values in C.
3430 valueKind = VK_PRValue;
3431 break;
3432 }
3433
3434 case Decl::CXXDeductionGuide:
3435 llvm_unreachable("building reference to deduction guide");
3436
3437 case Decl::MSProperty:
3438 case Decl::MSGuid:
3439 case Decl::TemplateParamObject:
3440 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3441 // capture in OpenMP, or duplicated between host and device?
3442 valueKind = VK_LValue;
3443 break;
3444
3445 case Decl::UnnamedGlobalConstant:
3446 valueKind = VK_LValue;
3447 break;
3448
3449 case Decl::CXXMethod:
3450 // If we're referring to a method with an __unknown_anytype
3451 // result type, make the entire expression __unknown_anytype.
3452 // This should only be possible with a type written directly.
3453 if (const FunctionProtoType *proto =
3454 dyn_cast<FunctionProtoType>(VD->getType()))
3455 if (proto->getReturnType() == Context.UnknownAnyTy) {
3457 valueKind = VK_PRValue;
3458 break;
3459 }
3460
3461 // C++ methods are l-values if static, r-values if non-static.
3462 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3463 valueKind = VK_LValue;
3464 break;
3465 }
3466 [[fallthrough]];
3467
3468 case Decl::CXXConversion:
3469 case Decl::CXXDestructor:
3470 case Decl::CXXConstructor:
3471 valueKind = VK_PRValue;
3472 break;
3473 }
3474
3475 auto *E =
3476 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3477 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3478 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3479 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3480 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3481 // diagnostics).
3482 if (VD->isInvalidDecl() && E)
3483 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3484 return E;
3485}
3486
3487static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3489 Target.resize(CharByteWidth * (Source.size() + 1));
3490 char *ResultPtr = &Target[0];
3491 const llvm::UTF8 *ErrorPtr;
3492 bool success =
3493 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3494 (void)success;
3495 assert(success);
3496 Target.resize(ResultPtr - &Target[0]);
3497}
3498
3501 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3502 if (!currentDecl) {
3503 Diag(Loc, diag::ext_predef_outside_function);
3504 currentDecl = Context.getTranslationUnitDecl();
3505 }
3506
3507 QualType ResTy;
3508 StringLiteral *SL = nullptr;
3509 if (cast<DeclContext>(currentDecl)->isDependentContext())
3510 ResTy = Context.DependentTy;
3511 else {
3512 // Pre-defined identifiers are of type char[x], where x is the length of
3513 // the string.
3514 bool ForceElaboratedPrinting =
3515 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3516 auto Str =
3517 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3518 unsigned Length = Str.length();
3519
3520 llvm::APInt LengthI(32, Length + 1);
3523 ResTy =
3525 SmallString<32> RawChars;
3527 Str, RawChars);
3528 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3530 /*IndexTypeQuals*/ 0);
3532 /*Pascal*/ false, ResTy, Loc);
3533 } else {
3535 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3537 /*IndexTypeQuals*/ 0);
3539 /*Pascal*/ false, ResTy, Loc);
3540 }
3541 }
3542
3543 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3544 SL);
3545}
3546
3549}
3550
3552 SmallString<16> CharBuffer;
3553 bool Invalid = false;
3554 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3555 if (Invalid)
3556 return ExprError();
3557
3558 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3559 PP, Tok.getKind());
3560 if (Literal.hadError())
3561 return ExprError();
3562
3563 QualType Ty;
3564 if (Literal.isWide())
3565 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3566 else if (Literal.isUTF8() && getLangOpts().C23)
3567 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3568 else if (Literal.isUTF8() && getLangOpts().Char8)
3569 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3570 else if (Literal.isUTF16())
3571 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3572 else if (Literal.isUTF32())
3573 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3574 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3575 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3576 else
3577 Ty = Context.CharTy; // 'x' -> char in C++;
3578 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3579
3581 if (Literal.isWide())
3583 else if (Literal.isUTF16())
3585 else if (Literal.isUTF32())
3587 else if (Literal.isUTF8())
3589
3590 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3591 Tok.getLocation());
3592
3593 if (Literal.getUDSuffix().empty())
3594 return Lit;
3595
3596 // We're building a user-defined literal.
3597 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3598 SourceLocation UDSuffixLoc =
3599 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3600
3601 // Make sure we're allowed user-defined literals here.
3602 if (!UDLScope)
3603 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3604
3605 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3606 // operator "" X (ch)
3607 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3608 Lit, Tok.getLocation());
3609}
3610
3612 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3614 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3615 Context.IntTy, Loc);
3616}
3617
3620 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3621
3622 using llvm::APFloat;
3623 APFloat Val(Format);
3624
3625 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3626 if (RM == llvm::RoundingMode::Dynamic)
3627 RM = llvm::RoundingMode::NearestTiesToEven;
3628 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3629
3630 // Overflow is always an error, but underflow is only an error if
3631 // we underflowed to zero (APFloat reports denormals as underflow).
3632 if ((result & APFloat::opOverflow) ||
3633 ((result & APFloat::opUnderflow) && Val.isZero())) {
3634 unsigned diagnostic;
3635 SmallString<20> buffer;
3636 if (result & APFloat::opOverflow) {
3637 diagnostic = diag::warn_float_overflow;
3638 APFloat::getLargest(Format).toString(buffer);
3639 } else {
3640 diagnostic = diag::warn_float_underflow;
3641 APFloat::getSmallest(Format).toString(buffer);
3642 }
3643
3644 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3645 }
3646
3647 bool isExact = (result == APFloat::opOK);
3648 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3649}
3650
3652 assert(E && "Invalid expression");
3653
3654 if (E->isValueDependent())
3655 return false;
3656
3657 QualType QT = E->getType();
3658 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3659 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3660 return true;
3661 }
3662
3663 llvm::APSInt ValueAPS;
3665
3666 if (R.isInvalid())
3667 return true;
3668
3669 // GCC allows the value of unroll count to be 0.
3670 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3671 // "The values of 0 and 1 block any unrolling of the loop."
3672 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3673 // '#pragma unroll' cases.
3674 bool ValueIsPositive =
3675 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3676 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3677 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3678 << toString(ValueAPS, 10) << ValueIsPositive;
3679 return true;
3680 }
3681
3682 return false;
3683}
3684
3686 // Fast path for a single digit (which is quite common). A single digit
3687 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3688 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3689 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3690 return ActOnIntegerConstant(Tok.getLocation(), Val);
3691 }
3692
3693 SmallString<128> SpellingBuffer;
3694 // NumericLiteralParser wants to overread by one character. Add padding to
3695 // the buffer in case the token is copied to the buffer. If getSpelling()
3696 // returns a StringRef to the memory buffer, it should have a null char at
3697 // the EOF, so it is also safe.
3698 SpellingBuffer.resize(Tok.getLength() + 1);
3699
3700 // Get the spelling of the token, which eliminates trigraphs, etc.
3701 bool Invalid = false;
3702 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3703 if (Invalid)
3704 return ExprError();
3705
3706 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3709 if (Literal.hadError)
3710 return ExprError();
3711
3712 if (Literal.hasUDSuffix()) {
3713 // We're building a user-defined literal.
3714 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3715 SourceLocation UDSuffixLoc =
3716 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3717
3718 // Make sure we're allowed user-defined literals here.
3719 if (!UDLScope)
3720 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3721
3722 QualType CookedTy;
3723 if (Literal.isFloatingLiteral()) {
3724 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3725 // long double, the literal is treated as a call of the form
3726 // operator "" X (f L)
3727 CookedTy = Context.LongDoubleTy;
3728 } else {
3729 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3730 // unsigned long long, the literal is treated as a call of the form
3731 // operator "" X (n ULL)
3732 CookedTy = Context.UnsignedLongLongTy;
3733 }
3734
3735 DeclarationName OpName =
3737 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3738 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3739
3740 SourceLocation TokLoc = Tok.getLocation();
3741
3742 // Perform literal operator lookup to determine if we're building a raw
3743 // literal or a cooked one.
3744 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3745 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3746 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3747 /*AllowStringTemplatePack*/ false,
3748 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3750 // Lookup failure for imaginary constants isn't fatal, there's still the
3751 // GNU extension producing _Complex types.
3752 break;
3753 case LOLR_Error:
3754 return ExprError();
3755 case LOLR_Cooked: {
3756 Expr *Lit;
3757 if (Literal.isFloatingLiteral()) {
3758 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3759 } else {
3760 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3761 if (Literal.GetIntegerValue(ResultVal))
3762 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3763 << /* Unsigned */ 1;
3764 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3765 Tok.getLocation());
3766 }
3767 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3768 }
3769
3770 case LOLR_Raw: {
3771 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3772 // literal is treated as a call of the form
3773 // operator "" X ("n")
3774 unsigned Length = Literal.getUDSuffixOffset();
3777 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3778 Expr *Lit =
3779 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3781 /*Pascal*/ false, StrTy, &TokLoc, 1);
3782 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3783 }
3784
3785 case LOLR_Template: {
3786 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3787 // template), L is treated as a call fo the form
3788 // operator "" X <'c1', 'c2', ... 'ck'>()
3789 // where n is the source character sequence c1 c2 ... ck.
3790 TemplateArgumentListInfo ExplicitArgs;
3791 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3792 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3793 llvm::APSInt Value(CharBits, CharIsUnsigned);
3794 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3795 Value = TokSpelling[I];
3798 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3799 }
3800 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
3801 }
3803 llvm_unreachable("unexpected literal operator lookup result");
3804 }
3805 }
3806
3807 Expr *Res;
3808
3809 if (Literal.isFixedPointLiteral()) {
3810 QualType Ty;
3811
3812 if (Literal.isAccum) {
3813 if (Literal.isHalf) {
3814 Ty = Context.ShortAccumTy;
3815 } else if (Literal.isLong) {
3816 Ty = Context.LongAccumTy;
3817 } else {
3818 Ty = Context.AccumTy;
3819 }
3820 } else if (Literal.isFract) {
3821 if (Literal.isHalf) {
3822 Ty = Context.ShortFractTy;
3823 } else if (Literal.isLong) {
3824 Ty = Context.LongFractTy;
3825 } else {
3826 Ty = Context.FractTy;
3827 }
3828 }
3829
3830 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3831
3832 bool isSigned = !Literal.isUnsigned;
3833 unsigned scale = Context.getFixedPointScale(Ty);
3834 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3835
3836 llvm::APInt Val(bit_width, 0, isSigned);
3837 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3838 bool ValIsZero = Val.isZero() && !Overflowed;
3839
3840 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3841 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3842 // Clause 6.4.4 - The value of a constant shall be in the range of
3843 // representable values for its type, with exception for constants of a
3844 // fract type with a value of exactly 1; such a constant shall denote
3845 // the maximal value for the type.
3846 --Val;
3847 else if (Val.ugt(MaxVal) || Overflowed)
3848 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3849
3851 Tok.getLocation(), scale);
3852 } else if (Literal.isFloatingLiteral()) {
3853 QualType Ty;
3854 if (Literal.isHalf){
3855 if (getLangOpts().HLSL ||
3856 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3857 Ty = Context.HalfTy;
3858 else {
3859 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3860 return ExprError();
3861 }
3862 } else if (Literal.isFloat)
3863 Ty = Context.FloatTy;
3864 else if (Literal.isLong)
3866 else if (Literal.isFloat16)
3867 Ty = Context.Float16Ty;
3868 else if (Literal.isFloat128)
3869 Ty = Context.Float128Ty;
3870 else if (getLangOpts().HLSL)
3871 Ty = Context.FloatTy;
3872 else
3873 Ty = Context.DoubleTy;
3874
3875 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3876
3877 if (Ty == Context.DoubleTy) {
3878 if (getLangOpts().SinglePrecisionConstants) {
3879 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3880 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3881 }
3882 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3883 "cl_khr_fp64", getLangOpts())) {
3884 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3885 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3887 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3888 }
3889 }
3890 } else if (!Literal.isIntegerLiteral()) {
3891 return ExprError();
3892 } else {
3893 QualType Ty;
3894
3895 // 'z/uz' literals are a C++23 feature.
3896 if (Literal.isSizeT)
3899 ? diag::warn_cxx20_compat_size_t_suffix
3900 : diag::ext_cxx23_size_t_suffix
3901 : diag::err_cxx23_size_t_suffix);
3902
3903 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
3904 // but we do not currently support the suffix in C++ mode because it's not
3905 // entirely clear whether WG21 will prefer this suffix to return a library
3906 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
3907 // literals are a C++ extension.
3908 if (Literal.isBitInt)
3909 PP.Diag(Tok.getLocation(),
3910 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
3911 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
3912 : diag::ext_c23_bitint_suffix);
3913
3914 // Get the value in the widest-possible width. What is "widest" depends on
3915 // whether the literal is a bit-precise integer or not. For a bit-precise
3916 // integer type, try to scan the source to determine how many bits are
3917 // needed to represent the value. This may seem a bit expensive, but trying
3918 // to get the integer value from an overly-wide APInt is *extremely*
3919 // expensive, so the naive approach of assuming
3920 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3921 unsigned BitsNeeded =
3922 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3923 Literal.getLiteralDigits(), Literal.getRadix())
3925 llvm::APInt ResultVal(BitsNeeded, 0);
3926
3927 if (Literal.GetIntegerValue(ResultVal)) {
3928 // If this value didn't fit into uintmax_t, error and force to ull.
3929 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3930 << /* Unsigned */ 1;
3932 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3933 "long long is not intmax_t?");
3934 } else {
3935 // If this value fits into a ULL, try to figure out what else it fits into
3936 // according to the rules of C99 6.4.4.1p5.
3937
3938 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3939 // be an unsigned int.
3940 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3941
3942 // HLSL doesn't really have `long` or `long long`. We support the `ll`
3943 // suffix for portability of code with C++, but both `l` and `ll` are
3944 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
3945 // same.
3946 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
3947 Literal.isLong = true;
3948 Literal.isLongLong = false;
3949 }
3950
3951 // Check from smallest to largest, picking the smallest type we can.
3952 unsigned Width = 0;
3953
3954 // Microsoft specific integer suffixes are explicitly sized.
3955 if (Literal.MicrosoftInteger) {
3956 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3957 Width = 8;
3958 Ty = Context.CharTy;
3959 } else {
3960 Width = Literal.MicrosoftInteger;
3961 Ty = Context.getIntTypeForBitwidth(Width,
3962 /*Signed=*/!Literal.isUnsigned);
3963 }
3964 }
3965
3966 // Bit-precise integer literals are automagically-sized based on the
3967 // width required by the literal.
3968 if (Literal.isBitInt) {
3969 // The signed version has one more bit for the sign value. There are no
3970 // zero-width bit-precise integers, even if the literal value is 0.
3971 Width = std::max(ResultVal.getActiveBits(), 1u) +
3972 (Literal.isUnsigned ? 0u : 1u);
3973
3974 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
3975 // and reset the type to the largest supported width.
3976 unsigned int MaxBitIntWidth =
3978 if (Width > MaxBitIntWidth) {
3979 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3980 << Literal.isUnsigned;
3981 Width = MaxBitIntWidth;
3982 }
3983
3984 // Reset the result value to the smaller APInt and select the correct
3985 // type to be used. Note, we zext even for signed values because the
3986 // literal itself is always an unsigned value (a preceeding - is a
3987 // unary operator, not part of the literal).
3988 ResultVal = ResultVal.zextOrTrunc(Width);
3989 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
3990 }
3991
3992 // Check C++23 size_t literals.
3993 if (Literal.isSizeT) {
3994 assert(!Literal.MicrosoftInteger &&
3995 "size_t literals can't be Microsoft literals");
3996 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3998
3999 // Does it fit in size_t?
4000 if (ResultVal.isIntN(SizeTSize)) {
4001 // Does it fit in ssize_t?
4002 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4004 else if (AllowUnsigned)
4005 Ty = Context.getSizeType();
4006 Width = SizeTSize;
4007 }
4008 }
4009
4010 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4011 !Literal.isSizeT) {
4012 // Are int/unsigned possibilities?
4013 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4014
4015 // Does it fit in a unsigned int?
4016 if (ResultVal.isIntN(IntSize)) {
4017 // Does it fit in a signed int?
4018 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4019 Ty = Context.IntTy;
4020 else if (AllowUnsigned)
4022 Width = IntSize;
4023 }
4024 }
4025
4026 // Are long/unsigned long possibilities?
4027 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4028 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4029
4030 // Does it fit in a unsigned long?
4031 if (ResultVal.isIntN(LongSize)) {
4032 // Does it fit in a signed long?
4033 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4034 Ty = Context.LongTy;
4035 else if (AllowUnsigned)
4037 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4038 // is compatible.
4039 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4040 const unsigned LongLongSize =
4042 Diag(Tok.getLocation(),
4044 ? Literal.isLong
4045 ? diag::warn_old_implicitly_unsigned_long_cxx
4046 : /*C++98 UB*/ diag::
4047 ext_old_implicitly_unsigned_long_cxx
4048 : diag::warn_old_implicitly_unsigned_long)
4049 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4050 : /*will be ill-formed*/ 1);
4052 }
4053 Width = LongSize;
4054 }
4055 }
4056
4057 // Check long long if needed.
4058 if (Ty.isNull() && !Literal.isSizeT) {
4059 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4060
4061 // Does it fit in a unsigned long long?
4062 if (ResultVal.isIntN(LongLongSize)) {
4063 // Does it fit in a signed long long?
4064 // To be compatible with MSVC, hex integer literals ending with the
4065 // LL or i64 suffix are always signed in Microsoft mode.
4066 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4067 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4068 Ty = Context.LongLongTy;
4069 else if (AllowUnsigned)
4071 Width = LongLongSize;
4072
4073 // 'long long' is a C99 or C++11 feature, whether the literal
4074 // explicitly specified 'long long' or we needed the extra width.
4075 if (getLangOpts().CPlusPlus)
4076 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4077 ? diag::warn_cxx98_compat_longlong
4078 : diag::ext_cxx11_longlong);
4079 else if (!getLangOpts().C99)
4080 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4081 }
4082 }
4083
4084 // If we still couldn't decide a type, we either have 'size_t' literal
4085 // that is out of range, or a decimal literal that does not fit in a
4086 // signed long long and has no U suffix.
4087 if (Ty.isNull()) {
4088 if (Literal.isSizeT)
4089 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4090 << Literal.isUnsigned;
4091 else
4092 Diag(Tok.getLocation(),
4093 diag::ext_integer_literal_too_large_for_signed);
4096 }
4097
4098 if (ResultVal.getBitWidth() != Width)
4099 ResultVal = ResultVal.trunc(Width);
4100 }
4101 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4102 }
4103
4104 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4105 if (Literal.isImaginary) {
4106 Res = new (Context) ImaginaryLiteral(Res,
4108
4109 // In C++, this is a GNU extension. In C, it's a C2y extension.
4110 unsigned DiagId;
4111 if (getLangOpts().CPlusPlus)
4112 DiagId = diag::ext_gnu_imaginary_constant;
4113 else if (getLangOpts().C2y)
4114 DiagId = diag::warn_c23_compat_imaginary_constant;
4115 else
4116 DiagId = diag::ext_c2y_imaginary_constant;
4117 Diag(Tok.getLocation(), DiagId);
4118 }
4119 return Res;
4120}
4121
4123 assert(E && "ActOnParenExpr() missing expr");
4124 QualType ExprTy = E->getType();
4125 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4126 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4127 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4128 return new (Context) ParenExpr(L, R, E);
4129}
4130
4133 SourceRange ArgRange) {
4134 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4135 // scalar or vector data type argument..."
4136 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4137 // type (C99 6.2.5p18) or void.
4138 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4139 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4140 << T << ArgRange;
4141 return true;
4142 }
4143
4144 assert((T->isVoidType() || !T->isIncompleteType()) &&
4145 "Scalar types should always be complete");
4146 return false;
4147}
4148
4151 SourceRange ArgRange) {
4152 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4153 if (!T->isVectorType() && !T->isSizelessVectorType())
4154 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4155 << ""
4156 << "__builtin_vectorelements" << T << ArgRange;
4157
4158 return false;
4159}
4160
4163 SourceRange ArgRange) {
4164 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4165 return true;
4166
4167 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4169 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4170 return true;
4171 }
4172
4173 return false;
4174}
4175
4178 SourceRange ArgRange,
4179 UnaryExprOrTypeTrait TraitKind) {
4180 // Invalid types must be hard errors for SFINAE in C++.
4181 if (S.LangOpts.CPlusPlus)
4182 return true;
4183
4184 // C99 6.5.3.4p1:
4185 if (T->isFunctionType() &&
4186 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4187 TraitKind == UETT_PreferredAlignOf)) {
4188 // sizeof(function)/alignof(function) is allowed as an extension.
4189 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4190 << getTraitSpelling(TraitKind) << ArgRange;
4191 return false;
4192 }
4193
4194 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4195 // this is an error (OpenCL v1.1 s6.3.k)
4196 if (T->isVoidType()) {
4197 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4198 : diag::ext_sizeof_alignof_void_type;
4199 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4200 return false;
4201 }
4202
4203 return true;
4204}
4205
4208 SourceRange ArgRange,
4209 UnaryExprOrTypeTrait TraitKind) {
4210 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4211 // runtime doesn't allow it.
4213 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4214 << T << (TraitKind == UETT_SizeOf)
4215 << ArgRange;
4216 return true;
4217 }
4218
4219 return false;
4220}
4221
4222/// Check whether E is a pointer from a decayed array type (the decayed
4223/// pointer type is equal to T) and emit a warning if it is.
4225 const Expr *E) {
4226 // Don't warn if the operation changed the type.
4227 if (T != E->getType())
4228 return;
4229
4230 // Now look for array decays.
4231 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4232 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4233 return;
4234
4235 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4236 << ICE->getType()
4237 << ICE->getSubExpr()->getType();
4238}
4239
4241 UnaryExprOrTypeTrait ExprKind) {
4242 QualType ExprTy = E->getType();
4243 assert(!ExprTy->isReferenceType());
4244
4245 bool IsUnevaluatedOperand =
4246 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4247 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4248 ExprKind == UETT_VecStep);
4249 if (IsUnevaluatedOperand) {
4251 if (Result.isInvalid())
4252 return true;
4253 E = Result.get();
4254 }
4255
4256 // The operand for sizeof and alignof is in an unevaluated expression context,
4257 // so side effects could result in unintended consequences.
4258 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4259 // used to build SFINAE gadgets.
4260 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4261 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4263 !E->getType()->isVariableArrayType() &&
4264 E->HasSideEffects(Context, false))
4265 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4266
4267 if (ExprKind == UETT_VecStep)
4268 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4269 E->getSourceRange());
4270
4271 if (ExprKind == UETT_VectorElements)
4272 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4273 E->getSourceRange());
4274
4275 // Explicitly list some types as extensions.
4276 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4277 E->getSourceRange(), ExprKind))
4278 return false;
4279
4280 // WebAssembly tables are always illegal operands to unary expressions and
4281 // type traits.
4282 if (Context.getTargetInfo().getTriple().isWasm() &&
4284 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4285 << getTraitSpelling(ExprKind);
4286 return true;
4287 }
4288
4289 // 'alignof' applied to an expression only requires the base element type of
4290 // the expression to be complete. 'sizeof' requires the expression's type to
4291 // be complete (and will attempt to complete it if it's an array of unknown
4292 // bound).
4293 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4296 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4297 getTraitSpelling(ExprKind), E->getSourceRange()))
4298 return true;
4299 } else {
4301 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4302 getTraitSpelling(ExprKind), E->getSourceRange()))
4303 return true;
4304 }
4305
4306 // Completing the expression's type may have changed it.
4307 ExprTy = E->getType();
4308 assert(!ExprTy->isReferenceType());
4309
4310 if (ExprTy->isFunctionType()) {
4311 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4312 << getTraitSpelling(ExprKind) << E->getSourceRange();
4313 return true;
4314 }
4315
4316 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4317 E->getSourceRange(), ExprKind))
4318 return true;
4319
4320 if (ExprKind == UETT_SizeOf) {
4321 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4322 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4323 QualType OType = PVD->getOriginalType();
4324 QualType Type = PVD->getType();
4325 if (Type->isPointerType() && OType->isArrayType()) {
4326 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4327 << Type << OType;
4328 Diag(PVD->getLocation(), diag::note_declared_at);
4329 }
4330 }
4331 }
4332
4333 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4334 // decays into a pointer and returns an unintended result. This is most
4335 // likely a typo for "sizeof(array) op x".
4336 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4337 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4338 BO->getLHS());
4339 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4340 BO->getRHS());
4341 }
4342 }
4343
4344 return false;
4345}
4346
4347static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4348 // Cannot know anything else if the expression is dependent.
4349 if (E->isTypeDependent())
4350 return false;
4351
4352 if (E->getObjectKind() == OK_BitField) {
4353 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4354 << 1 << E->getSourceRange();
4355 return true;
4356 }
4357
4358 ValueDecl *D = nullptr;
4359 Expr *Inner = E->IgnoreParens();
4360 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4361 D = DRE->getDecl();
4362 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4363 D = ME->getMemberDecl();
4364 }
4365
4366 // If it's a field, require the containing struct to have a
4367 // complete definition so that we can compute the layout.
4368 //
4369 // This can happen in C++11 onwards, either by naming the member
4370 // in a way that is not transformed into a member access expression
4371 // (in an unevaluated operand, for instance), or by naming the member
4372 // in a trailing-return-type.
4373 //
4374 // For the record, since __alignof__ on expressions is a GCC
4375 // extension, GCC seems to permit this but always gives the
4376 // nonsensical answer 0.
4377 //
4378 // We don't really need the layout here --- we could instead just
4379 // directly check for all the appropriate alignment-lowing
4380 // attributes --- but that would require duplicating a lot of
4381 // logic that just isn't worth duplicating for such a marginal
4382 // use-case.
4383 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4384 // Fast path this check, since we at least know the record has a
4385 // definition if we can find a member of it.
4386 if (!FD->getParent()->isCompleteDefinition()) {
4387 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4388 << E->getSourceRange();
4389 return true;
4390 }
4391
4392 // Otherwise, if it's a field, and the field doesn't have
4393 // reference type, then it must have a complete type (or be a
4394 // flexible array member, which we explicitly want to
4395 // white-list anyway), which makes the following checks trivial.
4396 if (!FD->getType()->isReferenceType())
4397 return false;
4398 }
4399
4400 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4401}
4402
4404 E = E->IgnoreParens();
4405
4406 // Cannot know anything else if the expression is dependent.
4407 if (E->isTypeDependent())
4408 return false;
4409
4410 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4411}
4412
4414 CapturingScopeInfo *CSI) {
4415 assert(T->isVariablyModifiedType());
4416 assert(CSI != nullptr);
4417
4418 // We're going to walk down into the type and look for VLA expressions.
4419 do {
4420 const Type *Ty = T.getTypePtr();
4421 switch (Ty->getTypeClass()) {
4422#define TYPE(Class, Base)
4423#define ABSTRACT_TYPE(Class, Base)
4424#define NON_CANONICAL_TYPE(Class, Base)
4425#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4426#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4427#include "clang/AST/TypeNodes.inc"
4428 T = QualType();
4429 break;
4430 // These types are never variably-modified.
4431 case Type::Builtin:
4432 case Type::Complex:
4433 case Type::Vector:
4434 case Type::ExtVector:
4435 case Type::ConstantMatrix:
4436 case Type::Record:
4437 case Type::Enum:
4438 case Type::TemplateSpecialization:
4439 case Type::ObjCObject:
4440 case Type::ObjCInterface:
4441 case Type::ObjCObjectPointer:
4442 case Type::ObjCTypeParam:
4443 case Type::Pipe:
4444 case Type::BitInt:
4445 llvm_unreachable("type class is never variably-modified!");
4446 case Type::Elaborated:
4447 T = cast<ElaboratedType>(Ty)->getNamedType();
4448 break;
4449 case Type::Adjusted:
4450 T = cast<AdjustedType>(Ty)->getOriginalType();
4451 break;
4452 case Type::Decayed:
4453 T = cast<DecayedType>(Ty)->getPointeeType();
4454 break;
4455 case Type::ArrayParameter:
4456 T = cast<ArrayParameterType>(Ty)->getElementType();
4457 break;
4458 case Type::Pointer:
4459 T = cast<PointerType>(Ty)->getPointeeType();
4460 break;
4461 case Type::BlockPointer:
4462 T = cast<BlockPointerType>(Ty)->getPointeeType();
4463 break;
4464 case Type::LValueReference:
4465 case Type::RValueReference:
4466 T = cast<ReferenceType>(Ty)->getPointeeType();
4467 break;
4468 case Type::MemberPointer:
4469 T = cast<MemberPointerType>(Ty)->getPointeeType();
4470 break;
4471 case Type::ConstantArray:
4472 case Type::IncompleteArray:
4473 // Losing element qualification here is fine.
4474 T = cast<ArrayType>(Ty)->getElementType();
4475 break;
4476 case Type::VariableArray: {
4477 // Losing element qualification here is fine.
4478 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4479
4480 // Unknown size indication requires no size computation.
4481 // Otherwise, evaluate and record it.
4482 auto Size = VAT->getSizeExpr();
4483 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4484 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4485 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4486
4487 T = VAT->getElementType();
4488 break;
4489 }
4490 case Type::FunctionProto:
4491 case Type::FunctionNoProto:
4492 T = cast<FunctionType>(Ty)->getReturnType();
4493 break;
4494 case Type::Paren:
4495 case Type::TypeOf:
4496 case Type::UnaryTransform:
4497 case Type::Attributed:
4498 case Type::BTFTagAttributed:
4499 case Type::HLSLAttributedResource:
4500 case Type::SubstTemplateTypeParm:
4501 case Type::MacroQualified:
4502 case Type::CountAttributed:
4503 // Keep walking after single level desugaring.
4504 T = T.getSingleStepDesugaredType(Context);
4505 break;
4506 case Type::Typedef:
4507 T = cast<TypedefType>(Ty)->desugar();
4508 break;
4509 case Type::Decltype:
4510 T = cast<DecltypeType>(Ty)->desugar();
4511 break;
4512 case Type::PackIndexing:
4513 T = cast<PackIndexingType>(Ty)->desugar();
4514 break;
4515 case Type::Using:
4516 T = cast<UsingType>(Ty)->desugar();
4517 break;
4518 case Type::Auto:
4519 case Type::DeducedTemplateSpecialization:
4520 T = cast<DeducedType>(Ty)->getDeducedType();
4521 break;
4522 case Type::TypeOfExpr:
4523 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4524 break;
4525 case Type::Atomic:
4526 T = cast<AtomicType>(Ty)->getValueType();
4527 break;
4528 }
4529 } while (!T.isNull() && T->isVariablyModifiedType());
4530}
4531
4533 SourceLocation OpLoc,
4534 SourceRange ExprRange,
4535 UnaryExprOrTypeTrait ExprKind,
4536 StringRef KWName) {
4537 if (ExprType->isDependentType())
4538 return false;
4539
4540 // C++ [expr.sizeof]p2:
4541 // When applied to a reference or a reference type, the result
4542 // is the size of the referenced type.
4543 // C++11 [expr.alignof]p3:
4544 // When alignof is applied to a reference type, the result
4545 // shall be the alignment of the referenced type.
4546 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4547 ExprType = Ref->getPointeeType();
4548
4549 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4550 // When alignof or _Alignof is applied to an array type, the result
4551 // is the alignment of the element type.
4552 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4553 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4554 // If the trait is 'alignof' in C before C2y, the ability to apply the
4555 // trait to an incomplete array is an extension.
4556 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4557 ExprType->isIncompleteArrayType())
4558 Diag(OpLoc, getLangOpts().C2y
4559 ? diag::warn_c2y_compat_alignof_incomplete_array
4560 : diag::ext_c2y_alignof_incomplete_array);
4561 ExprType = Context.getBaseElementType(ExprType);
4562 }
4563
4564 if (ExprKind == UETT_VecStep)
4565 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4566
4567 if (ExprKind == UETT_VectorElements)
4568 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4569 ExprRange);
4570
4571 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4572 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4573 ExprRange);
4574
4575 // Explicitly list some types as extensions.
4576 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4577 ExprKind))
4578 return false;
4579
4581 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4582 KWName, ExprRange))
4583 return true;
4584
4585 if (ExprType->isFunctionType()) {
4586 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4587 return true;
4588 }
4589
4590 // WebAssembly tables are always illegal operands to unary expressions and
4591 // type traits.
4592 if (Context.getTargetInfo().getTriple().isWasm() &&
4593 ExprType->isWebAssemblyTableType()) {
4594 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4595 << getTraitSpelling(ExprKind);
4596 return true;
4597 }
4598
4599 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4600 ExprKind))
4601 return true;
4602
4603 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4604 if (auto *TT = ExprType->getAs<TypedefType>()) {
4605 for (auto I = FunctionScopes.rbegin(),
4606 E = std::prev(FunctionScopes.rend());
4607 I != E; ++I) {
4608 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4609 if (CSI == nullptr)
4610 break;
4611 DeclContext *DC = nullptr;
4612 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4613 DC = LSI->CallOperator;
4614 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4615 DC = CRSI->TheCapturedDecl;
4616 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4617 DC = BSI->TheDecl;
4618 if (DC) {
4619 if (DC->containsDecl(TT->getDecl()))
4620 break;
4621 captureVariablyModifiedType(Context, ExprType, CSI);
4622 }
4623 }
4624 }
4625 }
4626
4627 return false;
4628}
4629
4631 SourceLocation OpLoc,
4632 UnaryExprOrTypeTrait ExprKind,
4633 SourceRange R) {
4634 if (!TInfo)
4635 return ExprError();
4636
4637 QualType T = TInfo->getType();
4638
4639 if (!T->isDependentType() &&
4640 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4641 getTraitSpelling(ExprKind)))
4642 return ExprError();
4643
4644 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4645 // properly deal with VLAs in nested calls of sizeof and typeof.
4646 if (currentEvaluationContext().isUnevaluated() &&
4647 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4648 ExprKind == UETT_SizeOf && TInfo->getType()->isVariablyModifiedType())
4649 TInfo = TransformToPotentiallyEvaluated(TInfo);
4650
4651 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4652 return new (Context) UnaryExprOrTypeTraitExpr(
4653 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4654}
4655
4658 UnaryExprOrTypeTrait ExprKind) {
4660 if (PE.isInvalid())
4661 return ExprError();
4662
4663 E = PE.get();
4664
4665 // Verify that the operand is valid.
4666 bool isInvalid = false;
4667 if (E->isTypeDependent()) {
4668 // Delay type-checking for type-dependent expressions.
4669 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4670 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4671 } else if (ExprKind == UETT_VecStep) {
4673 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4674 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4675 isInvalid = true;
4676 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4677 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4678 isInvalid = true;
4679 } else if (ExprKind == UETT_VectorElements) {
4680 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements);
4681 } else {
4683 }
4684
4685 if (isInvalid)
4686 return ExprError();
4687
4688 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4690 if (PE.isInvalid()) return ExprError();
4691 E = PE.get();
4692 }
4693
4694 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4695 return new (Context) UnaryExprOrTypeTraitExpr(
4696 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4697}
4698
4701 UnaryExprOrTypeTrait ExprKind, bool IsType,
4702 void *TyOrEx, SourceRange ArgRange) {
4703 // If error parsing type, ignore.
4704 if (!TyOrEx) return ExprError();
4705
4706 if (IsType) {
4707 TypeSourceInfo *TInfo;
4708 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4709 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4710 }
4711
4712 Expr *ArgEx = (Expr *)TyOrEx;
4713 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4714 return Result;
4715}
4716
4718 SourceLocation OpLoc, SourceRange R) {
4719 if (!TInfo)
4720 return true;
4721 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4722 UETT_AlignOf, KWName);
4723}
4724
4726 SourceLocation OpLoc, SourceRange R) {
4727 TypeSourceInfo *TInfo;
4729 &TInfo);
4730 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4731}
4732
4734 bool IsReal) {
4735 if (V.get()->isTypeDependent())
4736 return S.Context.DependentTy;
4737
4738 // _Real and _Imag are only l-values for normal l-values.
4739 if (V.get()->getObjectKind() != OK_Ordinary) {
4740 V = S.DefaultLvalueConversion(V.get());
4741 if (V.isInvalid())
4742 return QualType();
4743 }
4744
4745 // These operators return the element type of a complex type.
4746 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4747 return CT->getElementType();
4748
4749 // Otherwise they pass through real integer and floating point types here.
4750 if (V.get()->getType()->isArithmeticType())
4751 return V.get()->getType();
4752
4753 // Test for placeholders.
4754 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4755 if (PR.isInvalid()) return QualType();
4756 if (PR.get() != V.get()) {
4757 V = PR;
4758 return CheckRealImagOperand(S, V, Loc, IsReal);
4759 }
4760
4761 // Reject anything else.
4762 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4763 << (IsReal ? "__real" : "__imag");
4764 return QualType();
4765}
4766
4767
4768
4771 tok::TokenKind Kind, Expr *Input) {
4773 switch (Kind) {
4774 default: llvm_unreachable("Unknown unary op!");
4775 case tok::plusplus: Opc = UO_PostInc; break;
4776 case tok::minusminus: Opc = UO_PostDec; break;
4777 }
4778
4779 // Since this might is a postfix expression, get rid of ParenListExprs.
4781 if (Result.isInvalid()) return ExprError();
4782 Input = Result.get();
4783
4784 return BuildUnaryOp(S, OpLoc, Opc, Input);
4785}
4786
4787/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4788///
4789/// \return true on error
4791 SourceLocation opLoc,
4792 Expr *op) {
4793 assert(op->getType()->isObjCObjectPointerType());
4795 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4796 return false;
4797
4798 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4800 << op->getSourceRange();
4801 return true;
4802}
4803
4805 auto *BaseNoParens = Base->IgnoreParens();
4806 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4807 return MSProp->getPropertyDecl()->getType()->isArrayType();
4808 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4809}
4810
4811// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4812// Typically this is DependentTy, but can sometimes be more precise.
4813//
4814// There are cases when we could determine a non-dependent type:
4815// - LHS and RHS may have non-dependent types despite being type-dependent
4816// (e.g. unbounded array static members of the current instantiation)
4817// - one may be a dependent-sized array with known element type
4818// - one may be a dependent-typed valid index (enum in current instantiation)
4819//
4820// We *always* return a dependent type, in such cases it is DependentTy.
4821// This avoids creating type-dependent expressions with non-dependent types.
4822// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4824 const ASTContext &Ctx) {
4825 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4826 QualType LTy = LHS->getType(), RTy = RHS->getType();
4828 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4829 if (const PointerType *PT = LTy->getAs<PointerType>())
4830 Result = PT->getPointeeType();
4831 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4832 Result = AT->getElementType();
4833 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4834 if (const PointerType *PT = RTy->getAs<PointerType>())
4835 Result = PT->getPointeeType();
4836 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4837 Result = AT->getElementType();
4838 }
4839 // Ensure we return a dependent type.
4840 return Result->isDependentType() ? Result : Ctx.DependentTy;
4841}
4842
4844 SourceLocation lbLoc,
4845 MultiExprArg ArgExprs,
4846 SourceLocation rbLoc) {
4847
4848 if (base && !base->getType().isNull() &&
4849 base->hasPlaceholderType(BuiltinType::ArraySection)) {
4850 auto *AS = cast<ArraySectionExpr>(base);
4851 if (AS->isOMPArraySection())
4853 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
4854 /*Length*/ nullptr,
4855 /*Stride=*/nullptr, rbLoc);
4856
4857 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
4858 SourceLocation(), /*Length*/ nullptr,
4859 rbLoc);
4860 }
4861
4862 // Since this might be a postfix expression, get rid of ParenListExprs.
4863 if (isa<ParenListExpr>(base)) {
4865 if (result.isInvalid())
4866 return ExprError();
4867 base = result.get();
4868 }
4869
4870 // Check if base and idx form a MatrixSubscriptExpr.
4871 //
4872 // Helper to check for comma expressions, which are not allowed as indices for
4873 // matrix subscript expressions.
4874 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4875 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4876 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4877 << SourceRange(base->getBeginLoc(), rbLoc);
4878 return true;
4879 }
4880 return false;
4881 };
4882 // The matrix subscript operator ([][])is considered a single operator.
4883 // Separating the index expressions by parenthesis is not allowed.
4884 if (base && !base->getType().isNull() &&
4885 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4886 !isa<MatrixSubscriptExpr>(base)) {
4887 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4888 << SourceRange(base->getBeginLoc(), rbLoc);
4889 return ExprError();
4890 }
4891 // If the base is a MatrixSubscriptExpr, try to create a new
4892 // MatrixSubscriptExpr.
4893 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4894 if (matSubscriptE) {
4895 assert(ArgExprs.size() == 1);
4896 if (CheckAndReportCommaError(ArgExprs.front()))
4897 return ExprError();
4898
4899 assert(matSubscriptE->isIncomplete() &&
4900 "base has to be an incomplete matrix subscript");
4901 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4902 matSubscriptE->getRowIdx(),
4903 ArgExprs.front(), rbLoc);
4904 }
4905 if (base->getType()->isWebAssemblyTableType()) {
4906 Diag(base->getExprLoc(), diag::err_wasm_table_art)
4907 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
4908 return ExprError();
4909 }
4910
4911 CheckInvalidBuiltinCountedByRef(base, ArraySubscriptKind);
4912
4913 // Handle any non-overload placeholder types in the base and index
4914 // expressions. We can't handle overloads here because the other
4915 // operand might be an overloadable type, in which case the overload
4916 // resolution for the operator overload should get the first crack
4917 // at the overload.
4918 bool IsMSPropertySubscript = false;
4919 if (base->getType()->isNonOverloadPlaceholderType()) {
4920 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4921 if (!IsMSPropertySubscript) {
4922 ExprResult result = CheckPlaceholderExpr(base);
4923 if (result.isInvalid())
4924 return ExprError();
4925 base = result.get();
4926 }
4927 }
4928
4929 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4930 if (base->getType()->isMatrixType()) {
4931 assert(ArgExprs.size() == 1);
4932 if (CheckAndReportCommaError(ArgExprs.front()))
4933 return ExprError();
4934
4935 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4936 rbLoc);
4937 }
4938
4939 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4940 Expr *idx = ArgExprs[0];
4941 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4942 (isa<CXXOperatorCallExpr>(idx) &&
4943 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4944 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4945 << SourceRange(base->getBeginLoc(), rbLoc);
4946 }
4947 }
4948
4949 if (ArgExprs.size() == 1 &&
4950 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4951 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4952 if (result.isInvalid())
4953 return ExprError();
4954 ArgExprs[0] = result.get();
4955 } else {
4956 if (CheckArgsForPlaceholders(ArgExprs))
4957 return ExprError();
4958 }
4959
4960 // Build an unanalyzed expression if either operand is type-dependent.
4961 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4962 (base->isTypeDependent() ||
4964 !isa<PackExpansionExpr>(ArgExprs[0])) {
4965 return new (Context) ArraySubscriptExpr(
4966 base, ArgExprs.front(),
4967 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4968 VK_LValue, OK_Ordinary, rbLoc);
4969 }
4970
4971 // MSDN, property (C++)
4972 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4973 // This attribute can also be used in the declaration of an empty array in a
4974 // class or structure definition. For example:
4975 // __declspec(property(get=GetX, put=PutX)) int x[];
4976 // The above statement indicates that x[] can be used with one or more array
4977 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4978 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4979 if (IsMSPropertySubscript) {
4980 assert(ArgExprs.size() == 1);
4981 // Build MS property subscript expression if base is MS property reference
4982 // or MS property subscript.
4983 return new (Context)
4984 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4985 VK_LValue, OK_Ordinary, rbLoc);
4986 }
4987
4988 // Use C++ overloaded-operator rules if either operand has record
4989 // type. The spec says to do this if either type is *overloadable*,
4990 // but enum types can't declare subscript operators or conversion
4991 // operators, so there's nothing interesting for overload resolution
4992 // to do if there aren't any record types involved.
4993 //
4994 // ObjC pointers have their own subscripting logic that is not tied
4995 // to overload resolution and so should not take this path.
4996 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4997 ((base->getType()->isRecordType() ||
4998 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
4999 ArgExprs[0]->getType()->isRecordType())))) {
5000 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5001 }
5002
5003 ExprResult Res =
5004 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5005
5006 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5007 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5008
5009 return Res;
5010}
5011
5014 InitializationKind Kind =
5016 InitializationSequence InitSeq(*this, Entity, Kind, E);
5017 return InitSeq.Perform(*this, Entity, Kind, E);
5018}
5019
5021 Expr *ColumnIdx,
5022 SourceLocation RBLoc) {
5024 if (BaseR.isInvalid())
5025 return BaseR;
5026 Base = BaseR.get();
5027
5028 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5029 if (RowR.isInvalid())
5030 return RowR;
5031 RowIdx = RowR.get();
5032
5033 if (!ColumnIdx)
5034 return new (Context) MatrixSubscriptExpr(
5035 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5036
5037 // Build an unanalyzed expression if any of the operands is type-dependent.
5038 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5039 ColumnIdx->isTypeDependent())
5040 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5041 Context.DependentTy, RBLoc);
5042
5043 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5044 if (ColumnR.isInvalid())
5045 return ColumnR;
5046 ColumnIdx = ColumnR.get();
5047
5048 // Check that IndexExpr is an integer expression. If it is a constant
5049 // expression, check that it is less than Dim (= the number of elements in the
5050 // corresponding dimension).
5051 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5052 bool IsColumnIdx) -> Expr * {
5053 if (!IndexExpr->getType()->isIntegerType() &&
5054 !IndexExpr->isTypeDependent()) {
5055 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5056 << IsColumnIdx;
5057 return nullptr;
5058 }
5059
5060 if (std::optional<llvm::APSInt> Idx =
5061 IndexExpr->getIntegerConstantExpr(Context)) {
5062 if ((*Idx < 0 || *Idx >= Dim)) {
5063 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5064 << IsColumnIdx << Dim;
5065 return nullptr;
5066 }
5067 }
5068
5069 ExprResult ConvExpr = IndexExpr;
5070 assert(!ConvExpr.isInvalid() &&
5071 "should be able to convert any integer type to size type");
5072 return ConvExpr.get();
5073 };
5074
5075 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5076 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5077 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5078 if (!RowIdx || !ColumnIdx)
5079 return ExprError();
5080
5081 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5082 MTy->getElementType(), RBLoc);
5083}
5084
5085void Sema::CheckAddressOfNoDeref(const Expr *E) {
5086 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5087 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5088
5089 // For expressions like `&(*s).b`, the base is recorded and what should be
5090 // checked.
5091 const MemberExpr *Member = nullptr;
5092 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5093 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5094
5095 LastRecord.PossibleDerefs.erase(StrippedExpr);
5096}
5097
5098void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5100 return;
5101
5102 QualType ResultTy = E->getType();
5103 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5104
5105 // Bail if the element is an array since it is not memory access.
5106 if (isa<ArrayType>(ResultTy))
5107 return;
5108
5109 if (ResultTy->hasAttr(attr::NoDeref)) {
5110 LastRecord.PossibleDerefs.insert(E);
5111 return;
5112 }
5113
5114 // Check if the base type is a pointer to a member access of a struct
5115 // marked with noderef.
5116 const Expr *Base = E->getBase();
5117 QualType BaseTy = Base->getType();
5118 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5119 // Not a pointer access
5120 return;
5121
5122 const MemberExpr *Member = nullptr;
5123 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5124 Member->isArrow())
5125 Base = Member->getBase();
5126
5127 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5128 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5129 LastRecord.PossibleDerefs.insert(E);
5130 }
5131}
5132
5135 Expr *Idx, SourceLocation RLoc) {
5136 Expr *LHSExp = Base;
5137 Expr *RHSExp = Idx;
5138
5141
5142 // Per C++ core issue 1213, the result is an xvalue if either operand is
5143 // a non-lvalue array, and an lvalue otherwise.
5144 if (getLangOpts().CPlusPlus11) {
5145 for (auto *Op : {LHSExp, RHSExp}) {
5146 Op = Op->IgnoreImplicit();
5147 if (Op->getType()->isArrayType() && !Op->isLValue())
5148 VK = VK_XValue;
5149 }
5150 }
5151
5152 // Perform default conversions.
5153 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5155 if (Result.isInvalid())
5156 return ExprError();
5157 LHSExp = Result.get();
5158 }
5160 if (Result.isInvalid())
5161 return ExprError();
5162 RHSExp = Result.get();
5163
5164 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5165
5166 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5167 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5168 // in the subscript position. As a result, we need to derive the array base
5169 // and index from the expression types.
5170 Expr *BaseExpr, *IndexExpr;
5171 QualType ResultType;
5172 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5173 BaseExpr = LHSExp;
5174 IndexExpr = RHSExp;
5175 ResultType =
5177 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5178 BaseExpr = LHSExp;
5179 IndexExpr = RHSExp;
5180 ResultType = PTy->getPointeeType();
5181 } else if (const ObjCObjectPointerType *PTy =
5182 LHSTy->getAs<ObjCObjectPointerType>()) {
5183 BaseExpr = LHSExp;
5184 IndexExpr = RHSExp;
5185
5186 // Use custom logic if this should be the pseudo-object subscript
5187 // expression.
5189 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5190 nullptr, nullptr);
5191
5192 ResultType = PTy->getPointeeType();
5193 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5194 // Handle the uncommon case of "123[Ptr]".
5195 BaseExpr = RHSExp;
5196 IndexExpr = LHSExp;
5197 ResultType = PTy->getPointeeType();
5198 } else if (const ObjCObjectPointerType *PTy =
5199 RHSTy->getAs<ObjCObjectPointerType>()) {
5200 // Handle the uncommon case of "123[Ptr]".
5201 BaseExpr = RHSExp;
5202 IndexExpr = LHSExp;
5203 ResultType = PTy->getPointeeType();
5205 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5206 << ResultType << BaseExpr->getSourceRange();
5207 return ExprError();
5208 }
5209 } else if (LHSTy->isSubscriptableVectorType()) {
5210 if (LHSTy->isBuiltinType() &&
5211 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5212 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5213 if (BTy->isSVEBool())
5214 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5215 << LHSExp->getSourceRange()
5216 << RHSExp->getSourceRange());
5217 ResultType = BTy->getSveEltType(Context);
5218 } else {
5219 const VectorType *VTy = LHSTy->getAs<VectorType>();
5220 ResultType = VTy->getElementType();
5221 }
5222 BaseExpr = LHSExp; // vectors: V[123]
5223 IndexExpr = RHSExp;
5224 // We apply C++ DR1213 to vector subscripting too.
5225 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5226 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5227 if (Materialized.isInvalid())
5228 return ExprError();
5229 LHSExp = Materialized.get();
5230 }
5231 VK = LHSExp->getValueKind();
5232 if (VK != VK_PRValue)
5233 OK = OK_VectorComponent;
5234
5235 QualType BaseType = BaseExpr->getType();
5236 Qualifiers BaseQuals = BaseType.getQualifiers();
5237 Qualifiers MemberQuals = ResultType.getQualifiers();
5238 Qualifiers Combined = BaseQuals + MemberQuals;
5239 if (Combined != MemberQuals)
5240 ResultType = Context.getQualifiedType(ResultType, Combined);
5241 } else if (LHSTy->isArrayType()) {
5242 // If we see an array that wasn't promoted by
5243 // DefaultFunctionArrayLvalueConversion, it must be an array that
5244 // wasn't promoted because of the C90 rule that doesn't
5245 // allow promoting non-lvalue arrays. Warn, then
5246 // force the promotion here.
5247 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5248 << LHSExp->getSourceRange();
5249 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5250 CK_ArrayToPointerDecay).get();
5251 LHSTy = LHSExp->getType();
5252
5253 BaseExpr = LHSExp;
5254 IndexExpr = RHSExp;
5255 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5256 } else if (RHSTy->isArrayType()) {
5257 // Same as previous, except for 123[f().a] case
5258 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5259 << RHSExp->getSourceRange();
5260 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5261 CK_ArrayToPointerDecay).get();
5262 RHSTy = RHSExp->getType();
5263
5264 BaseExpr = RHSExp;
5265 IndexExpr = LHSExp;
5266 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5267 } else {
5268 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5269 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5270 }
5271 // C99 6.5.2.1p1
5272 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5273 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5274 << IndexExpr->getSourceRange());
5275
5276 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5277 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5278 !IndexExpr->isTypeDependent()) {
5279 std::optional<llvm::APSInt> IntegerContantExpr =
5281 if (!IntegerContantExpr.has_value() ||
5282 IntegerContantExpr.value().isNegative())
5283 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5284 }
5285
5286 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5287 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5288 // type. Note that Functions are not objects, and that (in C99 parlance)
5289 // incomplete types are not object types.
5290 if (ResultType->isFunctionType()) {
5291 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5292 << ResultType << BaseExpr->getSourceRange();
5293 return ExprError();
5294 }
5295
5296 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5297 // GNU extension: subscripting on pointer to void
5298 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5299 << BaseExpr->getSourceRange();
5300
5301 // C forbids expressions of unqualified void type from being l-values.
5302 // See IsCForbiddenLValueType.
5303 if (!ResultType.hasQualifiers())
5304 VK = VK_PRValue;
5305 } else if (!ResultType->isDependentType() &&
5306 !ResultType.isWebAssemblyReferenceType() &&
5308 LLoc, ResultType,
5309 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5310 return ExprError();
5311
5312 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5313 !ResultType.isCForbiddenLValueType());
5314
5316 FunctionScopes.size() > 1) {
5317 if (auto *TT =
5318 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5319 for (auto I = FunctionScopes.rbegin(),
5320 E = std::prev(FunctionScopes.rend());
5321 I != E; ++I) {
5322 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5323 if (CSI == nullptr)
5324 break;
5325 DeclContext *DC = nullptr;
5326 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5327 DC = LSI->CallOperator;
5328 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5329 DC = CRSI->TheCapturedDecl;
5330 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5331 DC = BSI->TheDecl;
5332 if (DC) {
5333 if (DC->containsDecl(TT->getDecl()))
5334 break;
5336 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5337 }
5338 }
5339 }
5340 }
5341
5342 return new (Context)
5343 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5344}
5345
5347 ParmVarDecl *Param, Expr *RewrittenInit,
5348 bool SkipImmediateInvocations) {
5349 if (Param->hasUnparsedDefaultArg()) {
5350 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5351 // If we've already cleared out the location for the default argument,
5352 // that means we're parsing it right now.
5353 if (!UnparsedDefaultArgLocs.count(Param)) {
5354 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5355 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5356 Param->setInvalidDecl();
5357 return true;
5358 }
5359
5360 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5361 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5363 diag::note_default_argument_declared_here);
5364 return true;
5365 }
5366
5367 if (Param->hasUninstantiatedDefaultArg()) {
5368 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5369 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5370 return true;
5371 }
5372
5373 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5374 assert(Init && "default argument but no initializer?");
5375
5376 // If the default expression creates temporaries, we need to
5377 // push them to the current stack of expression temporaries so they'll
5378 // be properly destroyed.
5379 // FIXME: We should really be rebuilding the default argument with new
5380 // bound temporaries; see the comment in PR5810.
5381 // We don't need to do that with block decls, though, because
5382 // blocks in default argument expression can never capture anything.
5383 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5384 // Set the "needs cleanups" bit regardless of whether there are
5385 // any explicit objects.
5386 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5387 // Append all the objects to the cleanup list. Right now, this
5388 // should always be a no-op, because blocks in default argument
5389 // expressions should never be able to capture anything.
5390 assert(!InitWithCleanup->getNumObjects() &&
5391 "default argument expression has capturing blocks?");
5392 }
5393 // C++ [expr.const]p15.1:
5394 // An expression or conversion is in an immediate function context if it is
5395 // potentially evaluated and [...] its innermost enclosing non-block scope
5396 // is a function parameter scope of an immediate function.
5398 *this,
5402 Param);
5403 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5404 SkipImmediateInvocations;
5405 runWithSufficientStackSpace(CallLoc, [&] {
5406 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5407 });
5408 return false;
5409}
5410
5413 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {
5414 ShouldVisitImplicitCode = true;
5415 }
5416
5417 bool HasImmediateCalls = false;
5418
5419 bool VisitCallExpr(CallExpr *E) override {
5420 if (const FunctionDecl *FD = E->getDirectCallee())
5421 HasImmediateCalls |= FD->isImmediateFunction();
5423 }
5424
5426 if (const FunctionDecl *FD = E->getConstructor())
5427 HasImmediateCalls |= FD->isImmediateFunction();
5429 }
5430
5431 // SourceLocExpr are not immediate invocations
5432 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5433 // need to be rebuilt so that they refer to the correct SourceLocation and
5434 // DeclContext.
5436 HasImmediateCalls = true;
5438 }
5439
5440 // A nested lambda might have parameters with immediate invocations
5441 // in their default arguments.
5442 // The compound statement is not visited (as it does not constitute a
5443 // subexpression).
5444 // FIXME: We should consider visiting and transforming captures
5445 // with init expressions.
5446 bool VisitLambdaExpr(LambdaExpr *E) override {
5447 return VisitCXXMethodDecl(E->getCallOperator());
5448 }
5449
5451 return TraverseStmt(E->getExpr());
5452 }
5453
5455 return TraverseStmt(E->getExpr());
5456 }
5457};
5458
5460 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5462 : TreeTransform(SemaRef) {}
5463
5464 bool AlwaysRebuild() { return true; }
5465
5466 // Lambda can only have immediate invocations in the default
5467 // args of their parameters, which is transformed upon calling the closure.
5468 // The body is not a subexpression, so we have nothing to do.
5469 // FIXME: Immediate calls in capture initializers should be transformed.
5472
5473 // Make sure we don't rebuild the this pointer as it would
5474 // cause it to incorrectly point it to the outermost class
5475 // in the case of nested struct initialization.
5477
5478 // Rewrite to source location to refer to the context in which they are used.
5480 DeclContext *DC = E->getParentContext();
5481 if (DC == SemaRef.CurContext)
5482 return E;
5483
5484 // FIXME: During instantiation, because the rebuild of defaults arguments
5485 // is not always done in the context of the template instantiator,
5486 // we run the risk of producing a dependent source location
5487 // that would never be rebuilt.
5488 // This usually happens during overload resolution, or in contexts
5489 // where the value of the source location does not matter.
5490 // However, we should find a better way to deal with source location
5491 // of function templates.
5492 if (!SemaRef.CurrentInstantiationScope ||
5493 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5494 DC = SemaRef.CurContext;
5495
5496 return getDerived().RebuildSourceLocExpr(
5497 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5498 }
5499};
5500
5502 FunctionDecl *FD, ParmVarDecl *Param,
5503 Expr *Init) {
5504 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5505
5506 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5507 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5508 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5509 InitializationContext =
5511 if (!InitializationContext.has_value())
5512 InitializationContext.emplace(CallLoc, Param, CurContext);
5513
5514 if (!Init && !Param->hasUnparsedDefaultArg()) {
5515 // Mark that we are replacing a default argument first.
5516 // If we are instantiating a template we won't have to
5517 // retransform immediate calls.
5518 // C++ [expr.const]p15.1:
5519 // An expression or conversion is in an immediate function context if it
5520 // is potentially evaluated and [...] its innermost enclosing non-block
5521 // scope is a function parameter scope of an immediate function.
5523 *this,
5527 Param);
5528
5529 if (Param->hasUninstantiatedDefaultArg()) {
5530 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5531 return ExprError();
5532 }
5533 // CWG2631
5534 // An immediate invocation that is not evaluated where it appears is
5535 // evaluated and checked for whether it is a constant expression at the
5536 // point where the enclosing initializer is used in a function call.
5538 if (!NestedDefaultChecking)
5539 V.TraverseDecl(Param);
5540
5541 // Rewrite the call argument that was created from the corresponding
5542 // parameter's default argument.
5543 if (V.HasImmediateCalls ||
5544 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5545 if (V.HasImmediateCalls)
5546 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5547 CallLoc, Param, CurContext};
5548 // Pass down lifetime extending flag, and collect temporaries in
5549 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5553 ExprResult Res;
5554 runWithSufficientStackSpace(CallLoc, [&] {
5555 Res = Immediate.TransformInitializer(Param->getInit(),
5556 /*NotCopy=*/false);
5557 });
5558 if (Res.isInvalid())
5559 return ExprError();
5560 Res = ConvertParamDefaultArgument(Param, Res.get(),
5561 Res.get()->getBeginLoc());
5562 if (Res.isInvalid())
5563 return ExprError();
5564 Init = Res.get();
5565 }
5566 }
5567
5569 CallLoc, FD, Param, Init,
5570 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5571 return ExprError();
5572
5573 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5574 Init, InitializationContext->Context);
5575}
5576
5578 FieldDecl *Field) {
5579 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5580 return Pattern;
5581 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5582 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5584 ClassPattern->lookup(Field->getDeclName());
5585 auto Rng = llvm::make_filter_range(
5586 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5587 if (Rng.empty())
5588 return nullptr;
5589 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5590 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5591 // && "Duplicated instantiation pattern for field decl");
5592 return cast<FieldDecl>(*Rng.begin());
5593}
5594
5596 assert(Field->hasInClassInitializer());
5597
5598 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5599
5600 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5601
5602 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5603 InitializationContext =
5605 if (!InitializationContext.has_value())
5606 InitializationContext.emplace(Loc, Field, CurContext);
5607
5608 Expr *Init = nullptr;
5609
5610 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5611 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5614
5615 if (!Field->getInClassInitializer()) {
5616 // Maybe we haven't instantiated the in-class initializer. Go check the
5617 // pattern FieldDecl to see if it has one.
5618 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5619 FieldDecl *Pattern =
5621 assert(Pattern && "We must have set the Pattern!");
5622 if (!Pattern->hasInClassInitializer() ||
5623 InstantiateInClassInitializer(Loc, Field, Pattern,
5625 Field->setInvalidDecl();
5626 return ExprError();
5627 }
5628 }
5629 }
5630
5631 // CWG2631
5632 // An immediate invocation that is not evaluated where it appears is
5633 // evaluated and checked for whether it is a constant expression at the
5634 // point where the enclosing initializer is used in a [...] a constructor
5635 // definition, or an aggregate initialization.
5637 if (!NestedDefaultChecking)
5638 V.TraverseDecl(Field);
5639
5640 // CWG1815
5641 // Support lifetime extension of temporary created by aggregate
5642 // initialization using a default member initializer. We should rebuild
5643 // the initializer in a lifetime extension context if the initializer
5644 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5645 // extension code recurses into the default initializer and does lifetime
5646 // extension when warranted.
5647 bool ContainsAnyTemporaries =
5648 isa_and_present<ExprWithCleanups>(Field->getInClassInitializer());
5649 if (Field->getInClassInitializer() &&
5650 !Field->getInClassInitializer()->containsErrors() &&
5651 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5652 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5653 CurContext};
5654 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5655 NestedDefaultChecking;
5656 // Pass down lifetime extending flag, and collect temporaries in
5657 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5661 ExprResult Res;
5663 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5664 /*CXXDirectInit=*/false);
5665 });
5666 if (!Res.isInvalid())
5667 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5668 if (Res.isInvalid()) {
5669 Field->setInvalidDecl();
5670 return ExprError();
5671 }
5672 Init = Res.get();
5673 }
5674
5675 if (Field->getInClassInitializer()) {
5676 Expr *E = Init ? Init : Field->getInClassInitializer();
5677 if (!NestedDefaultChecking)
5679 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5680 });
5683 // C++11 [class.base.init]p7:
5684 // The initialization of each base and member constitutes a
5685 // full-expression.
5686 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5687 if (Res.isInvalid()) {
5688 Field->setInvalidDecl();
5689 return ExprError();
5690 }
5691 Init = Res.get();
5692
5693 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5694 Field, InitializationContext->Context,
5695 Init);
5696 }
5697
5698 // DR1351:
5699 // If the brace-or-equal-initializer of a non-static data member
5700 // invokes a defaulted default constructor of its class or of an
5701 // enclosing class in a potentially evaluated subexpression, the
5702 // program is ill-formed.
5703 //
5704 // This resolution is unworkable: the exception specification of the
5705 // default constructor can be needed in an unevaluated context, in
5706 // particular, in the operand of a noexcept-expression, and we can be
5707 // unable to compute an exception specification for an enclosed class.
5708 //
5709 // Any attempt to resolve the exception specification of a defaulted default
5710 // constructor before the initializer is lexically complete will ultimately
5711 // come here at which point we can diagnose it.
5712 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5713 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5714 << OutermostClass << Field;
5715 Diag(Field->getEndLoc(),
5716 diag::note_default_member_initializer_not_yet_parsed);
5717 // Recover by marking the field invalid, unless we're in a SFINAE context.
5718 if (!isSFINAEContext())
5719 Field->setInvalidDecl();
5720 return ExprError();
5721}
5722
5725 Expr *Fn) {
5726 if (Proto && Proto->isVariadic()) {
5727 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5728 return VariadicConstructor;
5729 else if (Fn && Fn->getType()->isBlockPointerType())
5730 return VariadicBlock;
5731 else if (FDecl) {
5732 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5733 if (Method->isInstance())
5734 return VariadicMethod;
5735 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5736 return VariadicMethod;
5737 return VariadicFunction;
5738 }
5739 return VariadicDoesNotApply;
5740}
5741
5742namespace {
5743class FunctionCallCCC final : public FunctionCallFilterCCC {
5744public:
5745 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5746 unsigned NumArgs, MemberExpr *ME)
5747 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5748 FunctionName(FuncName) {}
5749
5750 bool ValidateCandidate(const TypoCorrection &candidate) override {
5751 if (!candidate.getCorrectionSpecifier() ||
5752 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5753 return false;
5754 }
5755
5757 }
5758
5759 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5760 return std::make_unique<FunctionCallCCC>(*this);
5761 }
5762
5763private:
5764 const IdentifierInfo *const FunctionName;
5765};
5766}
5767
5769 FunctionDecl *FDecl,
5770 ArrayRef<Expr *> Args) {
5771 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5772 DeclarationName FuncName = FDecl->getDeclName();
5773 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5774
5775 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5776 if (TypoCorrection Corrected = S.CorrectTypo(
5778 S.getScopeForContext(S.CurContext), nullptr, CCC,
5780 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5781 if (Corrected.isOverloaded()) {
5784 for (NamedDecl *CD : Corrected) {
5785 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5787 OCS);
5788 }
5789 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5790 case OR_Success:
5791 ND = Best->FoundDecl;
5792 Corrected.setCorrectionDecl(ND);
5793 break;
5794 default:
5795 break;
5796 }
5797 }
5798 ND = ND->getUnderlyingDecl();
5799 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5800 return Corrected;
5801 }
5802 }
5803 return TypoCorrection();
5804}
5805
5806// [C++26][[expr.unary.op]/p4
5807// A pointer to member is only formed when an explicit &
5808// is used and its operand is a qualified-id not enclosed in parentheses.
5810 if (!isa<ParenExpr>(Fn))
5811 return false;
5812
5813 Fn = Fn->IgnoreParens();
5814
5815 auto *UO = dyn_cast<UnaryOperator>(Fn);
5816 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
5817 return false;
5818 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
5819 return DRE->hasQualifier();
5820 }
5821 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
5822 return OVL->getQualifier();
5823 return false;
5824}
5825
5826bool
5828 FunctionDecl *FDecl,
5829 const FunctionProtoType *Proto,
5830 ArrayRef<Expr *> Args,
5831 SourceLocation RParenLoc,
5832 bool IsExecConfig) {
5833 // Bail out early if calling a builtin with custom typechecking.
5834 if (FDecl)
5835 if (unsigned ID = FDecl->getBuiltinID())
5837 return false;
5838
5839 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5840 // assignment, to the types of the corresponding parameter, ...
5841
5842 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
5843 bool HasExplicitObjectParameter =
5844 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
5845 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
5846 unsigned NumParams = Proto->getNumParams();
5847 bool Invalid = false;
5848 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5849 unsigned FnKind = Fn->getType()->isBlockPointerType()
5850 ? 1 /* block */
5851 : (IsExecConfig ? 3 /* kernel function (exec config) */
5852 : 0 /* function */);
5853
5854 // If too few arguments are available (and we don't have default
5855 // arguments for the remaining parameters), don't make the call.
5856 if (Args.size() < NumParams) {
5857 if (Args.size() < MinArgs) {
5858 TypoCorrection TC;
5859 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5860 unsigned diag_id =
5861 MinArgs == NumParams && !Proto->isVariadic()
5862 ? diag::err_typecheck_call_too_few_args_suggest
5863 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5865 TC, PDiag(diag_id)
5866 << FnKind << MinArgs - ExplicitObjectParameterOffset
5867 << static_cast<unsigned>(Args.size()) -
5868 ExplicitObjectParameterOffset
5869 << HasExplicitObjectParameter << TC.getCorrectionRange());
5870 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
5871 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5872 ->getDeclName())
5873 Diag(RParenLoc,
5874 MinArgs == NumParams && !Proto->isVariadic()
5875 ? diag::err_typecheck_call_too_few_args_one
5876 : diag::err_typecheck_call_too_few_args_at_least_one)
5877 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5878 << HasExplicitObjectParameter << Fn->getSourceRange();
5879 else
5880 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5881 ? diag::err_typecheck_call_too_few_args
5882 : diag::err_typecheck_call_too_few_args_at_least)
5883 << FnKind << MinArgs - ExplicitObjectParameterOffset
5884 << static_cast<unsigned>(Args.size()) -
5885 ExplicitObjectParameterOffset
5886 << HasExplicitObjectParameter << Fn->getSourceRange();
5887
5888 // Emit the location of the prototype.
5889 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5890 Diag(FDecl->getLocation(), diag::note_callee_decl)
5891 << FDecl << FDecl->getParametersSourceRange();
5892
5893 return true;
5894 }
5895 // We reserve space for the default arguments when we create
5896 // the call expression, before calling ConvertArgumentsForCall.
5897 assert((Call->getNumArgs() == NumParams) &&
5898 "We should have reserved space for the default arguments before!");
5899 }
5900
5901 // If too many are passed and not variadic, error on the extras and drop
5902 // them.
5903 if (Args.size() > NumParams) {
5904 if (!Proto->isVariadic()) {
5905 TypoCorrection TC;
5906 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5907 unsigned diag_id =
5908 MinArgs == NumParams && !Proto->isVariadic()
5909 ? diag::err_typecheck_call_too_many_args_suggest
5910 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5912 TC, PDiag(diag_id)
5913 << FnKind << NumParams - ExplicitObjectParameterOffset
5914 << static_cast<unsigned>(Args.size()) -
5915 ExplicitObjectParameterOffset
5916 << HasExplicitObjectParameter << TC.getCorrectionRange());
5917 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
5918 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5919 ->getDeclName())
5920 Diag(Args[NumParams]->getBeginLoc(),
5921 MinArgs == NumParams
5922 ? diag::err_typecheck_call_too_many_args_one
5923 : diag::err_typecheck_call_too_many_args_at_most_one)
5924 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5925 << static_cast<unsigned>(Args.size()) -
5926 ExplicitObjectParameterOffset
5927 << HasExplicitObjectParameter << Fn->getSourceRange()
5928 << SourceRange(Args[NumParams]->getBeginLoc(),
5929 Args.back()->getEndLoc());
5930 else
5931 Diag(Args[NumParams]->getBeginLoc(),
5932 MinArgs == NumParams
5933 ? diag::err_typecheck_call_too_many_args
5934 : diag::err_typecheck_call_too_many_args_at_most)
5935 << FnKind << NumParams - ExplicitObjectParameterOffset
5936 << static_cast<unsigned>(Args.size()) -
5937 ExplicitObjectParameterOffset
5938 << HasExplicitObjectParameter << Fn->getSourceRange()
5939 << SourceRange(Args[NumParams]->getBeginLoc(),
5940 Args.back()->getEndLoc());
5941
5942 // Emit the location of the prototype.
5943 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5944 Diag(FDecl->getLocation(), diag::note_callee_decl)
5945 << FDecl << FDecl->getParametersSourceRange();
5946
5947 // This deletes the extra arguments.
5948 Call->shrinkNumArgs(NumParams);
5949 return true;
5950 }
5951 }
5952 SmallVector<Expr *, 8> AllArgs;
5953 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5954
5955 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
5956 AllArgs, CallType);
5957 if (Invalid)
5958 return true;
5959 unsigned TotalNumArgs = AllArgs.size();
5960 for (unsigned i = 0; i < TotalNumArgs; ++i)
5961 Call->setArg(i, AllArgs[i]);
5962
5963 Call->computeDependence();
5964 return false;
5965}
5966
5968 const FunctionProtoType *Proto,
5969 unsigned FirstParam, ArrayRef<Expr *> Args,
5970 SmallVectorImpl<Expr *> &AllArgs,
5971 VariadicCallType CallType, bool AllowExplicit,
5972 bool IsListInitialization) {
5973 unsigned NumParams = Proto->getNumParams();
5974 bool Invalid = false;
5975 size_t ArgIx = 0;
5976 // Continue to check argument types (even if we have too few/many args).
5977 for (unsigned i = FirstParam; i < NumParams; i++) {
5978 QualType ProtoArgType = Proto->getParamType(i);
5979
5980 Expr *Arg;
5981 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5982 if (ArgIx < Args.size()) {
5983 Arg = Args[ArgIx++];
5984
5985 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5986 diag::err_call_incomplete_argument, Arg))
5987 return true;
5988
5989 // Strip the unbridged-cast placeholder expression off, if applicable.
5990 bool CFAudited = false;
5991 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5992 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5993 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5994 Arg = ObjC().stripARCUnbridgedCast(Arg);
5995 else if (getLangOpts().ObjCAutoRefCount &&
5996 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5997 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5998 CFAudited = true;
5999
6000 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6001 ProtoArgType->isBlockPointerType())
6002 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6003 BE->getBlockDecl()->setDoesNotEscape();
6004 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
6006 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
6007 if (ArgExpr.isInvalid())
6008 return true;
6009 Arg = ArgExpr.getAs<Expr>();
6010 }
6011
6012 InitializedEntity Entity =
6014 ProtoArgType)
6016 Context, ProtoArgType, Proto->isParamConsumed(i));
6017
6018 // Remember that parameter belongs to a CF audited API.
6019 if (CFAudited)
6020 Entity.setParameterCFAudited();
6021
6023 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6024 if (ArgE.isInvalid())
6025 return true;
6026
6027 Arg = ArgE.getAs<Expr>();
6028 } else {
6029 assert(Param && "can't use default arguments without a known callee");
6030
6031 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6032 if (ArgExpr.isInvalid())
6033 return true;
6034
6035 Arg = ArgExpr.getAs<Expr>();
6036 }
6037
6038 // Check for array bounds violations for each argument to the call. This
6039 // check only triggers warnings when the argument isn't a more complex Expr
6040 // with its own checking, such as a BinaryOperator.
6041 CheckArrayAccess(Arg);
6042
6043 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6044 CheckStaticArrayArgument(CallLoc, Param, Arg);
6045
6046 AllArgs.push_back(Arg);
6047 }
6048
6049 // If this is a variadic call, handle args passed through "...".
6050 if (CallType != VariadicDoesNotApply) {
6051 // Assume that extern "C" functions with variadic arguments that
6052 // return __unknown_anytype aren't *really* variadic.
6053 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6054 FDecl->isExternC()) {
6055 for (Expr *A : Args.slice(ArgIx)) {
6056 QualType paramType; // ignored
6057 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6058 Invalid |= arg.isInvalid();
6059 AllArgs.push_back(arg.get());
6060 }
6061
6062 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6063 } else {
6064 for (Expr *A : Args.slice(ArgIx)) {
6065 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6066 Invalid |= Arg.isInvalid();
6067 AllArgs.push_back(Arg.get());
6068 }
6069 }
6070
6071 // Check for array bounds violations.
6072 for (Expr *A : Args.slice(ArgIx))
6073 CheckArrayAccess(A);
6074 }
6075 return Invalid;
6076}
6077
6079 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6080 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6081 TL = DTL.getOriginalLoc();
6082 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6083 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6084 << ATL.getLocalSourceRange();
6085}
6086
6087void
6089 ParmVarDecl *Param,
6090 const Expr *ArgExpr) {
6091 // Static array parameters are not supported in C++.
6092 if (!Param || getLangOpts().CPlusPlus)
6093 return;
6094
6095 QualType OrigTy = Param->getOriginalType();
6096
6097 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6098 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6099 return;
6100
6101 if (ArgExpr->isNullPointerConstant(Context,
6103 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6104 DiagnoseCalleeStaticArrayParam(*this, Param);
6105 return;
6106 }
6107
6108 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6109 if (!CAT)
6110 return;
6111
6112 const ConstantArrayType *ArgCAT =
6114 if (!ArgCAT)
6115 return;
6116
6117 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6118 ArgCAT->getElementType())) {
6119 if (ArgCAT->getSize().ult(CAT->getSize())) {
6120 Diag(CallLoc, diag::warn_static_array_too_small)
6121 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6122 << (unsigned)CAT->getZExtSize() << 0;
6123 DiagnoseCalleeStaticArrayParam(*this, Param);
6124 }
6125 return;
6126 }
6127
6128 std::optional<CharUnits> ArgSize =
6130 std::optional<CharUnits> ParmSize =
6132 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6133 Diag(CallLoc, diag::warn_static_array_too_small)
6134 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6135 << (unsigned)ParmSize->getQuantity() << 1;
6136 DiagnoseCalleeStaticArrayParam(*this, Param);
6137 }
6138}
6139
6140/// Given a function expression of unknown-any type, try to rebuild it
6141/// to have a function type.
6143
6144/// Is the given type a placeholder that we need to lower out
6145/// immediately during argument processing?
6147 // Placeholders are never sugared.
6148 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6149 if (!placeholder) return false;
6150
6151 switch (placeholder->getKind()) {
6152 // Ignore all the non-placeholder types.
6153#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6154 case BuiltinType::Id:
6155#include "clang/Basic/OpenCLImageTypes.def"
6156#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6157 case BuiltinType::Id:
6158#include "clang/Basic/OpenCLExtensionTypes.def"
6159 // In practice we'll never use this, since all SVE types are sugared
6160 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6161#define SVE_TYPE(Name, Id, SingletonId) \
6162 case BuiltinType::Id:
6163#include "clang/Basic/AArch64SVEACLETypes.def"
6164#define PPC_VECTOR_TYPE(Name, Id, Size) \
6165 case BuiltinType::Id:
6166#include "clang/Basic/PPCTypes.def"
6167#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6168#include "clang/Basic/RISCVVTypes.def"
6169#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6170#include "clang/Basic/WebAssemblyReferenceTypes.def"
6171#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6172#include "clang/Basic/AMDGPUTypes.def"
6173#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6174#include "clang/Basic/HLSLIntangibleTypes.def"
6175#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6176#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6177#include "clang/AST/BuiltinTypes.def"
6178 return false;
6179
6180 case BuiltinType::UnresolvedTemplate:
6181 // We cannot lower out overload sets; they might validly be resolved
6182 // by the call machinery.
6183 case BuiltinType::Overload:
6184 return false;
6185
6186 // Unbridged casts in ARC can be handled in some call positions and
6187 // should be left in place.
6188 case BuiltinType::ARCUnbridgedCast:
6189 return false;
6190
6191 // Pseudo-objects should be converted as soon as possible.
6192 case BuiltinType::PseudoObject:
6193 return true;
6194
6195 // The debugger mode could theoretically but currently does not try
6196 // to resolve unknown-typed arguments based on known parameter types.
6197 case BuiltinType::UnknownAny:
6198 return true;
6199
6200 // These are always invalid as call arguments and should be reported.
6201 case BuiltinType::BoundMember:
6202 case BuiltinType::BuiltinFn:
6203 case BuiltinType::IncompleteMatrixIdx:
6204 case BuiltinType::ArraySection:
6205 case BuiltinType::OMPArrayShaping:
6206 case BuiltinType::OMPIterator:
6207 return true;
6208
6209 }
6210 llvm_unreachable("bad builtin type kind");
6211}
6212
6214 // Apply this processing to all the arguments at once instead of
6215 // dying at the first failure.
6216 bool hasInvalid = false;
6217 for (size_t i = 0, e = args.size(); i != e; i++) {
6218 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6219 ExprResult result = CheckPlaceholderExpr(args[i]);
6220 if (result.isInvalid()) hasInvalid = true;
6221 else args[i] = result.get();
6222 }
6223 }
6224 return hasInvalid;
6225}
6226
6227/// If a builtin function has a pointer argument with no explicit address
6228/// space, then it should be able to accept a pointer to any address
6229/// space as input. In order to do this, we need to replace the
6230/// standard builtin declaration with one that uses the same address space
6231/// as the call.
6232///
6233/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6234/// it does not contain any pointer arguments without
6235/// an address space qualifer. Otherwise the rewritten
6236/// FunctionDecl is returned.
6237/// TODO: Handle pointer return types.
6239 FunctionDecl *FDecl,
6240 MultiExprArg ArgExprs) {
6241
6242 QualType DeclType = FDecl->getType();
6243 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6244
6245 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6246 ArgExprs.size() < FT->getNumParams())
6247 return nullptr;
6248
6249 bool NeedsNewDecl = false;
6250 unsigned i = 0;
6251 SmallVector<QualType, 8> OverloadParams;
6252
6253 for (QualType ParamType : FT->param_types()) {
6254
6255 // Convert array arguments to pointer to simplify type lookup.
6256 ExprResult ArgRes =
6258 if (ArgRes.isInvalid())
6259 return nullptr;
6260 Expr *Arg = ArgRes.get();
6261 QualType ArgType = Arg->getType();
6262 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6263 !ArgType->isPointerType() ||
6264 !ArgType->getPointeeType().hasAddressSpace() ||
6266 OverloadParams.push_back(ParamType);
6267 continue;
6268 }
6269
6270 QualType PointeeType = ParamType->getPointeeType();
6271 if (PointeeType.hasAddressSpace())
6272 continue;
6273
6274 NeedsNewDecl = true;
6275 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6276
6277 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6278 OverloadParams.push_back(Context.getPointerType(PointeeType));
6279 }
6280
6281 if (!NeedsNewDecl)
6282 return nullptr;
6283
6285 EPI.Variadic = FT->isVariadic();
6286 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6287 OverloadParams, EPI);
6288 DeclContext *Parent = FDecl->getParent();
6289 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6290 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6291 FDecl->getIdentifier(), OverloadTy,
6292 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6293 false,
6294 /*hasPrototype=*/true);
6296 FT = cast<FunctionProtoType>(OverloadTy);
6297 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6298 QualType ParamType = FT->getParamType(i);
6299 ParmVarDecl *Parm =
6300 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6301 SourceLocation(), nullptr, ParamType,
6302 /*TInfo=*/nullptr, SC_None, nullptr);
6303 Parm->setScopeInfo(0, i);
6304 Params.push_back(Parm);
6305 }
6306 OverloadDecl->setParams(Params);
6307 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6308 return OverloadDecl;
6309}
6310
6311static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6312 FunctionDecl *Callee,
6313 MultiExprArg ArgExprs) {
6314 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6315 // similar attributes) really don't like it when functions are called with an
6316 // invalid number of args.
6317 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6318 /*PartialOverloading=*/false) &&
6319 !Callee->isVariadic())
6320 return;
6321 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6322 return;
6323
6324 if (const EnableIfAttr *Attr =
6325 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6326 S.Diag(Fn->getBeginLoc(),
6327 isa<CXXMethodDecl>(Callee)
6328 ? diag::err_ovl_no_viable_member_function_in_call
6329 : diag::err_ovl_no_viable_function_in_call)
6330 << Callee << Callee->getSourceRange();
6331 S.Diag(Callee->getLocation(),
6332 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6333 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6334 return;
6335 }
6336}
6337
6339 const UnresolvedMemberExpr *const UME, Sema &S) {
6340
6341 const auto GetFunctionLevelDCIfCXXClass =
6342 [](Sema &S) -> const CXXRecordDecl * {
6343 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6344 if (!DC || !DC->getParent())
6345 return nullptr;
6346
6347 // If the call to some member function was made from within a member
6348 // function body 'M' return return 'M's parent.
6349 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6350 return MD->getParent()->getCanonicalDecl();
6351 // else the call was made from within a default member initializer of a
6352 // class, so return the class.
6353 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6354 return RD->getCanonicalDecl();
6355 return nullptr;
6356 };
6357 // If our DeclContext is neither a member function nor a class (in the
6358 // case of a lambda in a default member initializer), we can't have an
6359 // enclosing 'this'.
6360
6361 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6362 if (!CurParentClass)
6363 return false;
6364
6365 // The naming class for implicit member functions call is the class in which
6366 // name lookup starts.
6367 const CXXRecordDecl *const NamingClass =
6369 assert(NamingClass && "Must have naming class even for implicit access");
6370
6371 // If the unresolved member functions were found in a 'naming class' that is
6372 // related (either the same or derived from) to the class that contains the
6373 // member function that itself contained the implicit member access.
6374
6375 return CurParentClass == NamingClass ||
6376 CurParentClass->isDerivedFrom(NamingClass);
6377}
6378
6379static void
6381 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6382
6383 if (!UME)
6384 return;
6385
6386 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6387 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6388 // already been captured, or if this is an implicit member function call (if
6389 // it isn't, an attempt to capture 'this' should already have been made).
6390 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6391 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6392 return;
6393
6394 // Check if the naming class in which the unresolved members were found is
6395 // related (same as or is a base of) to the enclosing class.
6396
6398 return;
6399
6400
6401 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6402 // If the enclosing function is not dependent, then this lambda is
6403 // capture ready, so if we can capture this, do so.
6404 if (!EnclosingFunctionCtx->isDependentContext()) {
6405 // If the current lambda and all enclosing lambdas can capture 'this' -
6406 // then go ahead and capture 'this' (since our unresolved overload set
6407 // contains at least one non-static member function).
6408 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6409 S.CheckCXXThisCapture(CallLoc);
6410 } else if (S.CurContext->isDependentContext()) {
6411 // ... since this is an implicit member reference, that might potentially
6412 // involve a 'this' capture, mark 'this' for potential capture in
6413 // enclosing lambdas.
6414 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6415 CurLSI->addPotentialThisCapture(CallLoc);
6416 }
6417}
6418
6419// Once a call is fully resolved, warn for unqualified calls to specific
6420// C++ standard functions, like move and forward.
6422 const CallExpr *Call) {
6423 // We are only checking unary move and forward so exit early here.
6424 if (Call->getNumArgs() != 1)
6425 return;
6426
6427 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6428 if (!E || isa<UnresolvedLookupExpr>(E))
6429 return;
6430 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6431 if (!DRE || !DRE->getLocation().isValid())
6432 return;
6433
6434 if (DRE->getQualifier())
6435 return;
6436
6437 const FunctionDecl *FD = Call->getDirectCallee();
6438 if (!FD)
6439 return;
6440
6441 // Only warn for some functions deemed more frequent or problematic.
6442 unsigned BuiltinID = FD->getBuiltinID();
6443 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6444 return;
6445
6446 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6448 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6449}
6450
6452 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6453 Expr *ExecConfig) {
6455 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6456 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6457 if (Call.isInvalid())
6458 return Call;
6459
6460 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6461 // language modes.
6462 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6463 ULE && ULE->hasExplicitTemplateArgs() &&
6464 ULE->decls_begin() == ULE->decls_end()) {
6465 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6466 ? diag::warn_cxx17_compat_adl_only_template_id
6467 : diag::ext_adl_only_template_id)
6468 << ULE->getName();
6469 }
6470
6471 if (LangOpts.OpenMP)
6472 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6473 ExecConfig);
6474 if (LangOpts.CPlusPlus) {
6475 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6477
6478 // If we previously found that the id-expression of this call refers to a
6479 // consteval function but the call is dependent, we should not treat is an
6480 // an invalid immediate call.
6481 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6482 DRE && Call.get()->isValueDependent()) {
6484 }
6485 }
6486 return Call;
6487}
6488
6490 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6491 Expr *ExecConfig, bool IsExecConfig,
6492 bool AllowRecovery) {
6493 // Since this might be a postfix expression, get rid of ParenListExprs.
6495 if (Result.isInvalid()) return ExprError();
6496 Fn = Result.get();
6497
6498 if (CheckArgsForPlaceholders(ArgExprs))
6499 return ExprError();
6500
6501 // The result of __builtin_counted_by_ref cannot be used as a function
6502 // argument. It allows leaking and modification of bounds safety information.
6503 for (const Expr *Arg : ArgExprs)
6504 if (CheckInvalidBuiltinCountedByRef(Arg, FunctionArgKind))
6505 return ExprError();
6506
6507 if (getLangOpts().CPlusPlus) {
6508 // If this is a pseudo-destructor expression, build the call immediately.
6509 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6510 if (!ArgExprs.empty()) {
6511 // Pseudo-destructor calls should not have any arguments.
6512 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6514 SourceRange(ArgExprs.front()->getBeginLoc(),
6515 ArgExprs.back()->getEndLoc()));
6516 }
6517
6518 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6519 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6520 }
6521 if (Fn->getType() == Context.PseudoObjectTy) {
6522 ExprResult result = CheckPlaceholderExpr(Fn);
6523 if (result.isInvalid()) return ExprError();
6524 Fn = result.get();
6525 }
6526
6527 // Determine whether this is a dependent call inside a C++ template,
6528 // in which case we won't do any semantic analysis now.
6529 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6530 if (ExecConfig) {
6532 cast<CallExpr>(ExecConfig), ArgExprs,
6534 RParenLoc, CurFPFeatureOverrides());
6535 } else {
6536
6538 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6539 Fn->getBeginLoc());
6540
6541 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6542 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6543 }
6544 }
6545
6546 // Determine whether this is a call to an object (C++ [over.call.object]).
6547 if (Fn->getType()->isRecordType())
6548 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6549 RParenLoc);
6550
6551 if (Fn->getType() == Context.UnknownAnyTy) {
6552 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6553 if (result.isInvalid()) return ExprError();
6554 Fn = result.get();
6555 }
6556
6557 if (Fn->getType() == Context.BoundMemberTy) {
6558 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6559 RParenLoc, ExecConfig, IsExecConfig,
6560 AllowRecovery);
6561 }
6562 }
6563
6564 // Check for overloaded calls. This can happen even in C due to extensions.
6565 if (Fn->getType() == Context.OverloadTy) {
6567
6568 // We aren't supposed to apply this logic if there's an '&' involved.
6571 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6572 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6573 OverloadExpr *ovl = find.Expression;
6574 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6576 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6577 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6578 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6579 RParenLoc, ExecConfig, IsExecConfig,
6580 AllowRecovery);
6581 }
6582 }
6583
6584 // If we're directly calling a function, get the appropriate declaration.
6585 if (Fn->getType() == Context.UnknownAnyTy) {
6586 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6587 if (result.isInvalid()) return ExprError();
6588 Fn = result.get();
6589 }
6590
6591 Expr *NakedFn = Fn->IgnoreParens();
6592
6593 bool CallingNDeclIndirectly = false;
6594 NamedDecl *NDecl = nullptr;
6595 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6596 if (UnOp->getOpcode() == UO_AddrOf) {
6597 CallingNDeclIndirectly = true;
6598 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6599 }
6600 }
6601
6602 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6603 NDecl = DRE->getDecl();
6604
6605 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6606 if (FDecl && FDecl->getBuiltinID()) {
6607 // Rewrite the function decl for this builtin by replacing parameters
6608 // with no explicit address space with the address space of the arguments
6609 // in ArgExprs.
6610 if ((FDecl =
6611 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6612 NDecl = FDecl;
6614 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6615 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6616 nullptr, DRE->isNonOdrUse());
6617 }
6618 }
6619 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6620 NDecl = ME->getMemberDecl();
6621
6622 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6623 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6624 FD, /*Complain=*/true, Fn->getBeginLoc()))
6625 return ExprError();
6626
6627 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6628
6629 // If this expression is a call to a builtin function in HIP device
6630 // compilation, allow a pointer-type argument to default address space to be
6631 // passed as a pointer-type parameter to a non-default address space.
6632 // If Arg is declared in the default address space and Param is declared
6633 // in a non-default address space, perform an implicit address space cast to
6634 // the parameter type.
6635 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6636 FD->getBuiltinID()) {
6637 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6638 ++Idx) {
6639 ParmVarDecl *Param = FD->getParamDecl(Idx);
6640 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6641 !ArgExprs[Idx]->getType()->isPointerType())
6642 continue;
6643
6644 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6645 auto ArgTy = ArgExprs[Idx]->getType();
6646 auto ArgPtTy = ArgTy->getPointeeType();
6647 auto ArgAS = ArgPtTy.getAddressSpace();
6648
6649 // Add address space cast if target address spaces are different
6650 bool NeedImplicitASC =
6651 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6652 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6653 // or from specific AS which has target AS matching that of Param.
6655 if (!NeedImplicitASC)
6656 continue;
6657
6658 // First, ensure that the Arg is an RValue.
6659 if (ArgExprs[Idx]->isGLValue()) {
6660 ArgExprs[Idx] = ImplicitCastExpr::Create(
6661 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6662 nullptr, VK_PRValue, FPOptionsOverride());
6663 }
6664
6665 // Construct a new arg type with address space of Param
6666 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6667 ArgPtQuals.setAddressSpace(ParamAS);
6668 auto NewArgPtTy =
6669 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6670 auto NewArgTy =
6672 ArgTy.getQualifiers());
6673
6674 // Finally perform an implicit address space cast
6675 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6676 CK_AddressSpaceConversion)
6677 .get();
6678 }
6679 }
6680 }
6681
6683 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6684 assert(!getLangOpts().CPlusPlus);
6685 assert((Fn->containsErrors() ||
6686 llvm::any_of(ArgExprs,
6687 [](clang::Expr *E) { return E->containsErrors(); })) &&
6688 "should only occur in error-recovery path.");
6689 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6690 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6691 }
6692 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6693 ExecConfig, IsExecConfig);
6694}
6695
6697 MultiExprArg CallArgs) {
6698 StringRef Name = Context.BuiltinInfo.getName(Id);
6699 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6701 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6702
6703 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6704 assert(BuiltInDecl && "failed to find builtin declaration");
6705
6706 ExprResult DeclRef =
6707 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6708 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6709
6711 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6712
6713 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6714 return Call.get();
6715}
6716
6718 SourceLocation BuiltinLoc,
6719 SourceLocation RParenLoc) {
6720 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6721 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6722}
6723
6725 SourceLocation BuiltinLoc,
6726 SourceLocation RParenLoc) {
6729 QualType SrcTy = E->getType();
6730 if (!SrcTy->isDependentType() &&
6731 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6732 return ExprError(
6733 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6734 << DestTy << SrcTy << E->getSourceRange());
6735 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6736}
6737
6739 SourceLocation BuiltinLoc,
6740 SourceLocation RParenLoc) {
6741 TypeSourceInfo *TInfo;
6742 GetTypeFromParser(ParsedDestTy, &TInfo);
6743 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6744}
6745
6747 SourceLocation LParenLoc,
6748 ArrayRef<Expr *> Args,
6749 SourceLocation RParenLoc, Expr *Config,
6750 bool IsExecConfig, ADLCallKind UsesADL) {
6751 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6752 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6753
6754 // Functions with 'interrupt' attribute cannot be called directly.
6755 if (FDecl) {
6756 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
6757 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6758 return ExprError();
6759 }
6760 if (FDecl->hasAttr<ARMInterruptAttr>()) {
6761 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
6762 return ExprError();
6763 }
6764 }
6765
6766 // X86 interrupt handlers may only call routines with attribute
6767 // no_caller_saved_registers since there is no efficient way to
6768 // save and restore the non-GPR state.
6769 if (auto *Caller = getCurFunctionDecl()) {
6770 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6771 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6772 const TargetInfo &TI = Context.getTargetInfo();
6773 bool HasNonGPRRegisters =
6774 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
6775 if (HasNonGPRRegisters &&
6776 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6777 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
6778 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6779 if (FDecl)
6780 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6781 }
6782 }
6783 }
6784
6785 // Promote the function operand.
6786 // We special-case function promotion here because we only allow promoting
6787 // builtin functions to function pointers in the callee of a call.
6789 QualType ResultTy;
6790 if (BuiltinID &&
6791 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6792 // Extract the return type from the (builtin) function pointer type.
6793 // FIXME Several builtins still have setType in
6794 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6795 // Builtins.td to ensure they are correct before removing setType calls.
6796 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6797 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6798 ResultTy = FDecl->getCallResultType();
6799 } else {
6801 ResultTy = Context.BoolTy;
6802 }
6803 if (Result.isInvalid())
6804 return ExprError();
6805 Fn = Result.get();
6806
6807 // Check for a valid function type, but only if it is not a builtin which
6808 // requires custom type checking. These will be handled by
6809 // CheckBuiltinFunctionCall below just after creation of the call expression.
6810 const FunctionType *FuncT = nullptr;
6811 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6812 retry:
6813 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6814 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6815 // have type pointer to function".
6816 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6817 if (!FuncT)
6818 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6819 << Fn->getType() << Fn->getSourceRange());
6820 } else if (const BlockPointerType *BPT =
6821 Fn->getType()->getAs<BlockPointerType>()) {
6822 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6823 } else {
6824 // Handle calls to expressions of unknown-any type.
6825 if (Fn->getType() == Context.UnknownAnyTy) {
6826 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6827 if (rewrite.isInvalid())
6828 return ExprError();
6829 Fn = rewrite.get();
6830 goto retry;
6831 }
6832
6833 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6834 << Fn->getType() << Fn->getSourceRange());
6835 }
6836 }
6837
6838 // Get the number of parameters in the function prototype, if any.
6839 // We will allocate space for max(Args.size(), NumParams) arguments
6840 // in the call expression.
6841 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6842 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6843
6844 CallExpr *TheCall;
6845 if (Config) {
6846 assert(UsesADL == ADLCallKind::NotADL &&
6847 "CUDAKernelCallExpr should not use ADL");
6848 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6849 Args, ResultTy, VK_PRValue, RParenLoc,
6850 CurFPFeatureOverrides(), NumParams);
6851 } else {
6852 TheCall =
6853 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6854 CurFPFeatureOverrides(), NumParams, UsesADL);
6855 }
6856
6858 // Forget about the nulled arguments since typo correction
6859 // do not handle them well.
6860 TheCall->shrinkNumArgs(Args.size());
6861 // C cannot always handle TypoExpr nodes in builtin calls and direct
6862 // function calls as their argument checking don't necessarily handle
6863 // dependent types properly, so make sure any TypoExprs have been
6864 // dealt with.
6866 if (!Result.isUsable()) return ExprError();
6867 CallExpr *TheOldCall = TheCall;
6868 TheCall = dyn_cast<CallExpr>(Result.get());
6869 bool CorrectedTypos = TheCall != TheOldCall;
6870 if (!TheCall) return Result;
6871 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6872
6873 // A new call expression node was created if some typos were corrected.
6874 // However it may not have been constructed with enough storage. In this
6875 // case, rebuild the node with enough storage. The waste of space is
6876 // immaterial since this only happens when some typos were corrected.
6877 if (CorrectedTypos && Args.size() < NumParams) {
6878 if (Config)
6880 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6881 RParenLoc, CurFPFeatureOverrides(), NumParams);
6882 else
6883 TheCall =
6884 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6885 CurFPFeatureOverrides(), NumParams, UsesADL);
6886 }
6887 // We can now handle the nulled arguments for the default arguments.
6888 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6889 }
6890
6891 // Bail out early if calling a builtin with custom type checking.
6892 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6893 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6894 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
6896 return E;
6897 }
6898
6899 if (getLangOpts().CUDA) {
6900 if (Config) {
6901 // CUDA: Kernel calls must be to global functions
6902 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6903 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6904 << FDecl << Fn->getSourceRange());
6905
6906 // CUDA: Kernel function must have 'void' return type
6907 if (!FuncT->getReturnType()->isVoidType() &&
6908 !FuncT->getReturnType()->getAs<AutoType>() &&
6910 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6911 << Fn->getType() << Fn->getSourceRange());
6912 } else {
6913 // CUDA: Calls to global functions must be configured
6914 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6915 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6916 << FDecl << Fn->getSourceRange());
6917 }
6918 }
6919
6920 // Check for a valid return type
6921 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6922 FDecl))
6923 return ExprError();
6924
6925 // We know the result type of the call, set it.
6926 TheCall->setType(FuncT->getCallResultType(Context));
6928
6929 // WebAssembly tables can't be used as arguments.
6930 if (Context.getTargetInfo().getTriple().isWasm()) {
6931 for (const Expr *Arg : Args) {
6932 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
6933 return ExprError(Diag(Arg->getExprLoc(),
6934 diag::err_wasm_table_as_function_parameter));
6935 }
6936 }
6937 }
6938
6939 if (Proto) {
6940 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6941 IsExecConfig))
6942 return ExprError();
6943 } else {
6944 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6945
6946 if (FDecl) {
6947 // Check if we have too few/too many template arguments, based
6948 // on our knowledge of the function definition.
6949 const FunctionDecl *Def = nullptr;
6950 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6951 Proto = Def->getType()->getAs<FunctionProtoType>();
6952 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6953 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6954 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6955 }
6956
6957 // If the function we're calling isn't a function prototype, but we have
6958 // a function prototype from a prior declaratiom, use that prototype.
6959 if (!FDecl->hasPrototype())
6960 Proto = FDecl->getType()->getAs<FunctionProtoType>();
6961 }
6962
6963 // If we still haven't found a prototype to use but there are arguments to
6964 // the call, diagnose this as calling a function without a prototype.
6965 // However, if we found a function declaration, check to see if
6966 // -Wdeprecated-non-prototype was disabled where the function was declared.
6967 // If so, we will silence the diagnostic here on the assumption that this
6968 // interface is intentional and the user knows what they're doing. We will
6969 // also silence the diagnostic if there is a function declaration but it
6970 // was implicitly defined (the user already gets diagnostics about the
6971 // creation of the implicit function declaration, so the additional warning
6972 // is not helpful).
6973 if (!Proto && !Args.empty() &&
6974 (!FDecl || (!FDecl->isImplicit() &&
6975 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
6976 FDecl->getLocation()))))
6977 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
6978 << (FDecl != nullptr) << FDecl;
6979
6980 // Promote the arguments (C99 6.5.2.2p6).
6981 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6982 Expr *Arg = Args[i];
6983
6984 if (Proto && i < Proto->getNumParams()) {
6986 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6987 ExprResult ArgE =
6989 if (ArgE.isInvalid())
6990 return true;
6991
6992 Arg = ArgE.getAs<Expr>();
6993
6994 } else {
6996
6997 if (ArgE.isInvalid())
6998 return true;
6999
7000 Arg = ArgE.getAs<Expr>();
7001 }
7002
7003 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7004 diag::err_call_incomplete_argument, Arg))
7005 return ExprError();
7006
7007 TheCall->setArg(i, Arg);
7008 }
7009 TheCall->computeDependence();
7010 }
7011
7012 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7013 if (Method->isImplicitObjectMemberFunction())
7014 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7015 << Fn->getSourceRange() << 0);
7016
7017 // Check for sentinels
7018 if (NDecl)
7019 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7020
7021 // Warn for unions passing across security boundary (CMSE).
7022 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7023 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7024 if (const auto *RT =
7025 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7026 if (RT->getDecl()->isOrContainsUnion())
7027 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7028 << 0 << i;
7029 }
7030 }
7031 }
7032
7033 // Do special checking on direct calls to functions.
7034 if (FDecl) {
7035 if (CheckFunctionCall(FDecl, TheCall, Proto))
7036 return ExprError();
7037
7038 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7039
7040 if (BuiltinID)
7041 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7042 } else if (NDecl) {
7043 if (CheckPointerCall(NDecl, TheCall, Proto))
7044 return ExprError();
7045 } else {
7046 if (CheckOtherCall(TheCall, Proto))
7047 return ExprError();
7048 }
7049
7050 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7051}
7052
7055 SourceLocation RParenLoc, Expr *InitExpr) {
7056 assert(Ty && "ActOnCompoundLiteral(): missing type");
7057 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7058
7059 TypeSourceInfo *TInfo;
7060 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7061 if (!TInfo)
7062 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7063
7064 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7065}
7066
7069 SourceLocation RParenLoc, Expr *LiteralExpr) {
7070 QualType literalType = TInfo->getType();
7071
7072 if (literalType->isArrayType()) {
7074 LParenLoc, Context.getBaseElementType(literalType),
7075 diag::err_array_incomplete_or_sizeless_type,
7076 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7077 return ExprError();
7078 if (literalType->isVariableArrayType()) {
7079 // C23 6.7.10p4: An entity of variable length array type shall not be
7080 // initialized except by an empty initializer.
7081 //
7082 // The C extension warnings are issued from ParseBraceInitializer() and
7083 // do not need to be issued here. However, we continue to issue an error
7084 // in the case there are initializers or we are compiling C++. We allow
7085 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7086 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7087 // FIXME: should we allow this construct in C++ when it makes sense to do
7088 // so?
7089 //
7090 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7091 // shall specify an object type or an array of unknown size, but not a
7092 // variable length array type. This seems odd, as it allows 'int a[size] =
7093 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7094 // says, this is what's implemented here for C (except for the extension
7095 // that permits constant foldable size arrays)
7096
7097 auto diagID = LangOpts.CPlusPlus
7098 ? diag::err_variable_object_no_init
7099 : diag::err_compound_literal_with_vla_type;
7100 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7101 diagID))
7102 return ExprError();
7103 }
7104 } else if (!literalType->isDependentType() &&
7105 RequireCompleteType(LParenLoc, literalType,
7106 diag::err_typecheck_decl_incomplete_type,
7107 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7108 return ExprError();
7109
7110 InitializedEntity Entity
7114 SourceRange(LParenLoc, RParenLoc),
7115 /*InitList=*/true);
7116 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7117 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7118 &literalType);
7119 if (Result.isInvalid())
7120 return ExprError();
7121 LiteralExpr = Result.get();
7122
7123 bool isFileScope = !CurContext->isFunctionOrMethod();
7124
7125 // In C, compound literals are l-values for some reason.
7126 // For GCC compatibility, in C++, file-scope array compound literals with
7127 // constant initializers are also l-values, and compound literals are
7128 // otherwise prvalues.
7129 //
7130 // (GCC also treats C++ list-initialized file-scope array prvalues with
7131 // constant initializers as l-values, but that's non-conforming, so we don't
7132 // follow it there.)
7133 //
7134 // FIXME: It would be better to handle the lvalue cases as materializing and
7135 // lifetime-extending a temporary object, but our materialized temporaries
7136 // representation only supports lifetime extension from a variable, not "out
7137 // of thin air".
7138 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7139 // is bound to the result of applying array-to-pointer decay to the compound
7140 // literal.
7141 // FIXME: GCC supports compound literals of reference type, which should
7142 // obviously have a value kind derived from the kind of reference involved.
7143 ExprValueKind VK =
7144 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7145 ? VK_PRValue
7146 : VK_LValue;
7147
7148 if (isFileScope)
7149 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7150 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7151 Expr *Init = ILE->getInit(i);
7152 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7153 }
7154
7155 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7156 VK, LiteralExpr, isFileScope);
7157 if (isFileScope) {
7158 if (!LiteralExpr->isTypeDependent() &&
7159 !LiteralExpr->isValueDependent() &&
7160 !literalType->isDependentType()) // C99 6.5.2.5p3
7161 if (CheckForConstantInitializer(LiteralExpr))
7162 return ExprError();
7163 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7164 literalType.getAddressSpace() != LangAS::Default) {
7165 // Embedded-C extensions to C99 6.5.2.5:
7166 // "If the compound literal occurs inside the body of a function, the
7167 // type name shall not be qualified by an address-space qualifier."
7168 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7169 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7170 return ExprError();
7171 }
7172
7173 if (!isFileScope && !getLangOpts().CPlusPlus) {
7174 // Compound literals that have automatic storage duration are destroyed at
7175 // the end of the scope in C; in C++, they're just temporaries.
7176
7177 // Emit diagnostics if it is or contains a C union type that is non-trivial
7178 // to destruct.
7182
7183 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7184 if (literalType.isDestructedType()) {
7186 ExprCleanupObjects.push_back(E);
7188 }
7189 }
7190
7193 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7194 E->getInitializer()->getExprLoc());
7195
7196 return MaybeBindToTemporary(E);
7197}
7198
7201 SourceLocation RBraceLoc) {
7202 // Only produce each kind of designated initialization diagnostic once.
7203 SourceLocation FirstDesignator;
7204 bool DiagnosedArrayDesignator = false;
7205 bool DiagnosedNestedDesignator = false;
7206 bool DiagnosedMixedDesignator = false;
7207
7208 // Check that any designated initializers are syntactically valid in the
7209 // current language mode.
7210 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7211 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7212 if (FirstDesignator.isInvalid())
7213 FirstDesignator = DIE->getBeginLoc();
7214
7215 if (!getLangOpts().CPlusPlus)
7216 break;
7217
7218 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7219 DiagnosedNestedDesignator = true;
7220 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7221 << DIE->getDesignatorsSourceRange();
7222 }
7223
7224 for (auto &Desig : DIE->designators()) {
7225 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7226 DiagnosedArrayDesignator = true;
7227 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7228 << Desig.getSourceRange();
7229 }
7230 }
7231
7232 if (!DiagnosedMixedDesignator &&
7233 !isa<DesignatedInitExpr>(InitArgList[0])) {
7234 DiagnosedMixedDesignator = true;
7235 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7236 << DIE->getSourceRange();
7237 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7238 << InitArgList[0]->getSourceRange();
7239 }
7240 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7241 isa<DesignatedInitExpr>(InitArgList[0])) {
7242 DiagnosedMixedDesignator = true;
7243 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7244 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7245 << DIE->getSourceRange();
7246 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7247 << InitArgList[I]->getSourceRange();
7248 }
7249 }
7250
7251 if (FirstDesignator.isValid()) {
7252 // Only diagnose designated initiaization as a C++20 extension if we didn't
7253 // already diagnose use of (non-C++20) C99 designator syntax.
7254 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7255 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7256 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7257 ? diag::warn_cxx17_compat_designated_init
7258 : diag::ext_cxx_designated_init);
7259 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7260 Diag(FirstDesignator, diag::ext_designated_init);
7261 }
7262 }
7263
7264 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7265}
7266
7269 SourceLocation RBraceLoc) {
7270 // Semantic analysis for initializers is done by ActOnDeclarator() and
7271 // CheckInitializer() - it requires knowledge of the object being initialized.
7272
7273 // Immediately handle non-overload placeholders. Overloads can be
7274 // resolved contextually, but everything else here can't.
7275 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7276 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7277 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7278
7279 // Ignore failures; dropping the entire initializer list because
7280 // of one failure would be terrible for indexing/etc.
7281 if (result.isInvalid()) continue;
7282
7283 InitArgList[I] = result.get();
7284 }
7285 }
7286
7287 InitListExpr *E =
7288 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7289 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7290 return E;
7291}
7292
7294 assert(E.get()->getType()->isBlockPointerType());
7295 assert(E.get()->isPRValue());
7296
7297 // Only do this in an r-value context.
7298 if (!getLangOpts().ObjCAutoRefCount) return;
7299
7301 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7302 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7304}
7305
7307 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7308 // Also, callers should have filtered out the invalid cases with
7309 // pointers. Everything else should be possible.
7310
7311 QualType SrcTy = Src.get()->getType();
7312 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7313 return CK_NoOp;
7314
7315 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7317 llvm_unreachable("member pointer type in C");
7318
7319 case Type::STK_CPointer:
7322 switch (DestTy->getScalarTypeKind()) {
7323 case Type::STK_CPointer: {
7324 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7325 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7326 if (SrcAS != DestAS)
7327 return CK_AddressSpaceConversion;
7328 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7329 return CK_NoOp;
7330 return CK_BitCast;
7331 }
7333 return (SrcKind == Type::STK_BlockPointer
7334 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7336 if (SrcKind == Type::STK_ObjCObjectPointer)
7337 return CK_BitCast;
7338 if (SrcKind == Type::STK_CPointer)
7339 return CK_CPointerToObjCPointerCast;
7341 return CK_BlockPointerToObjCPointerCast;
7342 case Type::STK_Bool:
7343 return CK_PointerToBoolean;
7344 case Type::STK_Integral:
7345 return CK_PointerToIntegral;
7346 case Type::STK_Floating:
7351 llvm_unreachable("illegal cast from pointer");
7352 }
7353 llvm_unreachable("Should have returned before this");
7354
7356 switch (DestTy->getScalarTypeKind()) {
7358 return CK_FixedPointCast;
7359 case Type::STK_Bool:
7360 return CK_FixedPointToBoolean;
7361 case Type::STK_Integral:
7362 return CK_FixedPointToIntegral;
7363 case Type::STK_Floating:
7364 return CK_FixedPointToFloating;
7367 Diag(Src.get()->getExprLoc(),
7368 diag::err_unimplemented_conversion_with_fixed_point_type)
7369 << DestTy;
7370 return CK_IntegralCast;
7371 case Type::STK_CPointer:
7375 llvm_unreachable("illegal cast to pointer type");
7376 }
7377 llvm_unreachable("Should have returned before this");
7378
7379 case Type::STK_Bool: // casting from bool is like casting from an integer
7380 case Type::STK_Integral:
7381 switch (DestTy->getScalarTypeKind()) {
7382 case Type::STK_CPointer:
7387 return CK_NullToPointer;
7388 return CK_IntegralToPointer;
7389 case Type::STK_Bool:
7390 return CK_IntegralToBoolean;
7391 case Type::STK_Integral:
7392 return CK_IntegralCast;
7393 case Type::STK_Floating:
7394 return CK_IntegralToFloating;
7396 Src = ImpCastExprToType(Src.get(),
7397 DestTy->castAs<ComplexType>()->getElementType(),
7398 CK_IntegralCast);
7399 return CK_IntegralRealToComplex;
7401 Src = ImpCastExprToType(Src.get(),
7402 DestTy->castAs<ComplexType>()->getElementType(),
7403 CK_IntegralToFloating);
7404 return CK_FloatingRealToComplex;
7406 llvm_unreachable("member pointer type in C");
7408 return CK_IntegralToFixedPoint;
7409 }
7410 llvm_unreachable("Should have returned before this");
7411
7412 case Type::STK_Floating:
7413 switch (DestTy->getScalarTypeKind()) {
7414 case Type::STK_Floating:
7415 return CK_FloatingCast;
7416 case Type::STK_Bool:
7417 return CK_FloatingToBoolean;
7418 case Type::STK_Integral:
7419 return CK_FloatingToIntegral;
7421 Src = ImpCastExprToType(Src.get(),
7422 DestTy->castAs<ComplexType>()->getElementType(),
7423 CK_FloatingCast);
7424 return CK_FloatingRealToComplex;
7426 Src = ImpCastExprToType(Src.get(),
7427 DestTy->castAs<ComplexType>()->getElementType(),
7428 CK_FloatingToIntegral);
7429 return CK_IntegralRealToComplex;
7430 case Type::STK_CPointer:
7433 llvm_unreachable("valid float->pointer cast?");
7435 llvm_unreachable("member pointer type in C");
7437 return CK_FloatingToFixedPoint;
7438 }
7439 llvm_unreachable("Should have returned before this");
7440
7442 switch (DestTy->getScalarTypeKind()) {
7444 return CK_FloatingComplexCast;
7446 return CK_FloatingComplexToIntegralComplex;
7447 case Type::STK_Floating: {
7448 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7449 if (Context.hasSameType(ET, DestTy))
7450 return CK_FloatingComplexToReal;
7451 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7452 return CK_FloatingCast;
7453 }
7454 case Type::STK_Bool:
7455 return CK_FloatingComplexToBoolean;
7456 case Type::STK_Integral:
7457 Src = ImpCastExprToType(Src.get(),
7458 SrcTy->castAs<ComplexType>()->getElementType(),
7459 CK_FloatingComplexToReal);
7460 return CK_FloatingToIntegral;
7461 case Type::STK_CPointer:
7464 llvm_unreachable("valid complex float->pointer cast?");
7466 llvm_unreachable("member pointer type in C");
7468 Diag(Src.get()->getExprLoc(),
7469 diag::err_unimplemented_conversion_with_fixed_point_type)
7470 << SrcTy;
7471 return CK_IntegralCast;
7472 }
7473 llvm_unreachable("Should have returned before this");
7474
7476 switch (DestTy->getScalarTypeKind()) {
7478 return CK_IntegralComplexToFloatingComplex;
7480 return CK_IntegralComplexCast;
7481 case Type::STK_Integral: {
7482 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7483 if (Context.hasSameType(ET, DestTy))
7484 return CK_IntegralComplexToReal;
7485 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7486 return CK_IntegralCast;
7487 }
7488 case Type::STK_Bool:
7489 return CK_IntegralComplexToBoolean;
7490 case Type::STK_Floating:
7491 Src = ImpCastExprToType(Src.get(),
7492 SrcTy->castAs<ComplexType>()->getElementType(),
7493 CK_IntegralComplexToReal);
7494 return CK_IntegralToFloating;
7495 case Type::STK_CPointer:
7498 llvm_unreachable("valid complex int->pointer cast?");
7500 llvm_unreachable("member pointer type in C");
7502 Diag(Src.get()->getExprLoc(),
7503 diag::err_unimplemented_conversion_with_fixed_point_type)
7504 << SrcTy;
7505 return CK_IntegralCast;
7506 }
7507 llvm_unreachable("Should have returned before this");
7508 }
7509
7510 llvm_unreachable("Unhandled scalar cast");
7511}
7512
7513static bool breakDownVectorType(QualType type, uint64_t &len,
7514 QualType &eltType) {
7515 // Vectors are simple.
7516 if (const VectorType *vecType = type->getAs<VectorType>()) {
7517 len = vecType->getNumElements();
7518 eltType = vecType->getElementType();
7519 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7520 return true;
7521 }
7522
7523 // We allow lax conversion to and from non-vector types, but only if
7524 // they're real types (i.e. non-complex, non-pointer scalar types).
7525 if (!type->isRealType()) return false;
7526
7527 len = 1;
7528 eltType = type;
7529 return true;
7530}
7531
7533 assert(srcTy->isVectorType() || destTy->isVectorType());
7534
7535 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7536 if (!FirstType->isSVESizelessBuiltinType())
7537 return false;
7538
7539 const auto *VecTy = SecondType->getAs<VectorType>();
7540 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7541 };
7542
7543 return ValidScalableConversion(srcTy, destTy) ||
7544 ValidScalableConversion(destTy, srcTy);
7545}
7546
7548 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7549 return false;
7550
7551 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7552 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7553
7554 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7555 matSrcType->getNumColumns() == matDestType->getNumColumns();
7556}
7557
7559 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7560
7561 uint64_t SrcLen, DestLen;
7562 QualType SrcEltTy, DestEltTy;
7563 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7564 return false;
7565 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7566 return false;
7567
7568 // ASTContext::getTypeSize will return the size rounded up to a
7569 // power of 2, so instead of using that, we need to use the raw
7570 // element size multiplied by the element count.
7571 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7572 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7573
7574 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7575}
7576
7578 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7579 "expected at least one type to be a vector here");
7580
7581 bool IsSrcTyAltivec =
7582 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7584 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7586 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7588
7589 bool IsDestTyAltivec = DestTy->isVectorType() &&
7590 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7592 (DestTy->castAs<VectorType>()->getVectorKind() ==
7594 (DestTy->castAs<VectorType>()->getVectorKind() ==
7596
7597 return (IsSrcTyAltivec || IsDestTyAltivec);
7598}
7599
7601 assert(destTy->isVectorType() || srcTy->isVectorType());
7602
7603 // Disallow lax conversions between scalars and ExtVectors (these
7604 // conversions are allowed for other vector types because common headers
7605 // depend on them). Most scalar OP ExtVector cases are handled by the
7606 // splat path anyway, which does what we want (convert, not bitcast).
7607 // What this rules out for ExtVectors is crazy things like char4*float.
7608 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7609 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7610
7611 return areVectorTypesSameSize(srcTy, destTy);
7612}
7613
7615 assert(destTy->isVectorType() || srcTy->isVectorType());
7616
7617 switch (Context.getLangOpts().getLaxVectorConversions()) {
7619 return false;
7620
7622 if (!srcTy->isIntegralOrEnumerationType()) {
7623 auto *Vec = srcTy->getAs<VectorType>();
7624 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7625 return false;
7626 }
7627 if (!destTy->isIntegralOrEnumerationType()) {
7628 auto *Vec = destTy->getAs<VectorType>();
7629 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7630 return false;
7631 }
7632 // OK, integer (vector) -> integer (vector) bitcast.
7633 break;
7634
7636 break;
7637 }
7638
7639 return areLaxCompatibleVectorTypes(srcTy, destTy);
7640}
7641
7643 CastKind &Kind) {
7644 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7645 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7646 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7647 << DestTy << SrcTy << R;
7648 }
7649 } else if (SrcTy->isMatrixType()) {
7650 return Diag(R.getBegin(),
7651 diag::err_invalid_conversion_between_matrix_and_type)
7652 << SrcTy << DestTy << R;
7653 } else if (DestTy->isMatrixType()) {
7654 return Diag(R.getBegin(),
7655 diag::err_invalid_conversion_between_matrix_and_type)
7656 << DestTy << SrcTy << R;
7657 }
7658
7659 Kind = CK_MatrixCast;
7660 return false;
7661}
7662
7664 CastKind &Kind) {
7665 assert(VectorTy->isVectorType() && "Not a vector type!");
7666
7667 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7668 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7669 return Diag(R.getBegin(),
7670 Ty->isVectorType() ?
7671 diag::err_invalid_conversion_between_vectors :
7672 diag::err_invalid_conversion_between_vector_and_integer)
7673 << VectorTy << Ty << R;
7674 } else
7675 return Diag(R.getBegin(),
7676 diag::err_invalid_conversion_between_vector_and_scalar)
7677 << VectorTy << Ty << R;
7678
7679 Kind = CK_BitCast;
7680 return false;
7681}
7682
7684 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7685
7686 if (DestElemTy == SplattedExpr->getType())
7687 return SplattedExpr;
7688
7689 assert(DestElemTy->isFloatingType() ||
7690 DestElemTy->isIntegralOrEnumerationType());
7691
7692 CastKind CK;
7693 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7694 // OpenCL requires that we convert `true` boolean expressions to -1, but
7695 // only when splatting vectors.
7696 if (DestElemTy->isFloatingType()) {
7697 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7698 // in two steps: boolean to signed integral, then to floating.
7699 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7700 CK_BooleanToSignedIntegral);
7701 SplattedExpr = CastExprRes.get();
7702 CK = CK_IntegralToFloating;
7703 } else {
7704 CK = CK_BooleanToSignedIntegral;
7705 }
7706 } else {
7707 ExprResult CastExprRes = SplattedExpr;
7708 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7709 if (CastExprRes.isInvalid())
7710 return ExprError();
7711 SplattedExpr = CastExprRes.get();
7712 }
7713 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7714}
7715
7717 Expr *CastExpr, CastKind &Kind) {
7718 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7719
7720 QualType SrcTy = CastExpr->getType();
7721
7722 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7723 // an ExtVectorType.
7724 // In OpenCL, casts between vectors of different types are not allowed.
7725 // (See OpenCL 6.2).
7726 if (SrcTy->isVectorType()) {
7727 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7728 (getLangOpts().OpenCL &&
7729 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7730 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7731 << DestTy << SrcTy << R;
7732 return ExprError();
7733 }
7734 Kind = CK_BitCast;
7735 return CastExpr;
7736 }
7737
7738 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7739 // conversion will take place first from scalar to elt type, and then
7740 // splat from elt type to vector.
7741 if (SrcTy->isPointerType())
7742 return Diag(R.getBegin(),
7743 diag::err_invalid_conversion_between_vector_and_scalar)
7744 << DestTy << SrcTy << R;
7745
7746 Kind = CK_VectorSplat;
7747 return prepareVectorSplat(DestTy, CastExpr);
7748}
7749
7752 Declarator &D, ParsedType &Ty,
7753 SourceLocation RParenLoc, Expr *CastExpr) {
7754 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7755 "ActOnCastExpr(): missing type or expr");
7756
7758 if (D.isInvalidType())
7759 return ExprError();
7760
7761 if (getLangOpts().CPlusPlus) {
7762 // Check that there are no default arguments (C++ only).
7764 } else {
7765 // Make sure any TypoExprs have been dealt with.
7767 if (!Res.isUsable())
7768 return ExprError();
7769 CastExpr = Res.get();
7770 }
7771
7773
7774 QualType castType = castTInfo->getType();
7775 Ty = CreateParsedType(castType, castTInfo);
7776
7777 bool isVectorLiteral = false;
7778
7779 // Check for an altivec or OpenCL literal,
7780 // i.e. all the elements are integer constants.
7781 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7782 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7783 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7784 && castType->isVectorType() && (PE || PLE)) {
7785 if (PLE && PLE->getNumExprs() == 0) {
7786 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7787 return ExprError();
7788 }
7789 if (PE || PLE->getNumExprs() == 1) {
7790 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7791 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7792 isVectorLiteral = true;
7793 }
7794 else
7795 isVectorLiteral = true;
7796 }
7797
7798 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7799 // then handle it as such.
7800 if (isVectorLiteral)
7801 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7802
7803 // If the Expr being casted is a ParenListExpr, handle it specially.
7804 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7805 // sequence of BinOp comma operators.
7806 if (isa<ParenListExpr>(CastExpr)) {
7808 if (Result.isInvalid()) return ExprError();
7809 CastExpr = Result.get();
7810 }
7811
7812 if (getLangOpts().CPlusPlus && !castType->isVoidType())
7813 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7814
7816
7818
7820
7821 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7822}
7823
7825 SourceLocation RParenLoc, Expr *E,
7826 TypeSourceInfo *TInfo) {
7827 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7828 "Expected paren or paren list expression");
7829
7830 Expr **exprs;
7831 unsigned numExprs;
7832 Expr *subExpr;
7833 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7834 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7835 LiteralLParenLoc = PE->getLParenLoc();
7836 LiteralRParenLoc = PE->getRParenLoc();
7837 exprs = PE->getExprs();
7838 numExprs = PE->getNumExprs();
7839 } else { // isa<ParenExpr> by assertion at function entrance
7840 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7841 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7842 subExpr = cast<ParenExpr>(E)->getSubExpr();
7843 exprs = &subExpr;
7844 numExprs = 1;
7845 }
7846
7847 QualType Ty = TInfo->getType();
7848 assert(Ty->isVectorType() && "Expected vector type");
7849
7850 SmallVector<Expr *, 8> initExprs;
7851 const VectorType *VTy = Ty->castAs<VectorType>();
7852 unsigned numElems = VTy->getNumElements();
7853
7854 // '(...)' form of vector initialization in AltiVec: the number of
7855 // initializers must be one or must match the size of the vector.
7856 // If a single value is specified in the initializer then it will be
7857 // replicated to all the components of the vector
7859 VTy->getElementType()))
7860 return ExprError();
7862 // The number of initializers must be one or must match the size of the
7863 // vector. If a single value is specified in the initializer then it will
7864 // be replicated to all the components of the vector
7865 if (numExprs == 1) {
7866 QualType ElemTy = VTy->getElementType();
7867 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7868 if (Literal.isInvalid())
7869 return ExprError();
7870 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7871 PrepareScalarCast(Literal, ElemTy));
7872 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7873 }
7874 else if (numExprs < numElems) {
7875 Diag(E->getExprLoc(),
7876 diag::err_incorrect_number_of_vector_initializers);
7877 return ExprError();
7878 }
7879 else
7880 initExprs.append(exprs, exprs + numExprs);
7881 }
7882 else {
7883 // For OpenCL, when the number of initializers is a single value,
7884 // it will be replicated to all components of the vector.
7886 numExprs == 1) {
7887 QualType ElemTy = VTy->getElementType();
7888 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7889 if (Literal.isInvalid())
7890 return ExprError();
7891 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7892 PrepareScalarCast(Literal, ElemTy));
7893 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7894 }
7895
7896 initExprs.append(exprs, exprs + numExprs);
7897 }
7898 // FIXME: This means that pretty-printing the final AST will produce curly
7899 // braces instead of the original commas.
7900 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7901 initExprs, LiteralRParenLoc);
7902 initE->setType(Ty);
7903 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7904}
7905
7908 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7909 if (!E)
7910 return OrigExpr;
7911
7912 ExprResult Result(E->getExpr(0));
7913
7914 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7915 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7916 E->getExpr(i));
7917
7918 if (Result.isInvalid()) return ExprError();
7919
7920 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7921}
7922
7925 MultiExprArg Val) {
7926 return ParenListExpr::Create(Context, L, Val, R);
7927}
7928
7929bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7930 SourceLocation QuestionLoc) {
7931 const Expr *NullExpr = LHSExpr;
7932 const Expr *NonPointerExpr = RHSExpr;
7936
7937 if (NullKind == Expr::NPCK_NotNull) {
7938 NullExpr = RHSExpr;
7939 NonPointerExpr = LHSExpr;
7940 NullKind =
7943 }
7944
7945 if (NullKind == Expr::NPCK_NotNull)
7946 return false;
7947
7948 if (NullKind == Expr::NPCK_ZeroExpression)
7949 return false;
7950
7951 if (NullKind == Expr::NPCK_ZeroLiteral) {
7952 // In this case, check to make sure that we got here from a "NULL"
7953 // string in the source code.
7954 NullExpr = NullExpr->IgnoreParenImpCasts();
7955 SourceLocation loc = NullExpr->getExprLoc();
7956 if (!findMacroSpelling(loc, "NULL"))
7957 return false;
7958 }
7959
7960 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7961 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7962 << NonPointerExpr->getType() << DiagType
7963 << NonPointerExpr->getSourceRange();
7964 return true;
7965}
7966
7967/// Return false if the condition expression is valid, true otherwise.
7968static bool checkCondition(Sema &S, const Expr *Cond,
7969 SourceLocation QuestionLoc) {
7970 QualType CondTy = Cond->getType();
7971
7972 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7973 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7974 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7975 << CondTy << Cond->getSourceRange();
7976 return true;
7977 }
7978
7979 // C99 6.5.15p2
7980 if (CondTy->isScalarType()) return false;
7981
7982 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7983 << CondTy << Cond->getSourceRange();
7984 return true;
7985}
7986
7987/// Return false if the NullExpr can be promoted to PointerTy,
7988/// true otherwise.
7990 QualType PointerTy) {
7991 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7992 !NullExpr.get()->isNullPointerConstant(S.Context,
7994 return true;
7995
7996 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7997 return false;
7998}
7999
8000/// Checks compatibility between two pointers and return the resulting
8001/// type.
8003 ExprResult &RHS,
8005 QualType LHSTy = LHS.get()->getType();
8006 QualType RHSTy = RHS.get()->getType();
8007
8008 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8009 // Two identical pointers types are always compatible.
8010 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8011 }
8012
8013 QualType lhptee, rhptee;
8014
8015 // Get the pointee types.
8016 bool IsBlockPointer = false;
8017 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8018 lhptee = LHSBTy->getPointeeType();
8019 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8020 IsBlockPointer = true;
8021 } else {
8022 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8023 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8024 }
8025
8026 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8027 // differently qualified versions of compatible types, the result type is
8028 // a pointer to an appropriately qualified version of the composite
8029 // type.
8030
8031 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8032 // clause doesn't make sense for our extensions. E.g. address space 2 should
8033 // be incompatible with address space 3: they may live on different devices or
8034 // anything.
8035 Qualifiers lhQual = lhptee.getQualifiers();
8036 Qualifiers rhQual = rhptee.getQualifiers();
8037
8038 LangAS ResultAddrSpace = LangAS::Default;
8039 LangAS LAddrSpace = lhQual.getAddressSpace();
8040 LangAS RAddrSpace = rhQual.getAddressSpace();
8041
8042 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8043 // spaces is disallowed.
8044 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8045 ResultAddrSpace = LAddrSpace;
8046 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8047 ResultAddrSpace = RAddrSpace;
8048 else {
8049 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8050 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8051 << RHS.get()->getSourceRange();
8052 return QualType();
8053 }
8054
8055 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8056 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8057 lhQual.removeCVRQualifiers();
8058 rhQual.removeCVRQualifiers();
8059
8060 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8061 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8062 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8063 // qual types are compatible iff
8064 // * corresponded types are compatible
8065 // * CVR qualifiers are equal
8066 // * address spaces are equal
8067 // Thus for conditional operator we merge CVR and address space unqualified
8068 // pointees and if there is a composite type we return a pointer to it with
8069 // merged qualifiers.
8070 LHSCastKind =
8071 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8072 RHSCastKind =
8073 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8074 lhQual.removeAddressSpace();
8075 rhQual.removeAddressSpace();
8076
8077 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8078 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8079
8080 QualType CompositeTy = S.Context.mergeTypes(
8081 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8082 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8083
8084 if (CompositeTy.isNull()) {
8085 // In this situation, we assume void* type. No especially good
8086 // reason, but this is what gcc does, and we do have to pick
8087 // to get a consistent AST.
8088 QualType incompatTy;
8089 incompatTy = S.Context.getPointerType(
8090 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8091 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8092 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8093
8094 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8095 // for casts between types with incompatible address space qualifiers.
8096 // For the following code the compiler produces casts between global and
8097 // local address spaces of the corresponded innermost pointees:
8098 // local int *global *a;
8099 // global int *global *b;
8100 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8101 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8102 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8103 << RHS.get()->getSourceRange();
8104
8105 return incompatTy;
8106 }
8107
8108 // The pointer types are compatible.
8109 // In case of OpenCL ResultTy should have the address space qualifier
8110 // which is a superset of address spaces of both the 2nd and the 3rd
8111 // operands of the conditional operator.
8112 QualType ResultTy = [&, ResultAddrSpace]() {
8113 if (S.getLangOpts().OpenCL) {
8114 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8115 CompositeQuals.setAddressSpace(ResultAddrSpace);
8116 return S.Context
8117 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8118 .withCVRQualifiers(MergedCVRQual);
8119 }
8120 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8121 }();
8122 if (IsBlockPointer)
8123 ResultTy = S.Context.getBlockPointerType(ResultTy);
8124 else
8125 ResultTy = S.Context.getPointerType(ResultTy);
8126
8127 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8128 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8129 return ResultTy;
8130}
8131
8132/// Return the resulting type when the operands are both block pointers.
8134 ExprResult &LHS,
8135 ExprResult &RHS,
8137 QualType LHSTy = LHS.get()->getType();
8138 QualType RHSTy = RHS.get()->getType();
8139
8140 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8141 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8143 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8144 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8145 return destType;
8146 }
8147 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8148 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8149 << RHS.get()->getSourceRange();
8150 return QualType();
8151 }
8152
8153 // We have 2 block pointer types.
8154 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8155}
8156
8157/// Return the resulting type when the operands are both pointers.
8158static QualType
8160 ExprResult &RHS,
8162 // get the pointer types
8163 QualType LHSTy = LHS.get()->getType();
8164 QualType RHSTy = RHS.get()->getType();
8165
8166 // get the "pointed to" types
8167 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8168 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8169
8170 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8171 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8172 // Figure out necessary qualifiers (C99 6.5.15p6)
8173 QualType destPointee
8174 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8175 QualType destType = S.Context.getPointerType(destPointee);
8176 // Add qualifiers if necessary.
8177 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8178 // Promote to void*.
8179 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8180 return destType;
8181 }
8182 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8183 QualType destPointee
8184 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8185 QualType destType = S.Context.getPointerType(destPointee);
8186 // Add qualifiers if necessary.
8187 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8188 // Promote to void*.
8189 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8190 return destType;
8191 }
8192
8193 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8194}
8195
8196/// Return false if the first expression is not an integer and the second
8197/// expression is not a pointer, true otherwise.
8199 Expr* PointerExpr, SourceLocation Loc,
8200 bool IsIntFirstExpr) {
8201 if (!PointerExpr->getType()->isPointerType() ||
8202 !Int.get()->getType()->isIntegerType())
8203 return false;
8204
8205 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8206 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8207
8208 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8209 << Expr1->getType() << Expr2->getType()
8210 << Expr1->getSourceRange() << Expr2->getSourceRange();
8211 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8212 CK_IntegralToPointer);
8213 return true;
8214}
8215
8216/// Simple conversion between integer and floating point types.
8217///
8218/// Used when handling the OpenCL conditional operator where the
8219/// condition is a vector while the other operands are scalar.
8220///
8221/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8222/// types are either integer or floating type. Between the two
8223/// operands, the type with the higher rank is defined as the "result
8224/// type". The other operand needs to be promoted to the same type. No
8225/// other type promotion is allowed. We cannot use
8226/// UsualArithmeticConversions() for this purpose, since it always
8227/// promotes promotable types.
8229 ExprResult &RHS,
8230 SourceLocation QuestionLoc) {
8232 if (LHS.isInvalid())
8233 return QualType();
8235 if (RHS.isInvalid())
8236 return QualType();
8237
8238 // For conversion purposes, we ignore any qualifiers.
8239 // For example, "const float" and "float" are equivalent.
8240 QualType LHSType =
8242 QualType RHSType =
8244
8245 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8246 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8247 << LHSType << LHS.get()->getSourceRange();
8248 return QualType();
8249 }
8250
8251 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8252 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8253 << RHSType << RHS.get()->getSourceRange();
8254 return QualType();
8255 }
8256
8257 // If both types are identical, no conversion is needed.
8258 if (LHSType == RHSType)
8259 return LHSType;
8260
8261 // Now handle "real" floating types (i.e. float, double, long double).
8262 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8263 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8264 /*IsCompAssign = */ false);
8265
8266 // Finally, we have two differing integer types.
8267 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8268 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8269}
8270
8271/// Convert scalar operands to a vector that matches the
8272/// condition in length.
8273///
8274/// Used when handling the OpenCL conditional operator where the
8275/// condition is a vector while the other operands are scalar.
8276///
8277/// We first compute the "result type" for the scalar operands
8278/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8279/// into a vector of that type where the length matches the condition
8280/// vector type. s6.11.6 requires that the element types of the result
8281/// and the condition must have the same number of bits.
8282static QualType
8284 QualType CondTy, SourceLocation QuestionLoc) {
8285 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8286 if (ResTy.isNull()) return QualType();
8287
8288 const VectorType *CV = CondTy->getAs<VectorType>();
8289 assert(CV);
8290
8291 // Determine the vector result type
8292 unsigned NumElements = CV->getNumElements();
8293 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8294
8295 // Ensure that all types have the same number of bits
8297 != S.Context.getTypeSize(ResTy)) {
8298 // Since VectorTy is created internally, it does not pretty print
8299 // with an OpenCL name. Instead, we just print a description.
8300 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8301 SmallString<64> Str;
8302 llvm::raw_svector_ostream OS(Str);
8303 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8304 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8305 << CondTy << OS.str();
8306 return QualType();
8307 }
8308
8309 // Convert operands to the vector result type
8310 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8311 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8312
8313 return VectorTy;
8314}
8315
8316/// Return false if this is a valid OpenCL condition vector
8318 SourceLocation QuestionLoc) {
8319 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8320 // integral type.
8321 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8322 assert(CondTy);
8323 QualType EleTy = CondTy->getElementType();
8324 if (EleTy->isIntegerType()) return false;
8325
8326 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8327 << Cond->getType() << Cond->getSourceRange();
8328 return true;
8329}
8330
8331/// Return false if the vector condition type and the vector
8332/// result type are compatible.
8333///
8334/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8335/// number of elements, and their element types have the same number
8336/// of bits.
8337static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8338 SourceLocation QuestionLoc) {
8339 const VectorType *CV = CondTy->getAs<VectorType>();
8340 const VectorType *RV = VecResTy->getAs<VectorType>();
8341 assert(CV && RV);
8342
8343 if (CV->getNumElements() != RV->getNumElements()) {
8344 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8345 << CondTy << VecResTy;
8346 return true;
8347 }
8348
8349 QualType CVE = CV->getElementType();
8350 QualType RVE = RV->getElementType();
8351
8352 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8353 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8354 << CondTy << VecResTy;
8355 return true;
8356 }
8357
8358 return false;
8359}
8360
8361/// Return the resulting type for the conditional operator in
8362/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8363/// s6.3.i) when the condition is a vector type.
8364static QualType
8366 ExprResult &LHS, ExprResult &RHS,
8367 SourceLocation QuestionLoc) {
8369 if (Cond.isInvalid())
8370 return QualType();
8371 QualType CondTy = Cond.get()->getType();
8372
8373 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8374 return QualType();
8375
8376 // If either operand is a vector then find the vector type of the
8377 // result as specified in OpenCL v1.1 s6.3.i.
8378 if (LHS.get()->getType()->isVectorType() ||
8379 RHS.get()->getType()->isVectorType()) {
8380 bool IsBoolVecLang =
8381 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8382 QualType VecResTy =
8383 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8384 /*isCompAssign*/ false,
8385 /*AllowBothBool*/ true,
8386 /*AllowBoolConversions*/ false,
8387 /*AllowBooleanOperation*/ IsBoolVecLang,
8388 /*ReportInvalid*/ true);
8389 if (VecResTy.isNull())
8390 return QualType();
8391 // The result type must match the condition type as specified in
8392 // OpenCL v1.1 s6.11.6.
8393 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8394 return QualType();
8395 return VecResTy;
8396 }
8397
8398 // Both operands are scalar.
8399 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8400}
8401
8402/// Return true if the Expr is block type
8403static bool checkBlockType(Sema &S, const Expr *E) {
8404 if (E->getType()->isBlockPointerType()) {
8405 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8406 return true;
8407 }
8408
8409 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8410 QualType Ty = CE->getCallee()->getType();
8411 if (Ty->isBlockPointerType()) {
8412 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8413 return true;
8414 }
8415 }
8416 return false;
8417}
8418
8419/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8420/// In that case, LHS = cond.
8421/// C99 6.5.15
8423 ExprResult &RHS, ExprValueKind &VK,
8424 ExprObjectKind &OK,
8425 SourceLocation QuestionLoc) {
8426
8427 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8428 if (!LHSResult.isUsable()) return QualType();
8429 LHS = LHSResult;
8430
8431 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8432 if (!RHSResult.isUsable()) return QualType();
8433 RHS = RHSResult;
8434
8435 // C++ is sufficiently different to merit its own checker.
8436 if (getLangOpts().CPlusPlus)
8437 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8438
8439 VK = VK_PRValue;
8440 OK = OK_Ordinary;
8441
8443 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8444 RHS.get()->isTypeDependent())) {
8445 assert(!getLangOpts().CPlusPlus);
8446 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8447 RHS.get()->containsErrors()) &&
8448 "should only occur in error-recovery path.");
8449 return Context.DependentTy;
8450 }
8451
8452 // The OpenCL operator with a vector condition is sufficiently
8453 // different to merit its own checker.
8454 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8455 Cond.get()->getType()->isExtVectorType())
8456 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8457
8458 // First, check the condition.
8459 Cond = UsualUnaryConversions(Cond.get());
8460 if (Cond.isInvalid())
8461 return QualType();
8462 if (checkCondition(*this, Cond.get(), QuestionLoc))
8463 return QualType();
8464
8465 // Handle vectors.
8466 if (LHS.get()->getType()->isVectorType() ||
8467 RHS.get()->getType()->isVectorType())
8468 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8469 /*AllowBothBool*/ true,
8470 /*AllowBoolConversions*/ false,
8471 /*AllowBooleanOperation*/ false,
8472 /*ReportInvalid*/ true);
8473
8474 QualType ResTy =
8475 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8476 if (LHS.isInvalid() || RHS.isInvalid())
8477 return QualType();
8478
8479 // WebAssembly tables are not allowed as conditional LHS or RHS.
8480 QualType LHSTy = LHS.get()->getType();
8481 QualType RHSTy = RHS.get()->getType();
8482 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8483 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8484 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8485 return QualType();
8486 }
8487
8488 // Diagnose attempts to convert between __ibm128, __float128 and long double
8489 // where such conversions currently can't be handled.
8490 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8491 Diag(QuestionLoc,
8492 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8493 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8494 return QualType();
8495 }
8496
8497 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8498 // selection operator (?:).
8499 if (getLangOpts().OpenCL &&
8500 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8501 return QualType();
8502 }
8503
8504 // If both operands have arithmetic type, do the usual arithmetic conversions
8505 // to find a common type: C99 6.5.15p3,5.
8506 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8507 // Disallow invalid arithmetic conversions, such as those between bit-
8508 // precise integers types of different sizes, or between a bit-precise
8509 // integer and another type.
8510 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8511 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8512 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8513 << RHS.get()->getSourceRange();
8514 return QualType();
8515 }
8516
8517 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8518 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8519
8520 return ResTy;
8521 }
8522
8523 // If both operands are the same structure or union type, the result is that
8524 // type.
8525 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8526 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8527 if (LHSRT->getDecl() == RHSRT->getDecl())
8528 // "If both the operands have structure or union type, the result has
8529 // that type." This implies that CV qualifiers are dropped.
8531 RHSTy.getUnqualifiedType());
8532 // FIXME: Type of conditional expression must be complete in C mode.
8533 }
8534
8535 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8536 // The following || allows only one side to be void (a GCC-ism).
8537 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8538 QualType ResTy;
8539 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8540 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8541 } else if (RHSTy->isVoidType()) {
8542 ResTy = RHSTy;
8543 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8544 << RHS.get()->getSourceRange();
8545 } else {
8546 ResTy = LHSTy;
8547 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8548 << LHS.get()->getSourceRange();
8549 }
8550 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8551 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8552 return ResTy;
8553 }
8554
8555 // C23 6.5.15p7:
8556 // ... if both the second and third operands have nullptr_t type, the
8557 // result also has that type.
8558 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8559 return ResTy;
8560
8561 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8562 // the type of the other operand."
8563 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8564 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8565
8566 // All objective-c pointer type analysis is done here.
8567 QualType compositeType =
8568 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8569 if (LHS.isInvalid() || RHS.isInvalid())
8570 return QualType();
8571 if (!compositeType.isNull())
8572 return compositeType;
8573
8574
8575 // Handle block pointer types.
8576 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8577 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8578 QuestionLoc);
8579
8580 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8581 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8582 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8583 QuestionLoc);
8584
8585 // GCC compatibility: soften pointer/integer mismatch. Note that
8586 // null pointers have been filtered out by this point.
8587 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8588 /*IsIntFirstExpr=*/true))
8589 return RHSTy;
8590 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8591 /*IsIntFirstExpr=*/false))
8592 return LHSTy;
8593
8594 // Emit a better diagnostic if one of the expressions is a null pointer
8595 // constant and the other is not a pointer type. In this case, the user most
8596 // likely forgot to take the address of the other expression.
8597 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8598 return QualType();
8599
8600 // Finally, if the LHS and RHS types are canonically the same type, we can
8601 // use the common sugared type.
8602 if (Context.hasSameType(LHSTy, RHSTy))
8603 return Context.getCommonSugaredType(LHSTy, RHSTy);
8604
8605 // Otherwise, the operands are not compatible.
8606 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8607 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8608 << RHS.get()->getSourceRange();
8609 return QualType();
8610}
8611
8612/// SuggestParentheses - Emit a note with a fixit hint that wraps
8613/// ParenRange in parentheses.
8615 const PartialDiagnostic &Note,
8616 SourceRange ParenRange) {
8617 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8618 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8619 EndLoc.isValid()) {
8620 Self.Diag(Loc, Note)
8621 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8622 << FixItHint::CreateInsertion(EndLoc, ")");
8623 } else {
8624 // We can't display the parentheses, so just show the bare note.
8625 Self.Diag(Loc, Note) << ParenRange;
8626 }
8627}
8628
8630 return BinaryOperator::isAdditiveOp(Opc) ||
8632 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8633 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8634 // not any of the logical operators. Bitwise-xor is commonly used as a
8635 // logical-xor because there is no logical-xor operator. The logical
8636 // operators, including uses of xor, have a high false positive rate for
8637 // precedence warnings.
8638}
8639
8640/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8641/// expression, either using a built-in or overloaded operator,
8642/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8643/// expression.
8645 const Expr **RHSExprs) {
8646 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8647 E = E->IgnoreImpCasts();
8649 E = E->IgnoreImpCasts();
8650 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8651 E = MTE->getSubExpr();
8652 E = E->IgnoreImpCasts();
8653 }
8654
8655 // Built-in binary operator.
8656 if (const auto *OP = dyn_cast<BinaryOperator>(E);
8657 OP && IsArithmeticOp(OP->getOpcode())) {
8658 *Opcode = OP->getOpcode();
8659 *RHSExprs = OP->getRHS();
8660 return true;
8661 }
8662
8663 // Overloaded operator.
8664 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8665 if (Call->getNumArgs() != 2)
8666 return false;
8667
8668 // Make sure this is really a binary operator that is safe to pass into
8669 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8670 OverloadedOperatorKind OO = Call->getOperator();
8671 if (OO < OO_Plus || OO > OO_Arrow ||
8672 OO == OO_PlusPlus || OO == OO_MinusMinus)
8673 return false;
8674
8676 if (IsArithmeticOp(OpKind)) {
8677 *Opcode = OpKind;
8678 *RHSExprs = Call->getArg(1);
8679 return true;
8680 }
8681 }
8682
8683 return false;
8684}
8685
8686/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8687/// or is a logical expression such as (x==y) which has int type, but is
8688/// commonly interpreted as boolean.
8689static bool ExprLooksBoolean(const Expr *E) {
8690 E = E->IgnoreParenImpCasts();
8691
8692 if (E->getType()->isBooleanType())
8693 return true;
8694 if (const auto *OP = dyn_cast<BinaryOperator>(E))
8695 return OP->isComparisonOp() || OP->isLogicalOp();
8696 if (const auto *OP = dyn_cast<UnaryOperator>(E))
8697 return OP->getOpcode() == UO_LNot;
8698 if (E->getType()->isPointerType())
8699 return true;
8700 // FIXME: What about overloaded operator calls returning "unspecified boolean
8701 // type"s (commonly pointer-to-members)?
8702
8703 return false;
8704}
8705
8706/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8707/// and binary operator are mixed in a way that suggests the programmer assumed
8708/// the conditional operator has higher precedence, for example:
8709/// "int x = a + someBinaryCondition ? 1 : 2".
8711 Expr *Condition, const Expr *LHSExpr,
8712 const Expr *RHSExpr) {
8713 BinaryOperatorKind CondOpcode;
8714 const Expr *CondRHS;
8715
8716 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8717 return;
8718 if (!ExprLooksBoolean(CondRHS))
8719 return;
8720
8721 // The condition is an arithmetic binary expression, with a right-
8722 // hand side that looks boolean, so warn.
8723
8724 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8725 ? diag::warn_precedence_bitwise_conditional
8726 : diag::warn_precedence_conditional;
8727
8728 Self.Diag(OpLoc, DiagID)
8729 << Condition->getSourceRange()
8730 << BinaryOperator::getOpcodeStr(CondOpcode);
8731
8733 Self, OpLoc,
8734 Self.PDiag(diag::note_precedence_silence)
8735 << BinaryOperator::getOpcodeStr(CondOpcode),
8736 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8737
8738 SuggestParentheses(Self, OpLoc,
8739 Self.PDiag(diag::note_precedence_conditional_first),
8740 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8741}
8742
8743/// Compute the nullability of a conditional expression.
8745 QualType LHSTy, QualType RHSTy,
8746 ASTContext &Ctx) {
8747 if (!ResTy->isAnyPointerType())
8748 return ResTy;
8749
8750 auto GetNullability = [](QualType Ty) {
8751 std::optional<NullabilityKind> Kind = Ty->getNullability();
8752 if (Kind) {
8753 // For our purposes, treat _Nullable_result as _Nullable.
8756 return *Kind;
8757 }
8759 };
8760
8761 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8762 NullabilityKind MergedKind;
8763
8764 // Compute nullability of a binary conditional expression.
8765 if (IsBin) {
8766 if (LHSKind == NullabilityKind::NonNull)
8767 MergedKind = NullabilityKind::NonNull;
8768 else
8769 MergedKind = RHSKind;
8770 // Compute nullability of a normal conditional expression.
8771 } else {
8772 if (LHSKind == NullabilityKind::Nullable ||
8773 RHSKind == NullabilityKind::Nullable)
8774 MergedKind = NullabilityKind::Nullable;
8775 else if (LHSKind == NullabilityKind::NonNull)
8776 MergedKind = RHSKind;
8777 else if (RHSKind == NullabilityKind::NonNull)
8778 MergedKind = LHSKind;
8779 else
8780 MergedKind = NullabilityKind::Unspecified;
8781 }
8782
8783 // Return if ResTy already has the correct nullability.
8784 if (GetNullability(ResTy) == MergedKind)
8785 return ResTy;
8786
8787 // Strip all nullability from ResTy.
8788 while (ResTy->getNullability())
8789 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8790
8791 // Create a new AttributedType with the new nullability kind.
8792 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
8793}
8794
8796 SourceLocation ColonLoc,
8797 Expr *CondExpr, Expr *LHSExpr,
8798 Expr *RHSExpr) {
8800 // C cannot handle TypoExpr nodes in the condition because it
8801 // doesn't handle dependent types properly, so make sure any TypoExprs have
8802 // been dealt with before checking the operands.
8803 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8804 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8805 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8806
8807 if (!CondResult.isUsable())
8808 return ExprError();
8809
8810 if (LHSExpr) {
8811 if (!LHSResult.isUsable())
8812 return ExprError();
8813 }
8814
8815 if (!RHSResult.isUsable())
8816 return ExprError();
8817
8818 CondExpr = CondResult.get();
8819 LHSExpr = LHSResult.get();
8820 RHSExpr = RHSResult.get();
8821 }
8822
8823 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8824 // was the condition.
8825 OpaqueValueExpr *opaqueValue = nullptr;
8826 Expr *commonExpr = nullptr;
8827 if (!LHSExpr) {
8828 commonExpr = CondExpr;
8829 // Lower out placeholder types first. This is important so that we don't
8830 // try to capture a placeholder. This happens in few cases in C++; such
8831 // as Objective-C++'s dictionary subscripting syntax.
8832 if (commonExpr->hasPlaceholderType()) {
8833 ExprResult result = CheckPlaceholderExpr(commonExpr);
8834 if (!result.isUsable()) return ExprError();
8835 commonExpr = result.get();
8836 }
8837 // We usually want to apply unary conversions *before* saving, except
8838 // in the special case of a C++ l-value conditional.
8839 if (!(getLangOpts().CPlusPlus
8840 && !commonExpr->isTypeDependent()
8841 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8842 && commonExpr->isGLValue()
8843 && commonExpr->isOrdinaryOrBitFieldObject()
8844 && RHSExpr->isOrdinaryOrBitFieldObject()
8845 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8846 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8847 if (commonRes.isInvalid())
8848 return ExprError();
8849 commonExpr = commonRes.get();
8850 }
8851
8852 // If the common expression is a class or array prvalue, materialize it
8853 // so that we can safely refer to it multiple times.
8854 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8855 commonExpr->getType()->isArrayType())) {
8856 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8857 if (MatExpr.isInvalid())
8858 return ExprError();
8859 commonExpr = MatExpr.get();
8860 }
8861
8862 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8863 commonExpr->getType(),
8864 commonExpr->getValueKind(),
8865 commonExpr->getObjectKind(),
8866 commonExpr);
8867 LHSExpr = CondExpr = opaqueValue;
8868 }
8869
8870 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8873 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8874 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8875 VK, OK, QuestionLoc);
8876 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8877 RHS.isInvalid())
8878 return ExprError();
8879
8880 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8881 RHS.get());
8882
8883 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8884
8885 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8886 Context);
8887
8888 if (!commonExpr)
8889 return new (Context)
8890 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8891 RHS.get(), result, VK, OK);
8892
8894 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8895 ColonLoc, result, VK, OK);
8896}
8897
8899 unsigned FromAttributes = 0, ToAttributes = 0;
8900 if (const auto *FromFn =
8901 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
8902 FromAttributes =
8903 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8904 if (const auto *ToFn =
8905 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
8906 ToAttributes =
8907 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8908
8909 return FromAttributes != ToAttributes;
8910}
8911
8912// Check if we have a conversion between incompatible cmse function pointer
8913// types, that is, a conversion between a function pointer with the
8914// cmse_nonsecure_call attribute and one without.
8916 QualType ToType) {
8917 if (const auto *ToFn =
8918 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8919 if (const auto *FromFn =
8920 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8921 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8922 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8923
8924 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8925 }
8926 }
8927 return false;
8928}
8929
8930// checkPointerTypesForAssignment - This is a very tricky routine (despite
8931// being closely modeled after the C99 spec:-). The odd characteristic of this
8932// routine is it effectively iqnores the qualifiers on the top level pointee.
8933// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8934// FIXME: add a couple examples in this comment.
8938 assert(LHSType.isCanonical() && "LHS not canonicalized!");
8939 assert(RHSType.isCanonical() && "RHS not canonicalized!");
8940
8941 // get the "pointed to" type (ignoring qualifiers at the top level)
8942 const Type *lhptee, *rhptee;
8943 Qualifiers lhq, rhq;
8944 std::tie(lhptee, lhq) =
8945 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8946 std::tie(rhptee, rhq) =
8947 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8948
8950
8951 // C99 6.5.16.1p1: This following citation is common to constraints
8952 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8953 // qualifiers of the type *pointed to* by the right;
8954
8955 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8956 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8958 // Ignore lifetime for further calculation.
8959 lhq.removeObjCLifetime();
8960 rhq.removeObjCLifetime();
8961 }
8962
8963 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
8964 // Treat address-space mismatches as fatal.
8965 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
8967
8968 // It's okay to add or remove GC or lifetime qualifiers when converting to
8969 // and from void*.
8972 S.getASTContext()) &&
8973 (lhptee->isVoidType() || rhptee->isVoidType()))
8974 ; // keep old
8975
8976 // Treat lifetime mismatches as fatal.
8977 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8979
8980 // For GCC/MS compatibility, other qualifier mismatches are treated
8981 // as still compatible in C.
8983 }
8984
8985 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8986 // incomplete type and the other is a pointer to a qualified or unqualified
8987 // version of void...
8988 if (lhptee->isVoidType()) {
8989 if (rhptee->isIncompleteOrObjectType())
8990 return ConvTy;
8991
8992 // As an extension, we allow cast to/from void* to function pointer.
8993 assert(rhptee->isFunctionType());
8995 }
8996
8997 if (rhptee->isVoidType()) {
8998 if (lhptee->isIncompleteOrObjectType())
8999 return ConvTy;
9000
9001 // As an extension, we allow cast to/from void* to function pointer.
9002 assert(lhptee->isFunctionType());
9004 }
9005
9006 if (!S.Diags.isIgnored(
9007 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9008 Loc) &&
9009 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9010 !S.IsFunctionConversion(RHSType, LHSType, RHSType))
9012
9013 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9014 // unqualified versions of compatible types, ...
9015 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9016 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9017 // Check if the pointee types are compatible ignoring the sign.
9018 // We explicitly check for char so that we catch "char" vs
9019 // "unsigned char" on systems where "char" is unsigned.
9020 if (lhptee->isCharType())
9021 ltrans = S.Context.UnsignedCharTy;
9022 else if (lhptee->hasSignedIntegerRepresentation())
9023 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9024
9025 if (rhptee->isCharType())
9026 rtrans = S.Context.UnsignedCharTy;
9027 else if (rhptee->hasSignedIntegerRepresentation())
9028 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9029
9030 if (ltrans == rtrans) {
9031 // Types are compatible ignoring the sign. Qualifier incompatibility
9032 // takes priority over sign incompatibility because the sign
9033 // warning can be disabled.
9034 if (ConvTy != Sema::Compatible)
9035 return ConvTy;
9036
9038 }
9039
9040 // If we are a multi-level pointer, it's possible that our issue is simply
9041 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9042 // the eventual target type is the same and the pointers have the same
9043 // level of indirection, this must be the issue.
9044 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9045 do {
9046 std::tie(lhptee, lhq) =
9047 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9048 std::tie(rhptee, rhq) =
9049 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9050
9051 // Inconsistent address spaces at this point is invalid, even if the
9052 // address spaces would be compatible.
9053 // FIXME: This doesn't catch address space mismatches for pointers of
9054 // different nesting levels, like:
9055 // __local int *** a;
9056 // int ** b = a;
9057 // It's not clear how to actually determine when such pointers are
9058 // invalidly incompatible.
9059 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9061
9062 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9063
9064 if (lhptee == rhptee)
9066 }
9067
9068 // General pointer incompatibility takes priority over qualifiers.
9069 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9072 }
9073 if (!S.getLangOpts().CPlusPlus &&
9074 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9076 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9078 if (S.IsInvalidSMECallConversion(rtrans, ltrans))
9080 return ConvTy;
9081}
9082
9083/// checkBlockPointerTypesForAssignment - This routine determines whether two
9084/// block pointer types are compatible or whether a block and normal pointer
9085/// are compatible. It is more restrict than comparing two function pointer
9086// types.
9089 QualType RHSType) {
9090 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9091 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9092
9093 QualType lhptee, rhptee;
9094
9095 // get the "pointed to" type (ignoring qualifiers at the top level)
9096 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9097 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9098
9099 // In C++, the types have to match exactly.
9100 if (S.getLangOpts().CPlusPlus)
9102
9104
9105 // For blocks we enforce that qualifiers are identical.
9106 Qualifiers LQuals = lhptee.getLocalQualifiers();
9107 Qualifiers RQuals = rhptee.getLocalQualifiers();
9108 if (S.getLangOpts().OpenCL) {
9109 LQuals.removeAddressSpace();
9110 RQuals.removeAddressSpace();
9111 }
9112 if (LQuals != RQuals)
9114
9115 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9116 // assignment.
9117 // The current behavior is similar to C++ lambdas. A block might be
9118 // assigned to a variable iff its return type and parameters are compatible
9119 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9120 // an assignment. Presumably it should behave in way that a function pointer
9121 // assignment does in C, so for each parameter and return type:
9122 // * CVR and address space of LHS should be a superset of CVR and address
9123 // space of RHS.
9124 // * unqualified types should be compatible.
9125 if (S.getLangOpts().OpenCL) {
9127 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9128 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9130 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9132
9133 return ConvTy;
9134}
9135
9136/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9137/// for assignment compatibility.
9140 QualType RHSType) {
9141 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9142 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9143
9144 if (LHSType->isObjCBuiltinType()) {
9145 // Class is not compatible with ObjC object pointers.
9146 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9147 !RHSType->isObjCQualifiedClassType())
9149 return Sema::Compatible;
9150 }
9151 if (RHSType->isObjCBuiltinType()) {
9152 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9153 !LHSType->isObjCQualifiedClassType())
9155 return Sema::Compatible;
9156 }
9157 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9158 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9159
9160 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9161 // make an exception for id<P>
9162 !LHSType->isObjCQualifiedIdType())
9164
9165 if (S.Context.typesAreCompatible(LHSType, RHSType))
9166 return Sema::Compatible;
9167 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9170}
9171
9174 QualType LHSType, QualType RHSType) {
9175 // Fake up an opaque expression. We don't actually care about what
9176 // cast operations are required, so if CheckAssignmentConstraints
9177 // adds casts to this they'll be wasted, but fortunately that doesn't
9178 // usually happen on valid code.
9179 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9180 ExprResult RHSPtr = &RHSExpr;
9181 CastKind K;
9182
9183 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9184}
9185
9186/// This helper function returns true if QT is a vector type that has element
9187/// type ElementType.
9188static bool isVector(QualType QT, QualType ElementType) {
9189 if (const VectorType *VT = QT->getAs<VectorType>())
9190 return VT->getElementType().getCanonicalType() == ElementType;
9191 return false;
9192}
9193
9194/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9195/// has code to accommodate several GCC extensions when type checking
9196/// pointers. Here are some objectionable examples that GCC considers warnings:
9197///
9198/// int a, *pint;
9199/// short *pshort;
9200/// struct foo *pfoo;
9201///
9202/// pint = pshort; // warning: assignment from incompatible pointer type
9203/// a = pint; // warning: assignment makes integer from pointer without a cast
9204/// pint = a; // warning: assignment makes pointer from integer without a cast
9205/// pint = pfoo; // warning: assignment from incompatible pointer type
9206///
9207/// As a result, the code for dealing with pointers is more complex than the
9208/// C99 spec dictates.
9209///
9210/// Sets 'Kind' for any result kind except Incompatible.
9213 CastKind &Kind, bool ConvertRHS) {
9214 QualType RHSType = RHS.get()->getType();
9215 QualType OrigLHSType = LHSType;
9216
9217 // Get canonical types. We're not formatting these types, just comparing
9218 // them.
9219 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9220 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9221
9222 // Common case: no conversion required.
9223 if (LHSType == RHSType) {
9224 Kind = CK_NoOp;
9225 return Compatible;
9226 }
9227
9228 // If the LHS has an __auto_type, there are no additional type constraints
9229 // to be worried about.
9230 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9231 if (AT->isGNUAutoType()) {
9232 Kind = CK_NoOp;
9233 return Compatible;
9234 }
9235 }
9236
9237 // If we have an atomic type, try a non-atomic assignment, then just add an
9238 // atomic qualification step.
9239 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9241 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9242 if (result != Compatible)
9243 return result;
9244 if (Kind != CK_NoOp && ConvertRHS)
9245 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9246 Kind = CK_NonAtomicToAtomic;
9247 return Compatible;
9248 }
9249
9250 // If the left-hand side is a reference type, then we are in a
9251 // (rare!) case where we've allowed the use of references in C,
9252 // e.g., as a parameter type in a built-in function. In this case,
9253 // just make sure that the type referenced is compatible with the
9254 // right-hand side type. The caller is responsible for adjusting
9255 // LHSType so that the resulting expression does not have reference
9256 // type.
9257 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9258 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9259 Kind = CK_LValueBitCast;
9260 return Compatible;
9261 }
9262 return Incompatible;
9263 }
9264
9265 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9266 // to the same ExtVector type.
9267 if (LHSType->isExtVectorType()) {
9268 if (RHSType->isExtVectorType())
9269 return Incompatible;
9270 if (RHSType->isArithmeticType()) {
9271 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9272 if (ConvertRHS)
9273 RHS = prepareVectorSplat(LHSType, RHS.get());
9274 Kind = CK_VectorSplat;
9275 return Compatible;
9276 }
9277 }
9278
9279 // Conversions to or from vector type.
9280 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9281 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9282 // Allow assignments of an AltiVec vector type to an equivalent GCC
9283 // vector type and vice versa
9284 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9285 Kind = CK_BitCast;
9286 return Compatible;
9287 }
9288
9289 // If we are allowing lax vector conversions, and LHS and RHS are both
9290 // vectors, the total size only needs to be the same. This is a bitcast;
9291 // no bits are changed but the result type is different.
9292 if (isLaxVectorConversion(RHSType, LHSType)) {
9293 // The default for lax vector conversions with Altivec vectors will
9294 // change, so if we are converting between vector types where
9295 // at least one is an Altivec vector, emit a warning.
9296 if (Context.getTargetInfo().getTriple().isPPC() &&
9297 anyAltivecTypes(RHSType, LHSType) &&
9298 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9299 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9300 << RHSType << LHSType;
9301 Kind = CK_BitCast;
9302 return IncompatibleVectors;
9303 }
9304 }
9305
9306 // When the RHS comes from another lax conversion (e.g. binops between
9307 // scalars and vectors) the result is canonicalized as a vector. When the
9308 // LHS is also a vector, the lax is allowed by the condition above. Handle
9309 // the case where LHS is a scalar.
9310 if (LHSType->isScalarType()) {
9311 const VectorType *VecType = RHSType->getAs<VectorType>();
9312 if (VecType && VecType->getNumElements() == 1 &&
9313 isLaxVectorConversion(RHSType, LHSType)) {
9314 if (Context.getTargetInfo().getTriple().isPPC() &&
9316 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9318 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9319 << RHSType << LHSType;
9320 ExprResult *VecExpr = &RHS;
9321 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9322 Kind = CK_BitCast;
9323 return Compatible;
9324 }
9325 }
9326
9327 // Allow assignments between fixed-length and sizeless SVE vectors.
9328 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9329 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9330 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9331 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9332 Kind = CK_BitCast;
9333 return Compatible;
9334 }
9335
9336 // Allow assignments between fixed-length and sizeless RVV vectors.
9337 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9338 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9339 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9340 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9341 Kind = CK_BitCast;
9342 return Compatible;
9343 }
9344 }
9345
9346 return Incompatible;
9347 }
9348
9349 // Diagnose attempts to convert between __ibm128, __float128 and long double
9350 // where such conversions currently can't be handled.
9351 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9352 return Incompatible;
9353
9354 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9355 // discards the imaginary part.
9356 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9357 !LHSType->getAs<ComplexType>())
9358 return Incompatible;
9359
9360 // Arithmetic conversions.
9361 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9362 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9363 if (ConvertRHS)
9364 Kind = PrepareScalarCast(RHS, LHSType);
9365 return Compatible;
9366 }
9367
9368 // Conversions to normal pointers.
9369 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9370 // U* -> T*
9371 if (isa<PointerType>(RHSType)) {
9372 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9373 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9374 if (AddrSpaceL != AddrSpaceR)
9375 Kind = CK_AddressSpaceConversion;
9376 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9377 Kind = CK_NoOp;
9378 else
9379 Kind = CK_BitCast;
9380 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9381 RHS.get()->getBeginLoc());
9382 }
9383
9384 // int -> T*
9385 if (RHSType->isIntegerType()) {
9386 Kind = CK_IntegralToPointer; // FIXME: null?
9387 return IntToPointer;
9388 }
9389
9390 // C pointers are not compatible with ObjC object pointers,
9391 // with two exceptions:
9392 if (isa<ObjCObjectPointerType>(RHSType)) {
9393 // - conversions to void*
9394 if (LHSPointer->getPointeeType()->isVoidType()) {
9395 Kind = CK_BitCast;
9396 return Compatible;
9397 }
9398
9399 // - conversions from 'Class' to the redefinition type
9400 if (RHSType->isObjCClassType() &&
9401 Context.hasSameType(LHSType,
9403 Kind = CK_BitCast;
9404 return Compatible;
9405 }
9406
9407 Kind = CK_BitCast;
9408 return IncompatiblePointer;
9409 }
9410
9411 // U^ -> void*
9412 if (RHSType->getAs<BlockPointerType>()) {
9413 if (LHSPointer->getPointeeType()->isVoidType()) {
9414 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9415 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9416 ->getPointeeType()
9417 .getAddressSpace();
9418 Kind =
9419 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9420 return Compatible;
9421 }
9422 }
9423
9424 return Incompatible;
9425 }
9426
9427 // Conversions to block pointers.
9428 if (isa<BlockPointerType>(LHSType)) {
9429 // U^ -> T^
9430 if (RHSType->isBlockPointerType()) {
9431 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9432 ->getPointeeType()
9433 .getAddressSpace();
9434 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9435 ->getPointeeType()
9436 .getAddressSpace();
9437 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9438 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9439 }
9440
9441 // int or null -> T^
9442 if (RHSType->isIntegerType()) {
9443 Kind = CK_IntegralToPointer; // FIXME: null
9444 return IntToBlockPointer;
9445 }
9446
9447 // id -> T^
9448 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9449 Kind = CK_AnyPointerToBlockPointerCast;
9450 return Compatible;
9451 }
9452
9453 // void* -> T^
9454 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9455 if (RHSPT->getPointeeType()->isVoidType()) {
9456 Kind = CK_AnyPointerToBlockPointerCast;
9457 return Compatible;
9458 }
9459
9460 return Incompatible;
9461 }
9462
9463 // Conversions to Objective-C pointers.
9464 if (isa<ObjCObjectPointerType>(LHSType)) {
9465 // A* -> B*
9466 if (RHSType->isObjCObjectPointerType()) {
9467 Kind = CK_BitCast;
9469 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9470 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9471 result == Compatible &&
9472 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9473 result = IncompatibleObjCWeakRef;
9474 return result;
9475 }
9476
9477 // int or null -> A*
9478 if (RHSType->isIntegerType()) {
9479 Kind = CK_IntegralToPointer; // FIXME: null
9480 return IntToPointer;
9481 }
9482
9483 // In general, C pointers are not compatible with ObjC object pointers,
9484 // with two exceptions:
9485 if (isa<PointerType>(RHSType)) {
9486 Kind = CK_CPointerToObjCPointerCast;
9487
9488 // - conversions from 'void*'
9489 if (RHSType->isVoidPointerType()) {
9490 return Compatible;
9491 }
9492
9493 // - conversions to 'Class' from its redefinition type
9494 if (LHSType->isObjCClassType() &&
9495 Context.hasSameType(RHSType,
9497 return Compatible;
9498 }
9499
9500 return IncompatiblePointer;
9501 }
9502
9503 // Only under strict condition T^ is compatible with an Objective-C pointer.
9504 if (RHSType->isBlockPointerType() &&
9506 if (ConvertRHS)
9508 Kind = CK_BlockPointerToObjCPointerCast;
9509 return Compatible;
9510 }
9511
9512 return Incompatible;
9513 }
9514
9515 // Conversion to nullptr_t (C23 only)
9516 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9519 // null -> nullptr_t
9520 Kind = CK_NullToPointer;
9521 return Compatible;
9522 }
9523
9524 // Conversions from pointers that are not covered by the above.
9525 if (isa<PointerType>(RHSType)) {
9526 // T* -> _Bool
9527 if (LHSType == Context.BoolTy) {
9528 Kind = CK_PointerToBoolean;
9529 return Compatible;
9530 }
9531
9532 // T* -> int
9533 if (LHSType->isIntegerType()) {
9534 Kind = CK_PointerToIntegral;
9535 return PointerToInt;
9536 }
9537
9538 return Incompatible;
9539 }
9540
9541 // Conversions from Objective-C pointers that are not covered by the above.
9542 if (isa<ObjCObjectPointerType>(RHSType)) {
9543 // T* -> _Bool
9544 if (LHSType == Context.BoolTy) {
9545 Kind = CK_PointerToBoolean;
9546 return Compatible;
9547 }
9548
9549 // T* -> int
9550 if (LHSType->isIntegerType()) {
9551 Kind = CK_PointerToIntegral;
9552 return PointerToInt;
9553 }
9554
9555 return Incompatible;
9556 }
9557
9558 // struct A -> struct B
9559 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9560 if (Context.typesAreCompatible(LHSType, RHSType)) {
9561 Kind = CK_NoOp;
9562 return Compatible;
9563 }
9564 }
9565
9566 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9567 Kind = CK_IntToOCLSampler;
9568 return Compatible;
9569 }
9570
9571 return Incompatible;
9572}
9573
9574/// Constructs a transparent union from an expression that is
9575/// used to initialize the transparent union.
9577 ExprResult &EResult, QualType UnionType,
9578 FieldDecl *Field) {
9579 // Build an initializer list that designates the appropriate member
9580 // of the transparent union.
9581 Expr *E = EResult.get();
9583 E, SourceLocation());
9584 Initializer->setType(UnionType);
9585 Initializer->setInitializedFieldInUnion(Field);
9586
9587 // Build a compound literal constructing a value of the transparent
9588 // union type from this initializer list.
9589 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9590 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9591 VK_PRValue, Initializer, false);
9592}
9593
9596 ExprResult &RHS) {
9597 QualType RHSType = RHS.get()->getType();
9598
9599 // If the ArgType is a Union type, we want to handle a potential
9600 // transparent_union GCC extension.
9601 const RecordType *UT = ArgType->getAsUnionType();
9602 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9603 return Incompatible;
9604
9605 // The field to initialize within the transparent union.
9606 RecordDecl *UD = UT->getDecl();
9607 FieldDecl *InitField = nullptr;
9608 // It's compatible if the expression matches any of the fields.
9609 for (auto *it : UD->fields()) {
9610 if (it->getType()->isPointerType()) {
9611 // If the transparent union contains a pointer type, we allow:
9612 // 1) void pointer
9613 // 2) null pointer constant
9614 if (RHSType->isPointerType())
9615 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9616 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9617 InitField = it;
9618 break;
9619 }
9620
9623 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9624 CK_NullToPointer);
9625 InitField = it;
9626 break;
9627 }
9628 }
9629
9630 CastKind Kind;
9631 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9632 == Compatible) {
9633 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9634 InitField = it;
9635 break;
9636 }
9637 }
9638
9639 if (!InitField)
9640 return Incompatible;
9641
9642 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9643 return Compatible;
9644}
9645
9648 bool Diagnose,
9649 bool DiagnoseCFAudited,
9650 bool ConvertRHS) {
9651 // We need to be able to tell the caller whether we diagnosed a problem, if
9652 // they ask us to issue diagnostics.
9653 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9654
9655 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9656 // we can't avoid *all* modifications at the moment, so we need some somewhere
9657 // to put the updated value.
9658 ExprResult LocalRHS = CallerRHS;
9659 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9660
9661 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9662 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9663 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9664 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9665 Diag(RHS.get()->getExprLoc(),
9666 diag::warn_noderef_to_dereferenceable_pointer)
9667 << RHS.get()->getSourceRange();
9668 }
9669 }
9670 }
9671
9672 if (getLangOpts().CPlusPlus) {
9673 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9674 // C++ 5.17p3: If the left operand is not of class type, the
9675 // expression is implicitly converted (C++ 4) to the
9676 // cv-unqualified type of the left operand.
9677 QualType RHSType = RHS.get()->getType();
9678 if (Diagnose) {
9679 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9681 } else {
9684 /*SuppressUserConversions=*/false,
9685 AllowedExplicit::None,
9686 /*InOverloadResolution=*/false,
9687 /*CStyle=*/false,
9688 /*AllowObjCWritebackConversion=*/false);
9689 if (ICS.isFailure())
9690 return Incompatible;
9691 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9693 }
9694 if (RHS.isInvalid())
9695 return Incompatible;
9697 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9698 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9699 result = IncompatibleObjCWeakRef;
9700 return result;
9701 }
9702
9703 // FIXME: Currently, we fall through and treat C++ classes like C
9704 // structures.
9705 // FIXME: We also fall through for atomics; not sure what should
9706 // happen there, though.
9707 } else if (RHS.get()->getType() == Context.OverloadTy) {
9708 // As a set of extensions to C, we support overloading on functions. These
9709 // functions need to be resolved here.
9710 DeclAccessPair DAP;
9712 RHS.get(), LHSType, /*Complain=*/false, DAP))
9713 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9714 else
9715 return Incompatible;
9716 }
9717
9718 // This check seems unnatural, however it is necessary to ensure the proper
9719 // conversion of functions/arrays. If the conversion were done for all
9720 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9721 // expressions that suppress this implicit conversion (&, sizeof). This needs
9722 // to happen before we check for null pointer conversions because C does not
9723 // undergo the same implicit conversions as C++ does above (by the calls to
9724 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
9725 // lvalue to rvalue cast before checking for null pointer constraints. This
9726 // addresses code like: nullptr_t val; int *ptr; ptr = val;
9727 //
9728 // Suppress this for references: C++ 8.5.3p5.
9729 if (!LHSType->isReferenceType()) {
9730 // FIXME: We potentially allocate here even if ConvertRHS is false.
9732 if (RHS.isInvalid())
9733 return Incompatible;
9734 }
9735
9736 // The constraints are expressed in terms of the atomic, qualified, or
9737 // unqualified type of the LHS.
9738 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
9739
9740 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9741 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
9742 if ((LHSTypeAfterConversion->isPointerType() ||
9743 LHSTypeAfterConversion->isObjCObjectPointerType() ||
9744 LHSTypeAfterConversion->isBlockPointerType()) &&
9745 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
9748 if (Diagnose || ConvertRHS) {
9749 CastKind Kind;
9751 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9752 /*IgnoreBaseAccess=*/false, Diagnose);
9753 if (ConvertRHS)
9754 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9755 }
9756 return Compatible;
9757 }
9758 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
9759 // unqualified bool, and the right operand is a pointer or its type is
9760 // nullptr_t.
9761 if (getLangOpts().C23 && LHSType->isBooleanType() &&
9762 RHS.get()->getType()->isNullPtrType()) {
9763 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
9764 // only handles nullptr -> _Bool due to needing an extra conversion
9765 // step.
9766 // We model this by converting from nullptr -> void * and then let the
9767 // conversion from void * -> _Bool happen naturally.
9768 if (Diagnose || ConvertRHS) {
9769 CastKind Kind;
9772 /*IgnoreBaseAccess=*/false, Diagnose);
9773 if (ConvertRHS)
9774 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
9775 &Path);
9776 }
9777 }
9778
9779 // OpenCL queue_t type assignment.
9780 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9782 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9783 return Compatible;
9784 }
9785
9786 CastKind Kind;
9788 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9789
9790 // C99 6.5.16.1p2: The value of the right operand is converted to the
9791 // type of the assignment expression.
9792 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9793 // so that we can use references in built-in functions even in C.
9794 // The getNonReferenceType() call makes sure that the resulting expression
9795 // does not have reference type.
9796 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9798 Expr *E = RHS.get();
9799
9800 // Check for various Objective-C errors. If we are not reporting
9801 // diagnostics and just checking for errors, e.g., during overload
9802 // resolution, return Incompatible to indicate the failure.
9803 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9804 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
9806 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
9807 if (!Diagnose)
9808 return Incompatible;
9809 }
9810 if (getLangOpts().ObjC &&
9811 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9812 E->getType(), E, Diagnose) ||
9813 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9814 if (!Diagnose)
9815 return Incompatible;
9816 // Replace the expression with a corrected version and continue so we
9817 // can find further errors.
9818 RHS = E;
9819 return Compatible;
9820 }
9821
9822 if (ConvertRHS)
9823 RHS = ImpCastExprToType(E, Ty, Kind);
9824 }
9825
9826 return result;
9827}
9828
9829namespace {
9830/// The original operand to an operator, prior to the application of the usual
9831/// arithmetic conversions and converting the arguments of a builtin operator
9832/// candidate.
9833struct OriginalOperand {
9834 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9835 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9836 Op = MTE->getSubExpr();
9837 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9838 Op = BTE->getSubExpr();
9839 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9840 Orig = ICE->getSubExprAsWritten();
9841 Conversion = ICE->getConversionFunction();
9842 }
9843 }
9844
9845 QualType getType() const { return Orig->getType(); }
9846
9847 Expr *Orig;
9848 NamedDecl *Conversion;
9849};
9850}
9851
9853 ExprResult &RHS) {
9854 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9855
9856 Diag(Loc, diag::err_typecheck_invalid_operands)
9857 << OrigLHS.getType() << OrigRHS.getType()
9858 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9859
9860 // If a user-defined conversion was applied to either of the operands prior
9861 // to applying the built-in operator rules, tell the user about it.
9862 if (OrigLHS.Conversion) {
9863 Diag(OrigLHS.Conversion->getLocation(),
9864 diag::note_typecheck_invalid_operands_converted)
9865 << 0 << LHS.get()->getType();
9866 }
9867 if (OrigRHS.Conversion) {
9868 Diag(OrigRHS.Conversion->getLocation(),
9869 diag::note_typecheck_invalid_operands_converted)
9870 << 1 << RHS.get()->getType();
9871 }
9872
9873 return QualType();
9874}
9875
9877 ExprResult &RHS) {
9878 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9879 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9880
9881 bool LHSNatVec = LHSType->isVectorType();
9882 bool RHSNatVec = RHSType->isVectorType();
9883
9884 if (!(LHSNatVec && RHSNatVec)) {
9885 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9886 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9887 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9888 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9889 << Vector->getSourceRange();
9890 return QualType();
9891 }
9892
9893 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9894 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9895 << RHS.get()->getSourceRange();
9896
9897 return QualType();
9898}
9899
9900/// Try to convert a value of non-vector type to a vector type by converting
9901/// the type to the element type of the vector and then performing a splat.
9902/// If the language is OpenCL, we only use conversions that promote scalar
9903/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9904/// for float->int.
9905///
9906/// OpenCL V2.0 6.2.6.p2:
9907/// An error shall occur if any scalar operand type has greater rank
9908/// than the type of the vector element.
9909///
9910/// \param scalar - if non-null, actually perform the conversions
9911/// \return true if the operation fails (but without diagnosing the failure)
9913 QualType scalarTy,
9914 QualType vectorEltTy,
9915 QualType vectorTy,
9916 unsigned &DiagID) {
9917 // The conversion to apply to the scalar before splatting it,
9918 // if necessary.
9919 CastKind scalarCast = CK_NoOp;
9920
9921 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
9922 scalarCast = CK_IntegralToBoolean;
9923 } else if (vectorEltTy->isIntegralType(S.Context)) {
9924 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9925 (scalarTy->isIntegerType() &&
9926 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9927 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9928 return true;
9929 }
9930 if (!scalarTy->isIntegralType(S.Context))
9931 return true;
9932 scalarCast = CK_IntegralCast;
9933 } else if (vectorEltTy->isRealFloatingType()) {
9934 if (scalarTy->isRealFloatingType()) {
9935 if (S.getLangOpts().OpenCL &&
9936 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9937 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9938 return true;
9939 }
9940 scalarCast = CK_FloatingCast;
9941 }
9942 else if (scalarTy->isIntegralType(S.Context))
9943 scalarCast = CK_IntegralToFloating;
9944 else
9945 return true;
9946 } else {
9947 return true;
9948 }
9949
9950 // Adjust scalar if desired.
9951 if (scalar) {
9952 if (scalarCast != CK_NoOp)
9953 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9954 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9955 }
9956 return false;
9957}
9958
9959/// Convert vector E to a vector with the same number of elements but different
9960/// element type.
9961static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9962 const auto *VecTy = E->getType()->getAs<VectorType>();
9963 assert(VecTy && "Expression E must be a vector");
9964 QualType NewVecTy =
9965 VecTy->isExtVectorType()
9966 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
9967 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
9968 VecTy->getVectorKind());
9969
9970 // Look through the implicit cast. Return the subexpression if its type is
9971 // NewVecTy.
9972 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9973 if (ICE->getSubExpr()->getType() == NewVecTy)
9974 return ICE->getSubExpr();
9975
9976 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9977 return S.ImpCastExprToType(E, NewVecTy, Cast);
9978}
9979
9980/// Test if a (constant) integer Int can be casted to another integer type
9981/// IntTy without losing precision.
9983 QualType OtherIntTy) {
9984 if (Int->get()->containsErrors())
9985 return false;
9986
9987 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9988
9989 // Reject cases where the value of the Int is unknown as that would
9990 // possibly cause truncation, but accept cases where the scalar can be
9991 // demoted without loss of precision.
9992 Expr::EvalResult EVResult;
9993 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9994 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9995 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9996 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9997
9998 if (CstInt) {
9999 // If the scalar is constant and is of a higher order and has more active
10000 // bits that the vector element type, reject it.
10001 llvm::APSInt Result = EVResult.Val.getInt();
10002 unsigned NumBits = IntSigned
10003 ? (Result.isNegative() ? Result.getSignificantBits()
10004 : Result.getActiveBits())
10005 : Result.getActiveBits();
10006 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10007 return true;
10008
10009 // If the signedness of the scalar type and the vector element type
10010 // differs and the number of bits is greater than that of the vector
10011 // element reject it.
10012 return (IntSigned != OtherIntSigned &&
10013 NumBits > S.Context.getIntWidth(OtherIntTy));
10014 }
10015
10016 // Reject cases where the value of the scalar is not constant and it's
10017 // order is greater than that of the vector element type.
10018 return (Order < 0);
10019}
10020
10021/// Test if a (constant) integer Int can be casted to floating point type
10022/// FloatTy without losing precision.
10024 QualType FloatTy) {
10025 if (Int->get()->containsErrors())
10026 return false;
10027
10028 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10029
10030 // Determine if the integer constant can be expressed as a floating point
10031 // number of the appropriate type.
10032 Expr::EvalResult EVResult;
10033 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10034
10035 uint64_t Bits = 0;
10036 if (CstInt) {
10037 // Reject constants that would be truncated if they were converted to
10038 // the floating point type. Test by simple to/from conversion.
10039 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10040 // could be avoided if there was a convertFromAPInt method
10041 // which could signal back if implicit truncation occurred.
10042 llvm::APSInt Result = EVResult.Val.getInt();
10043 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10044 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10045 llvm::APFloat::rmTowardZero);
10046 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10048 bool Ignored = false;
10049 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10050 &Ignored);
10051 if (Result != ConvertBack)
10052 return true;
10053 } else {
10054 // Reject types that cannot be fully encoded into the mantissa of
10055 // the float.
10056 Bits = S.Context.getTypeSize(IntTy);
10057 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10058 S.Context.getFloatTypeSemantics(FloatTy));
10059 if (Bits > FloatPrec)
10060 return true;
10061 }
10062
10063 return false;
10064}
10065
10066/// Attempt to convert and splat Scalar into a vector whose types matches
10067/// Vector following GCC conversion rules. The rule is that implicit
10068/// conversion can occur when Scalar can be casted to match Vector's element
10069/// type without causing truncation of Scalar.
10071 ExprResult *Vector) {
10072 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10073 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10074 QualType VectorEltTy;
10075
10076 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10077 assert(!isa<ExtVectorType>(VT) &&
10078 "ExtVectorTypes should not be handled here!");
10079 VectorEltTy = VT->getElementType();
10080 } else if (VectorTy->isSveVLSBuiltinType()) {
10081 VectorEltTy =
10082 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10083 } else {
10084 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10085 }
10086
10087 // Reject cases where the vector element type or the scalar element type are
10088 // not integral or floating point types.
10089 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10090 return true;
10091
10092 // The conversion to apply to the scalar before splatting it,
10093 // if necessary.
10094 CastKind ScalarCast = CK_NoOp;
10095
10096 // Accept cases where the vector elements are integers and the scalar is
10097 // an integer.
10098 // FIXME: Notionally if the scalar was a floating point value with a precise
10099 // integral representation, we could cast it to an appropriate integer
10100 // type and then perform the rest of the checks here. GCC will perform
10101 // this conversion in some cases as determined by the input language.
10102 // We should accept it on a language independent basis.
10103 if (VectorEltTy->isIntegralType(S.Context) &&
10104 ScalarTy->isIntegralType(S.Context) &&
10105 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10106
10107 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10108 return true;
10109
10110 ScalarCast = CK_IntegralCast;
10111 } else if (VectorEltTy->isIntegralType(S.Context) &&
10112 ScalarTy->isRealFloatingType()) {
10113 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10114 ScalarCast = CK_FloatingToIntegral;
10115 else
10116 return true;
10117 } else if (VectorEltTy->isRealFloatingType()) {
10118 if (ScalarTy->isRealFloatingType()) {
10119
10120 // Reject cases where the scalar type is not a constant and has a higher
10121 // Order than the vector element type.
10122 llvm::APFloat Result(0.0);
10123
10124 // Determine whether this is a constant scalar. In the event that the
10125 // value is dependent (and thus cannot be evaluated by the constant
10126 // evaluator), skip the evaluation. This will then diagnose once the
10127 // expression is instantiated.
10128 bool CstScalar = Scalar->get()->isValueDependent() ||
10129 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10130 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10131 if (!CstScalar && Order < 0)
10132 return true;
10133
10134 // If the scalar cannot be safely casted to the vector element type,
10135 // reject it.
10136 if (CstScalar) {
10137 bool Truncated = false;
10138 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10139 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10140 if (Truncated)
10141 return true;
10142 }
10143
10144 ScalarCast = CK_FloatingCast;
10145 } else if (ScalarTy->isIntegralType(S.Context)) {
10146 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10147 return true;
10148
10149 ScalarCast = CK_IntegralToFloating;
10150 } else
10151 return true;
10152 } else if (ScalarTy->isEnumeralType())
10153 return true;
10154
10155 // Adjust scalar if desired.
10156 if (ScalarCast != CK_NoOp)
10157 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10158 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10159 return false;
10160}
10161
10163 SourceLocation Loc, bool IsCompAssign,
10164 bool AllowBothBool,
10165 bool AllowBoolConversions,
10166 bool AllowBoolOperation,
10167 bool ReportInvalid) {
10168 if (!IsCompAssign) {
10170 if (LHS.isInvalid())
10171 return QualType();
10172 }
10174 if (RHS.isInvalid())
10175 return QualType();
10176
10177 // For conversion purposes, we ignore any qualifiers.
10178 // For example, "const float" and "float" are equivalent.
10179 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10180 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10181
10182 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10183 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10184 assert(LHSVecType || RHSVecType);
10185
10186 if (getLangOpts().HLSL)
10187 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10188 IsCompAssign);
10189
10190 // Any operation with MFloat8 type is only possible with C intrinsics
10191 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10192 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10193 return InvalidOperands(Loc, LHS, RHS);
10194
10195 // AltiVec-style "vector bool op vector bool" combinations are allowed
10196 // for some operators but not others.
10197 if (!AllowBothBool && LHSVecType &&
10198 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10199 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10200 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10201
10202 // This operation may not be performed on boolean vectors.
10203 if (!AllowBoolOperation &&
10204 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10205 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10206
10207 // If the vector types are identical, return.
10208 if (Context.hasSameType(LHSType, RHSType))
10209 return Context.getCommonSugaredType(LHSType, RHSType);
10210
10211 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10212 if (LHSVecType && RHSVecType &&
10213 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10214 if (isa<ExtVectorType>(LHSVecType)) {
10215 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10216 return LHSType;
10217 }
10218
10219 if (!IsCompAssign)
10220 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10221 return RHSType;
10222 }
10223
10224 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10225 // can be mixed, with the result being the non-bool type. The non-bool
10226 // operand must have integer element type.
10227 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10228 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10229 (Context.getTypeSize(LHSVecType->getElementType()) ==
10230 Context.getTypeSize(RHSVecType->getElementType()))) {
10231 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10232 LHSVecType->getElementType()->isIntegerType() &&
10233 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10234 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10235 return LHSType;
10236 }
10237 if (!IsCompAssign &&
10238 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10239 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10240 RHSVecType->getElementType()->isIntegerType()) {
10241 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10242 return RHSType;
10243 }
10244 }
10245
10246 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10247 // invalid since the ambiguity can affect the ABI.
10248 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10249 unsigned &SVEorRVV) {
10250 const VectorType *VecType = SecondType->getAs<VectorType>();
10251 SVEorRVV = 0;
10252 if (FirstType->isSizelessBuiltinType() && VecType) {
10255 return true;
10261 SVEorRVV = 1;
10262 return true;
10263 }
10264 }
10265
10266 return false;
10267 };
10268
10269 unsigned SVEorRVV;
10270 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10271 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10272 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10273 << SVEorRVV << LHSType << RHSType;
10274 return QualType();
10275 }
10276
10277 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10278 // invalid since the ambiguity can affect the ABI.
10279 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10280 unsigned &SVEorRVV) {
10281 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10282 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10283
10284 SVEorRVV = 0;
10285 if (FirstVecType && SecondVecType) {
10286 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10287 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10288 SecondVecType->getVectorKind() ==
10290 return true;
10291 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10292 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10293 SecondVecType->getVectorKind() ==
10295 SecondVecType->getVectorKind() ==
10297 SecondVecType->getVectorKind() ==
10299 SVEorRVV = 1;
10300 return true;
10301 }
10302 }
10303 return false;
10304 }
10305
10306 if (SecondVecType &&
10307 SecondVecType->getVectorKind() == VectorKind::Generic) {
10308 if (FirstType->isSVESizelessBuiltinType())
10309 return true;
10310 if (FirstType->isRVVSizelessBuiltinType()) {
10311 SVEorRVV = 1;
10312 return true;
10313 }
10314 }
10315
10316 return false;
10317 };
10318
10319 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10320 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10321 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10322 << SVEorRVV << LHSType << RHSType;
10323 return QualType();
10324 }
10325
10326 // If there's a vector type and a scalar, try to convert the scalar to
10327 // the vector element type and splat.
10328 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10329 if (!RHSVecType) {
10330 if (isa<ExtVectorType>(LHSVecType)) {
10331 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10332 LHSVecType->getElementType(), LHSType,
10333 DiagID))
10334 return LHSType;
10335 } else {
10336 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10337 return LHSType;
10338 }
10339 }
10340 if (!LHSVecType) {
10341 if (isa<ExtVectorType>(RHSVecType)) {
10342 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10343 LHSType, RHSVecType->getElementType(),
10344 RHSType, DiagID))
10345 return RHSType;
10346 } else {
10347 if (LHS.get()->isLValue() ||
10348 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10349 return RHSType;
10350 }
10351 }
10352
10353 // FIXME: The code below also handles conversion between vectors and
10354 // non-scalars, we should break this down into fine grained specific checks
10355 // and emit proper diagnostics.
10356 QualType VecType = LHSVecType ? LHSType : RHSType;
10357 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10358 QualType OtherType = LHSVecType ? RHSType : LHSType;
10359 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10360 if (isLaxVectorConversion(OtherType, VecType)) {
10361 if (Context.getTargetInfo().getTriple().isPPC() &&
10362 anyAltivecTypes(RHSType, LHSType) &&
10363 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10364 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10365 // If we're allowing lax vector conversions, only the total (data) size
10366 // needs to be the same. For non compound assignment, if one of the types is
10367 // scalar, the result is always the vector type.
10368 if (!IsCompAssign) {
10369 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10370 return VecType;
10371 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10372 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10373 // type. Note that this is already done by non-compound assignments in
10374 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10375 // <1 x T> -> T. The result is also a vector type.
10376 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10377 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10378 ExprResult *RHSExpr = &RHS;
10379 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10380 return VecType;
10381 }
10382 }
10383
10384 // Okay, the expression is invalid.
10385
10386 // If there's a non-vector, non-real operand, diagnose that.
10387 if ((!RHSVecType && !RHSType->isRealType()) ||
10388 (!LHSVecType && !LHSType->isRealType())) {
10389 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10390 << LHSType << RHSType
10391 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10392 return QualType();
10393 }
10394
10395 // OpenCL V1.1 6.2.6.p1:
10396 // If the operands are of more than one vector type, then an error shall
10397 // occur. Implicit conversions between vector types are not permitted, per
10398 // section 6.2.1.
10399 if (getLangOpts().OpenCL &&
10400 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10401 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10402 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10403 << RHSType;
10404 return QualType();
10405 }
10406
10407
10408 // If there is a vector type that is not a ExtVector and a scalar, we reach
10409 // this point if scalar could not be converted to the vector's element type
10410 // without truncation.
10411 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10412 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10413 QualType Scalar = LHSVecType ? RHSType : LHSType;
10414 QualType Vector = LHSVecType ? LHSType : RHSType;
10415 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10416 Diag(Loc,
10417 diag::err_typecheck_vector_not_convertable_implict_truncation)
10418 << ScalarOrVector << Scalar << Vector;
10419
10420 return QualType();
10421 }
10422
10423 // Otherwise, use the generic diagnostic.
10424 Diag(Loc, DiagID)
10425 << LHSType << RHSType
10426 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10427 return QualType();
10428}
10429
10432 bool IsCompAssign,
10433 ArithConvKind OperationKind) {
10434 if (!IsCompAssign) {
10436 if (LHS.isInvalid())
10437 return QualType();
10438 }
10440 if (RHS.isInvalid())
10441 return QualType();
10442
10443 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10444 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10445
10446 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10447 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10448
10449 unsigned DiagID = diag::err_typecheck_invalid_operands;
10450 if ((OperationKind == ACK_Arithmetic) &&
10451 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10452 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10453 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10454 << RHS.get()->getSourceRange();
10455 return QualType();
10456 }
10457
10458 if (Context.hasSameType(LHSType, RHSType))
10459 return LHSType;
10460
10461 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10462 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10463 return LHSType;
10464 }
10465 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10466 if (LHS.get()->isLValue() ||
10467 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10468 return RHSType;
10469 }
10470
10471 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10472 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10473 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10474 << LHSType << RHSType << LHS.get()->getSourceRange()
10475 << RHS.get()->getSourceRange();
10476 return QualType();
10477 }
10478
10479 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10480 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10481 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10482 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10483 << LHSType << RHSType << LHS.get()->getSourceRange()
10484 << RHS.get()->getSourceRange();
10485 return QualType();
10486 }
10487
10488 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10489 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10490 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10491 bool ScalarOrVector =
10492 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10493
10494 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10495 << ScalarOrVector << Scalar << Vector;
10496
10497 return QualType();
10498 }
10499
10500 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10501 << RHS.get()->getSourceRange();
10502 return QualType();
10503}
10504
10505// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10506// expression. These are mainly cases where the null pointer is used as an
10507// integer instead of a pointer.
10509 SourceLocation Loc, bool IsCompare) {
10510 // The canonical way to check for a GNU null is with isNullPointerConstant,
10511 // but we use a bit of a hack here for speed; this is a relatively
10512 // hot path, and isNullPointerConstant is slow.
10513 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10514 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10515
10516 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10517
10518 // Avoid analyzing cases where the result will either be invalid (and
10519 // diagnosed as such) or entirely valid and not something to warn about.
10520 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10521 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10522 return;
10523
10524 // Comparison operations would not make sense with a null pointer no matter
10525 // what the other expression is.
10526 if (!IsCompare) {
10527 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10528 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10529 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10530 return;
10531 }
10532
10533 // The rest of the operations only make sense with a null pointer
10534 // if the other expression is a pointer.
10535 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10536 NonNullType->canDecayToPointerType())
10537 return;
10538
10539 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10540 << LHSNull /* LHS is NULL */ << NonNullType
10541 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10542}
10543
10546 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10547 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10548 if (!LUE || !RUE)
10549 return;
10550 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10551 RUE->getKind() != UETT_SizeOf)
10552 return;
10553
10554 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10555 QualType LHSTy = LHSArg->getType();
10556 QualType RHSTy;
10557
10558 if (RUE->isArgumentType())
10559 RHSTy = RUE->getArgumentType().getNonReferenceType();
10560 else
10561 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10562
10563 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10564 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10565 return;
10566
10567 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10568 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10569 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10570 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10571 << LHSArgDecl;
10572 }
10573 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10574 QualType ArrayElemTy = ArrayTy->getElementType();
10575 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10576 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10577 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10578 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10579 return;
10580 S.Diag(Loc, diag::warn_division_sizeof_array)
10581 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10582 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10583 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10584 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10585 << LHSArgDecl;
10586 }
10587
10588 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10589 }
10590}
10591
10593 ExprResult &RHS,
10594 SourceLocation Loc, bool IsDiv) {
10595 // Check for division/remainder by zero.
10596 Expr::EvalResult RHSValue;
10597 if (!RHS.get()->isValueDependent() &&
10598 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10599 RHSValue.Val.getInt() == 0)
10600 S.DiagRuntimeBehavior(Loc, RHS.get(),
10601 S.PDiag(diag::warn_remainder_division_by_zero)
10602 << IsDiv << RHS.get()->getSourceRange());
10603}
10604
10607 bool IsCompAssign, bool IsDiv) {
10608 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10609
10610 QualType LHSTy = LHS.get()->getType();
10611 QualType RHSTy = RHS.get()->getType();
10612 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10613 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10614 /*AllowBothBool*/ getLangOpts().AltiVec,
10615 /*AllowBoolConversions*/ false,
10616 /*AllowBooleanOperation*/ false,
10617 /*ReportInvalid*/ true);
10618 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10619 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10621 if (!IsDiv &&
10622 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10623 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10624 // For division, only matrix-by-scalar is supported. Other combinations with
10625 // matrix types are invalid.
10626 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10627 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10628
10630 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10631 if (LHS.isInvalid() || RHS.isInvalid())
10632 return QualType();
10633
10634
10635 if (compType.isNull() || !compType->isArithmeticType())
10636 return InvalidOperands(Loc, LHS, RHS);
10637 if (IsDiv) {
10638 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10639 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10640 }
10641 return compType;
10642}
10643
10645 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10646 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10647
10648 if (LHS.get()->getType()->isVectorType() ||
10649 RHS.get()->getType()->isVectorType()) {
10650 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10652 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10653 /*AllowBothBool*/ getLangOpts().AltiVec,
10654 /*AllowBoolConversions*/ false,
10655 /*AllowBooleanOperation*/ false,
10656 /*ReportInvalid*/ true);
10657 return InvalidOperands(Loc, LHS, RHS);
10658 }
10659
10660 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10661 RHS.get()->getType()->isSveVLSBuiltinType()) {
10662 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10664 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10666
10667 return InvalidOperands(Loc, LHS, RHS);
10668 }
10669
10671 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10672 if (LHS.isInvalid() || RHS.isInvalid())
10673 return QualType();
10674
10675 if (compType.isNull() || !compType->isIntegerType())
10676 return InvalidOperands(Loc, LHS, RHS);
10677 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10678 return compType;
10679}
10680
10681/// Diagnose invalid arithmetic on two void pointers.
10683 Expr *LHSExpr, Expr *RHSExpr) {
10684 S.Diag(Loc, S.getLangOpts().CPlusPlus
10685 ? diag::err_typecheck_pointer_arith_void_type
10686 : diag::ext_gnu_void_ptr)
10687 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10688 << RHSExpr->getSourceRange();
10689}
10690
10691/// Diagnose invalid arithmetic on a void pointer.
10693 Expr *Pointer) {
10694 S.Diag(Loc, S.getLangOpts().CPlusPlus
10695 ? diag::err_typecheck_pointer_arith_void_type
10696 : diag::ext_gnu_void_ptr)
10697 << 0 /* one pointer */ << Pointer->getSourceRange();
10698}
10699
10700/// Diagnose invalid arithmetic on a null pointer.
10701///
10702/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10703/// idiom, which we recognize as a GNU extension.
10704///
10706 Expr *Pointer, bool IsGNUIdiom) {
10707 if (IsGNUIdiom)
10708 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10709 << Pointer->getSourceRange();
10710 else
10711 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10712 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10713}
10714
10715/// Diagnose invalid subraction on a null pointer.
10716///
10718 Expr *Pointer, bool BothNull) {
10719 // Null - null is valid in C++ [expr.add]p7
10720 if (BothNull && S.getLangOpts().CPlusPlus)
10721 return;
10722
10723 // Is this s a macro from a system header?
10725 return;
10726
10728 S.PDiag(diag::warn_pointer_sub_null_ptr)
10729 << S.getLangOpts().CPlusPlus
10730 << Pointer->getSourceRange());
10731}
10732
10733/// Diagnose invalid arithmetic on two function pointers.
10735 Expr *LHS, Expr *RHS) {
10736 assert(LHS->getType()->isAnyPointerType());
10737 assert(RHS->getType()->isAnyPointerType());
10738 S.Diag(Loc, S.getLangOpts().CPlusPlus
10739 ? diag::err_typecheck_pointer_arith_function_type
10740 : diag::ext_gnu_ptr_func_arith)
10741 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10742 // We only show the second type if it differs from the first.
10744 RHS->getType())
10745 << RHS->getType()->getPointeeType()
10746 << LHS->getSourceRange() << RHS->getSourceRange();
10747}
10748
10749/// Diagnose invalid arithmetic on a function pointer.
10751 Expr *Pointer) {
10752 assert(Pointer->getType()->isAnyPointerType());
10753 S.Diag(Loc, S.getLangOpts().CPlusPlus
10754 ? diag::err_typecheck_pointer_arith_function_type
10755 : diag::ext_gnu_ptr_func_arith)
10756 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10757 << 0 /* one pointer, so only one type */
10758 << Pointer->getSourceRange();
10759}
10760
10761/// Emit error if Operand is incomplete pointer type
10762///
10763/// \returns True if pointer has incomplete type
10765 Expr *Operand) {
10766 QualType ResType = Operand->getType();
10767 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10768 ResType = ResAtomicType->getValueType();
10769
10770 assert(ResType->isAnyPointerType());
10771 QualType PointeeTy = ResType->getPointeeType();
10772 return S.RequireCompleteSizedType(
10773 Loc, PointeeTy,
10774 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10775 Operand->getSourceRange());
10776}
10777
10778/// Check the validity of an arithmetic pointer operand.
10779///
10780/// If the operand has pointer type, this code will check for pointer types
10781/// which are invalid in arithmetic operations. These will be diagnosed
10782/// appropriately, including whether or not the use is supported as an
10783/// extension.
10784///
10785/// \returns True when the operand is valid to use (even if as an extension).
10787 Expr *Operand) {
10788 QualType ResType = Operand->getType();
10789 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10790 ResType = ResAtomicType->getValueType();
10791
10792 if (!ResType->isAnyPointerType()) return true;
10793
10794 QualType PointeeTy = ResType->getPointeeType();
10795 if (PointeeTy->isVoidType()) {
10797 return !S.getLangOpts().CPlusPlus;
10798 }
10799 if (PointeeTy->isFunctionType()) {
10801 return !S.getLangOpts().CPlusPlus;
10802 }
10803
10804 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10805
10806 return true;
10807}
10808
10809/// Check the validity of a binary arithmetic operation w.r.t. pointer
10810/// operands.
10811///
10812/// This routine will diagnose any invalid arithmetic on pointer operands much
10813/// like \see checkArithmeticOpPointerOperand. However, it has special logic
10814/// for emitting a single diagnostic even for operations where both LHS and RHS
10815/// are (potentially problematic) pointers.
10816///
10817/// \returns True when the operand is valid to use (even if as an extension).
10819 Expr *LHSExpr, Expr *RHSExpr) {
10820 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10821 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10822 if (!isLHSPointer && !isRHSPointer) return true;
10823
10824 QualType LHSPointeeTy, RHSPointeeTy;
10825 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10826 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10827
10828 // if both are pointers check if operation is valid wrt address spaces
10829 if (isLHSPointer && isRHSPointer) {
10830 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
10831 S.getASTContext())) {
10832 S.Diag(Loc,
10833 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10834 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10835 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10836 return false;
10837 }
10838 }
10839
10840 // Check for arithmetic on pointers to incomplete types.
10841 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10842 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10843 if (isLHSVoidPtr || isRHSVoidPtr) {
10844 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10845 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10846 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10847
10848 return !S.getLangOpts().CPlusPlus;
10849 }
10850
10851 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10852 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10853 if (isLHSFuncPtr || isRHSFuncPtr) {
10854 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10855 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10856 RHSExpr);
10857 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10858
10859 return !S.getLangOpts().CPlusPlus;
10860 }
10861
10862 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10863 return false;
10864 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10865 return false;
10866
10867 return true;
10868}
10869
10870/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10871/// literal.
10873 Expr *LHSExpr, Expr *RHSExpr) {
10874 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10875 Expr* IndexExpr = RHSExpr;
10876 if (!StrExpr) {
10877 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10878 IndexExpr = LHSExpr;
10879 }
10880
10881 bool IsStringPlusInt = StrExpr &&
10883 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10884 return;
10885
10886 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10887 Self.Diag(OpLoc, diag::warn_string_plus_int)
10888 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10889
10890 // Only print a fixit for "str" + int, not for int + "str".
10891 if (IndexExpr == RHSExpr) {
10892 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10893 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10894 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10896 << FixItHint::CreateInsertion(EndLoc, "]");
10897 } else
10898 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10899}
10900
10901/// Emit a warning when adding a char literal to a string.
10903 Expr *LHSExpr, Expr *RHSExpr) {
10904 const Expr *StringRefExpr = LHSExpr;
10905 const CharacterLiteral *CharExpr =
10906 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10907
10908 if (!CharExpr) {
10909 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10910 StringRefExpr = RHSExpr;
10911 }
10912
10913 if (!CharExpr || !StringRefExpr)
10914 return;
10915
10916 const QualType StringType = StringRefExpr->getType();
10917
10918 // Return if not a PointerType.
10919 if (!StringType->isAnyPointerType())
10920 return;
10921
10922 // Return if not a CharacterType.
10923 if (!StringType->getPointeeType()->isAnyCharacterType())
10924 return;
10925
10926 ASTContext &Ctx = Self.getASTContext();
10927 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10928
10929 const QualType CharType = CharExpr->getType();
10930 if (!CharType->isAnyCharacterType() &&
10931 CharType->isIntegerType() &&
10932 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10933 Self.Diag(OpLoc, diag::warn_string_plus_char)
10934 << DiagRange << Ctx.CharTy;
10935 } else {
10936 Self.Diag(OpLoc, diag::warn_string_plus_char)
10937 << DiagRange << CharExpr->getType();
10938 }
10939
10940 // Only print a fixit for str + char, not for char + str.
10941 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10942 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10943 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10944 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10946 << FixItHint::CreateInsertion(EndLoc, "]");
10947 } else {
10948 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10949 }
10950}
10951
10952/// Emit error when two pointers are incompatible.
10954 Expr *LHSExpr, Expr *RHSExpr) {
10955 assert(LHSExpr->getType()->isAnyPointerType());
10956 assert(RHSExpr->getType()->isAnyPointerType());
10957 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10958 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10959 << RHSExpr->getSourceRange();
10960}
10961
10962// C99 6.5.6
10965 QualType* CompLHSTy) {
10966 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10967
10968 if (LHS.get()->getType()->isVectorType() ||
10969 RHS.get()->getType()->isVectorType()) {
10970 QualType compType =
10971 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
10972 /*AllowBothBool*/ getLangOpts().AltiVec,
10973 /*AllowBoolConversions*/ getLangOpts().ZVector,
10974 /*AllowBooleanOperation*/ false,
10975 /*ReportInvalid*/ true);
10976 if (CompLHSTy) *CompLHSTy = compType;
10977 return compType;
10978 }
10979
10980 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10981 RHS.get()->getType()->isSveVLSBuiltinType()) {
10982 QualType compType =
10983 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
10984 if (CompLHSTy)
10985 *CompLHSTy = compType;
10986 return compType;
10987 }
10988
10989 if (LHS.get()->getType()->isConstantMatrixType() ||
10990 RHS.get()->getType()->isConstantMatrixType()) {
10991 QualType compType =
10992 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10993 if (CompLHSTy)
10994 *CompLHSTy = compType;
10995 return compType;
10996 }
10997
10999 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11000 if (LHS.isInvalid() || RHS.isInvalid())
11001 return QualType();
11002
11003 // Diagnose "string literal" '+' int and string '+' "char literal".
11004 if (Opc == BO_Add) {
11005 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11006 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11007 }
11008
11009 // handle the common case first (both operands are arithmetic).
11010 if (!compType.isNull() && compType->isArithmeticType()) {
11011 if (CompLHSTy) *CompLHSTy = compType;
11012 return compType;
11013 }
11014
11015 // Type-checking. Ultimately the pointer's going to be in PExp;
11016 // note that we bias towards the LHS being the pointer.
11017 Expr *PExp = LHS.get(), *IExp = RHS.get();
11018
11019 bool isObjCPointer;
11020 if (PExp->getType()->isPointerType()) {
11021 isObjCPointer = false;
11022 } else if (PExp->getType()->isObjCObjectPointerType()) {
11023 isObjCPointer = true;
11024 } else {
11025 std::swap(PExp, IExp);
11026 if (PExp->getType()->isPointerType()) {
11027 isObjCPointer = false;
11028 } else if (PExp->getType()->isObjCObjectPointerType()) {
11029 isObjCPointer = true;
11030 } else {
11031 return InvalidOperands(Loc, LHS, RHS);
11032 }
11033 }
11034 assert(PExp->getType()->isAnyPointerType());
11035
11036 if (!IExp->getType()->isIntegerType())
11037 return InvalidOperands(Loc, LHS, RHS);
11038
11039 // Adding to a null pointer results in undefined behavior.
11042 // In C++ adding zero to a null pointer is defined.
11043 Expr::EvalResult KnownVal;
11044 if (!getLangOpts().CPlusPlus ||
11045 (!IExp->isValueDependent() &&
11046 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11047 KnownVal.Val.getInt() != 0))) {
11048 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11050 Context, BO_Add, PExp, IExp);
11051 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11052 }
11053 }
11054
11055 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11056 return QualType();
11057
11058 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11059 return QualType();
11060
11061 // Arithmetic on label addresses is normally allowed, except when we add
11062 // a ptrauth signature to the addresses.
11063 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
11064 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11065 << /*addition*/ 1;
11066 return QualType();
11067 }
11068
11069 // Check array bounds for pointer arithemtic
11070 CheckArrayAccess(PExp, IExp);
11071
11072 if (CompLHSTy) {
11074 if (LHSTy.isNull()) {
11075 LHSTy = LHS.get()->getType();
11077 LHSTy = Context.getPromotedIntegerType(LHSTy);
11078 }
11079 *CompLHSTy = LHSTy;
11080 }
11081
11082 return PExp->getType();
11083}
11084
11085// C99 6.5.6
11088 QualType* CompLHSTy) {
11089 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11090
11091 if (LHS.get()->getType()->isVectorType() ||
11092 RHS.get()->getType()->isVectorType()) {
11093 QualType compType =
11094 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11095 /*AllowBothBool*/ getLangOpts().AltiVec,
11096 /*AllowBoolConversions*/ getLangOpts().ZVector,
11097 /*AllowBooleanOperation*/ false,
11098 /*ReportInvalid*/ true);
11099 if (CompLHSTy) *CompLHSTy = compType;
11100 return compType;
11101 }
11102
11103 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11104 RHS.get()->getType()->isSveVLSBuiltinType()) {
11105 QualType compType =
11106 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11107 if (CompLHSTy)
11108 *CompLHSTy = compType;
11109 return compType;
11110 }
11111
11112 if (LHS.get()->getType()->isConstantMatrixType() ||
11113 RHS.get()->getType()->isConstantMatrixType()) {
11114 QualType compType =
11115 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11116 if (CompLHSTy)
11117 *CompLHSTy = compType;
11118 return compType;
11119 }
11120
11122 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11123 if (LHS.isInvalid() || RHS.isInvalid())
11124 return QualType();
11125
11126 // Enforce type constraints: C99 6.5.6p3.
11127
11128 // Handle the common case first (both operands are arithmetic).
11129 if (!compType.isNull() && compType->isArithmeticType()) {
11130 if (CompLHSTy) *CompLHSTy = compType;
11131 return compType;
11132 }
11133
11134 // Either ptr - int or ptr - ptr.
11135 if (LHS.get()->getType()->isAnyPointerType()) {
11136 QualType lpointee = LHS.get()->getType()->getPointeeType();
11137
11138 // Diagnose bad cases where we step over interface counts.
11139 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11140 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11141 return QualType();
11142
11143 // Arithmetic on label addresses is normally allowed, except when we add
11144 // a ptrauth signature to the addresses.
11145 if (isa<AddrLabelExpr>(LHS.get()) &&
11146 getLangOpts().PointerAuthIndirectGotos) {
11147 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11148 << /*subtraction*/ 0;
11149 return QualType();
11150 }
11151
11152 // The result type of a pointer-int computation is the pointer type.
11153 if (RHS.get()->getType()->isIntegerType()) {
11154 // Subtracting from a null pointer should produce a warning.
11155 // The last argument to the diagnose call says this doesn't match the
11156 // GNU int-to-pointer idiom.
11159 // In C++ adding zero to a null pointer is defined.
11160 Expr::EvalResult KnownVal;
11161 if (!getLangOpts().CPlusPlus ||
11162 (!RHS.get()->isValueDependent() &&
11163 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11164 KnownVal.Val.getInt() != 0))) {
11165 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11166 }
11167 }
11168
11169 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11170 return QualType();
11171
11172 // Check array bounds for pointer arithemtic
11173 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11174 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11175
11176 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11177 return LHS.get()->getType();
11178 }
11179
11180 // Handle pointer-pointer subtractions.
11181 if (const PointerType *RHSPTy
11182 = RHS.get()->getType()->getAs<PointerType>()) {
11183 QualType rpointee = RHSPTy->getPointeeType();
11184
11185 if (getLangOpts().CPlusPlus) {
11186 // Pointee types must be the same: C++ [expr.add]
11187 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11188 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11189 }
11190 } else {
11191 // Pointee types must be compatible C99 6.5.6p3
11195 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11196 return QualType();
11197 }
11198 }
11199
11201 LHS.get(), RHS.get()))
11202 return QualType();
11203
11204 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11206 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11208
11209 // Subtracting nullptr or from nullptr is suspect
11210 if (LHSIsNullPtr)
11211 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11212 if (RHSIsNullPtr)
11213 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11214
11215 // The pointee type may have zero size. As an extension, a structure or
11216 // union may have zero size or an array may have zero length. In this
11217 // case subtraction does not make sense.
11218 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11219 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11220 if (ElementSize.isZero()) {
11221 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11222 << rpointee.getUnqualifiedType()
11223 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11224 }
11225 }
11226
11227 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11228 return Context.getPointerDiffType();
11229 }
11230 }
11231
11232 return InvalidOperands(Loc, LHS, RHS);
11233}
11234
11236 if (const EnumType *ET = T->getAs<EnumType>())
11237 return ET->getDecl()->isScoped();
11238 return false;
11239}
11240
11243 QualType LHSType) {
11244 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11245 // so skip remaining warnings as we don't want to modify values within Sema.
11246 if (S.getLangOpts().OpenCL)
11247 return;
11248
11249 // Check right/shifter operand
11250 Expr::EvalResult RHSResult;
11251 if (RHS.get()->isValueDependent() ||
11252 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11253 return;
11254 llvm::APSInt Right = RHSResult.Val.getInt();
11255
11256 if (Right.isNegative()) {
11257 S.DiagRuntimeBehavior(Loc, RHS.get(),
11258 S.PDiag(diag::warn_shift_negative)
11259 << RHS.get()->getSourceRange());
11260 return;
11261 }
11262
11263 QualType LHSExprType = LHS.get()->getType();
11264 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11265 if (LHSExprType->isBitIntType())
11266 LeftSize = S.Context.getIntWidth(LHSExprType);
11267 else if (LHSExprType->isFixedPointType()) {
11268 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11269 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11270 }
11271 if (Right.uge(LeftSize)) {
11272 S.DiagRuntimeBehavior(Loc, RHS.get(),
11273 S.PDiag(diag::warn_shift_gt_typewidth)
11274 << RHS.get()->getSourceRange());
11275 return;
11276 }
11277
11278 // FIXME: We probably need to handle fixed point types specially here.
11279 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11280 return;
11281
11282 // When left shifting an ICE which is signed, we can check for overflow which
11283 // according to C++ standards prior to C++2a has undefined behavior
11284 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11285 // more than the maximum value representable in the result type, so never
11286 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11287 // expression is still probably a bug.)
11288 Expr::EvalResult LHSResult;
11289 if (LHS.get()->isValueDependent() ||
11291 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11292 return;
11293 llvm::APSInt Left = LHSResult.Val.getInt();
11294
11295 // Don't warn if signed overflow is defined, then all the rest of the
11296 // diagnostics will not be triggered because the behavior is defined.
11297 // Also don't warn in C++20 mode (and newer), as signed left shifts
11298 // always wrap and never overflow.
11299 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11300 return;
11301
11302 // If LHS does not have a non-negative value then, the
11303 // behavior is undefined before C++2a. Warn about it.
11304 if (Left.isNegative()) {
11305 S.DiagRuntimeBehavior(Loc, LHS.get(),
11306 S.PDiag(diag::warn_shift_lhs_negative)
11307 << LHS.get()->getSourceRange());
11308 return;
11309 }
11310
11311 llvm::APInt ResultBits =
11312 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11313 if (ResultBits.ule(LeftSize))
11314 return;
11315 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11316 Result = Result.shl(Right);
11317
11318 // Print the bit representation of the signed integer as an unsigned
11319 // hexadecimal number.
11320 SmallString<40> HexResult;
11321 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11322
11323 // If we are only missing a sign bit, this is less likely to result in actual
11324 // bugs -- if the result is cast back to an unsigned type, it will have the
11325 // expected value. Thus we place this behind a different warning that can be
11326 // turned off separately if needed.
11327 if (ResultBits - 1 == LeftSize) {
11328 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11329 << HexResult << LHSType
11330 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11331 return;
11332 }
11333
11334 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11335 << HexResult.str() << Result.getSignificantBits() << LHSType
11336 << Left.getBitWidth() << LHS.get()->getSourceRange()
11337 << RHS.get()->getSourceRange();
11338}
11339
11340/// Return the resulting type when a vector is shifted
11341/// by a scalar or vector shift amount.
11343 SourceLocation Loc, bool IsCompAssign) {
11344 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11345 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11346 !LHS.get()->getType()->isVectorType()) {
11347 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11348 << RHS.get()->getType() << LHS.get()->getType()
11349 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11350 return QualType();
11351 }
11352
11353 if (!IsCompAssign) {
11354 LHS = S.UsualUnaryConversions(LHS.get());
11355 if (LHS.isInvalid()) return QualType();
11356 }
11357
11358 RHS = S.UsualUnaryConversions(RHS.get());
11359 if (RHS.isInvalid()) return QualType();
11360
11361 QualType LHSType = LHS.get()->getType();
11362 // Note that LHS might be a scalar because the routine calls not only in
11363 // OpenCL case.
11364 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11365 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11366
11367 // Note that RHS might not be a vector.
11368 QualType RHSType = RHS.get()->getType();
11369 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11370 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11371
11372 // Do not allow shifts for boolean vectors.
11373 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11374 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11375 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11376 << LHS.get()->getType() << RHS.get()->getType()
11377 << LHS.get()->getSourceRange();
11378 return QualType();
11379 }
11380
11381 // The operands need to be integers.
11382 if (!LHSEleType->isIntegerType()) {
11383 S.Diag(Loc, diag::err_typecheck_expect_int)
11384 << LHS.get()->getType() << LHS.get()->getSourceRange();
11385 return QualType();
11386 }
11387
11388 if (!RHSEleType->isIntegerType()) {
11389 S.Diag(Loc, diag::err_typecheck_expect_int)
11390 << RHS.get()->getType() << RHS.get()->getSourceRange();
11391 return QualType();
11392 }
11393
11394 if (!LHSVecTy) {
11395 assert(RHSVecTy);
11396 if (IsCompAssign)
11397 return RHSType;
11398 if (LHSEleType != RHSEleType) {
11399 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11400 LHSEleType = RHSEleType;
11401 }
11402 QualType VecTy =
11403 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11404 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11405 LHSType = VecTy;
11406 } else if (RHSVecTy) {
11407 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11408 // are applied component-wise. So if RHS is a vector, then ensure
11409 // that the number of elements is the same as LHS...
11410 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11411 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11412 << LHS.get()->getType() << RHS.get()->getType()
11413 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11414 return QualType();
11415 }
11416 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11417 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11418 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11419 if (LHSBT != RHSBT &&
11420 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11421 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11422 << LHS.get()->getType() << RHS.get()->getType()
11423 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11424 }
11425 }
11426 } else {
11427 // ...else expand RHS to match the number of elements in LHS.
11428 QualType VecTy =
11429 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11430 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11431 }
11432
11433 return LHSType;
11434}
11435
11438 bool IsCompAssign) {
11439 if (!IsCompAssign) {
11440 LHS = S.UsualUnaryConversions(LHS.get());
11441 if (LHS.isInvalid())
11442 return QualType();
11443 }
11444
11445 RHS = S.UsualUnaryConversions(RHS.get());
11446 if (RHS.isInvalid())
11447 return QualType();
11448
11449 QualType LHSType = LHS.get()->getType();
11450 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11451 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11452 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11453 : LHSType;
11454
11455 // Note that RHS might not be a vector
11456 QualType RHSType = RHS.get()->getType();
11457 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11458 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11459 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11460 : RHSType;
11461
11462 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11463 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11464 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11465 << LHSType << RHSType << LHS.get()->getSourceRange();
11466 return QualType();
11467 }
11468
11469 if (!LHSEleType->isIntegerType()) {
11470 S.Diag(Loc, diag::err_typecheck_expect_int)
11471 << LHS.get()->getType() << LHS.get()->getSourceRange();
11472 return QualType();
11473 }
11474
11475 if (!RHSEleType->isIntegerType()) {
11476 S.Diag(Loc, diag::err_typecheck_expect_int)
11477 << RHS.get()->getType() << RHS.get()->getSourceRange();
11478 return QualType();
11479 }
11480
11481 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11482 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11483 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11484 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11485 << LHSType << RHSType << LHS.get()->getSourceRange()
11486 << RHS.get()->getSourceRange();
11487 return QualType();
11488 }
11489
11490 if (!LHSType->isSveVLSBuiltinType()) {
11491 assert(RHSType->isSveVLSBuiltinType());
11492 if (IsCompAssign)
11493 return RHSType;
11494 if (LHSEleType != RHSEleType) {
11495 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11496 LHSEleType = RHSEleType;
11497 }
11498 const llvm::ElementCount VecSize =
11499 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11500 QualType VecTy =
11501 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11502 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11503 LHSType = VecTy;
11504 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11505 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11506 S.Context.getTypeSize(LHSBuiltinTy)) {
11507 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11508 << LHSType << RHSType << LHS.get()->getSourceRange()
11509 << RHS.get()->getSourceRange();
11510 return QualType();
11511 }
11512 } else {
11513 const llvm::ElementCount VecSize =
11514 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11515 if (LHSEleType != RHSEleType) {
11516 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11517 RHSEleType = LHSEleType;
11518 }
11519 QualType VecTy =
11520 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11521 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11522 }
11523
11524 return LHSType;
11525}
11526
11527// C99 6.5.7
11530 bool IsCompAssign) {
11531 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11532
11533 // Vector shifts promote their scalar inputs to vector type.
11534 if (LHS.get()->getType()->isVectorType() ||
11535 RHS.get()->getType()->isVectorType()) {
11536 if (LangOpts.ZVector) {
11537 // The shift operators for the z vector extensions work basically
11538 // like general shifts, except that neither the LHS nor the RHS is
11539 // allowed to be a "vector bool".
11540 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11541 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11542 return InvalidOperands(Loc, LHS, RHS);
11543 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11544 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11545 return InvalidOperands(Loc, LHS, RHS);
11546 }
11547 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11548 }
11549
11550 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11551 RHS.get()->getType()->isSveVLSBuiltinType())
11552 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11553
11554 // Shifts don't perform usual arithmetic conversions, they just do integer
11555 // promotions on each operand. C99 6.5.7p3
11556
11557 // For the LHS, do usual unary conversions, but then reset them away
11558 // if this is a compound assignment.
11559 ExprResult OldLHS = LHS;
11560 LHS = UsualUnaryConversions(LHS.get());
11561 if (LHS.isInvalid())
11562 return QualType();
11563 QualType LHSType = LHS.get()->getType();
11564 if (IsCompAssign) LHS = OldLHS;
11565
11566 // The RHS is simpler.
11567 RHS = UsualUnaryConversions(RHS.get());
11568 if (RHS.isInvalid())
11569 return QualType();
11570 QualType RHSType = RHS.get()->getType();
11571
11572 // C99 6.5.7p2: Each of the operands shall have integer type.
11573 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11574 if ((!LHSType->isFixedPointOrIntegerType() &&
11575 !LHSType->hasIntegerRepresentation()) ||
11576 !RHSType->hasIntegerRepresentation())
11577 return InvalidOperands(Loc, LHS, RHS);
11578
11579 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11580 // hasIntegerRepresentation() above instead of this.
11581 if (isScopedEnumerationType(LHSType) ||
11582 isScopedEnumerationType(RHSType)) {
11583 return InvalidOperands(Loc, LHS, RHS);
11584 }
11585 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11586
11587 // "The type of the result is that of the promoted left operand."
11588 return LHSType;
11589}
11590
11591/// Diagnose bad pointer comparisons.
11593 ExprResult &LHS, ExprResult &RHS,
11594 bool IsError) {
11595 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11596 : diag::ext_typecheck_comparison_of_distinct_pointers)
11597 << LHS.get()->getType() << RHS.get()->getType()
11598 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11599}
11600
11601/// Returns false if the pointers are converted to a composite type,
11602/// true otherwise.
11604 ExprResult &LHS, ExprResult &RHS) {
11605 // C++ [expr.rel]p2:
11606 // [...] Pointer conversions (4.10) and qualification
11607 // conversions (4.4) are performed on pointer operands (or on
11608 // a pointer operand and a null pointer constant) to bring
11609 // them to their composite pointer type. [...]
11610 //
11611 // C++ [expr.eq]p1 uses the same notion for (in)equality
11612 // comparisons of pointers.
11613
11614 QualType LHSType = LHS.get()->getType();
11615 QualType RHSType = RHS.get()->getType();
11616 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11617 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11618
11619 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11620 if (T.isNull()) {
11621 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11622 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11623 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11624 else
11625 S.InvalidOperands(Loc, LHS, RHS);
11626 return true;
11627 }
11628
11629 return false;
11630}
11631
11633 ExprResult &LHS,
11634 ExprResult &RHS,
11635 bool IsError) {
11636 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11637 : diag::ext_typecheck_comparison_of_fptr_to_void)
11638 << LHS.get()->getType() << RHS.get()->getType()
11639 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11640}
11641
11643 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11644 case Stmt::ObjCArrayLiteralClass:
11645 case Stmt::ObjCDictionaryLiteralClass:
11646 case Stmt::ObjCStringLiteralClass:
11647 case Stmt::ObjCBoxedExprClass:
11648 return true;
11649 default:
11650 // Note that ObjCBoolLiteral is NOT an object literal!
11651 return false;
11652 }
11653}
11654
11655static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11658
11659 // If this is not actually an Objective-C object, bail out.
11660 if (!Type)
11661 return false;
11662
11663 // Get the LHS object's interface type.
11664 QualType InterfaceType = Type->getPointeeType();
11665
11666 // If the RHS isn't an Objective-C object, bail out.
11667 if (!RHS->getType()->isObjCObjectPointerType())
11668 return false;
11669
11670 // Try to find the -isEqual: method.
11671 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
11672 ObjCMethodDecl *Method =
11673 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
11674 /*IsInstance=*/true);
11675 if (!Method) {
11676 if (Type->isObjCIdType()) {
11677 // For 'id', just check the global pool.
11678 Method =
11680 /*receiverId=*/true);
11681 } else {
11682 // Check protocols.
11683 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
11684 /*IsInstance=*/true);
11685 }
11686 }
11687
11688 if (!Method)
11689 return false;
11690
11691 QualType T = Method->parameters()[0]->getType();
11692 if (!T->isObjCObjectPointerType())
11693 return false;
11694
11695 QualType R = Method->getReturnType();
11696 if (!R->isScalarType())
11697 return false;
11698
11699 return true;
11700}
11701
11703 ExprResult &LHS, ExprResult &RHS,
11705 Expr *Literal;
11706 Expr *Other;
11707 if (isObjCObjectLiteral(LHS)) {
11708 Literal = LHS.get();
11709 Other = RHS.get();
11710 } else {
11711 Literal = RHS.get();
11712 Other = LHS.get();
11713 }
11714
11715 // Don't warn on comparisons against nil.
11716 Other = Other->IgnoreParenCasts();
11717 if (Other->isNullPointerConstant(S.getASTContext(),
11719 return;
11720
11721 // This should be kept in sync with warn_objc_literal_comparison.
11722 // LK_String should always be after the other literals, since it has its own
11723 // warning flag.
11724 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
11725 assert(LiteralKind != SemaObjC::LK_Block);
11726 if (LiteralKind == SemaObjC::LK_None) {
11727 llvm_unreachable("Unknown Objective-C object literal kind");
11728 }
11729
11730 if (LiteralKind == SemaObjC::LK_String)
11731 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11732 << Literal->getSourceRange();
11733 else
11734 S.Diag(Loc, diag::warn_objc_literal_comparison)
11735 << LiteralKind << Literal->getSourceRange();
11736
11738 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11739 SourceLocation Start = LHS.get()->getBeginLoc();
11741 CharSourceRange OpRange =
11743
11744 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11745 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11746 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11747 << FixItHint::CreateInsertion(End, "]");
11748 }
11749}
11750
11751/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11754 BinaryOperatorKind Opc) {
11755 // Check that left hand side is !something.
11756 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11757 if (!UO || UO->getOpcode() != UO_LNot) return;
11758
11759 // Only check if the right hand side is non-bool arithmetic type.
11760 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11761
11762 // Make sure that the something in !something is not bool.
11763 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11764 if (SubExpr->isKnownToHaveBooleanValue()) return;
11765
11766 // Emit warning.
11767 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11768 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11769 << Loc << IsBitwiseOp;
11770
11771 // First note suggest !(x < y)
11772 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11773 SourceLocation FirstClose = RHS.get()->getEndLoc();
11774 FirstClose = S.getLocForEndOfToken(FirstClose);
11775 if (FirstClose.isInvalid())
11776 FirstOpen = SourceLocation();
11777 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11778 << IsBitwiseOp
11779 << FixItHint::CreateInsertion(FirstOpen, "(")
11780 << FixItHint::CreateInsertion(FirstClose, ")");
11781
11782 // Second note suggests (!x) < y
11783 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11784 SourceLocation SecondClose = LHS.get()->getEndLoc();
11785 SecondClose = S.getLocForEndOfToken(SecondClose);
11786 if (SecondClose.isInvalid())
11787 SecondOpen = SourceLocation();
11788 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11789 << FixItHint::CreateInsertion(SecondOpen, "(")
11790 << FixItHint::CreateInsertion(SecondClose, ")");
11791}
11792
11793// Returns true if E refers to a non-weak array.
11794static bool checkForArray(const Expr *E) {
11795 const ValueDecl *D = nullptr;
11796 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11797 D = DR->getDecl();
11798 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11799 if (Mem->isImplicitAccess())
11800 D = Mem->getMemberDecl();
11801 }
11802 if (!D)
11803 return false;
11804 return D->getType()->isArrayType() && !D->isWeak();
11805}
11806
11807/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
11808/// pointer and size is an unsigned integer. Return whether the result is
11809/// always true/false.
11810static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
11811 const Expr *RHS,
11812 BinaryOperatorKind Opc) {
11813 if (!LHS->getType()->isPointerType() ||
11814 S.getLangOpts().PointerOverflowDefined)
11815 return std::nullopt;
11816
11817 // Canonicalize to >= or < predicate.
11818 switch (Opc) {
11819 case BO_GE:
11820 case BO_LT:
11821 break;
11822 case BO_GT:
11823 std::swap(LHS, RHS);
11824 Opc = BO_LT;
11825 break;
11826 case BO_LE:
11827 std::swap(LHS, RHS);
11828 Opc = BO_GE;
11829 break;
11830 default:
11831 return std::nullopt;
11832 }
11833
11834 auto *BO = dyn_cast<BinaryOperator>(LHS);
11835 if (!BO || BO->getOpcode() != BO_Add)
11836 return std::nullopt;
11837
11838 Expr *Other;
11839 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
11840 Other = BO->getRHS();
11841 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
11842 Other = BO->getLHS();
11843 else
11844 return std::nullopt;
11845
11846 if (!Other->getType()->isUnsignedIntegerType())
11847 return std::nullopt;
11848
11849 return Opc == BO_GE;
11850}
11851
11852/// Diagnose some forms of syntactically-obvious tautological comparison.
11854 Expr *LHS, Expr *RHS,
11855 BinaryOperatorKind Opc) {
11856 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11857 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11858
11859 QualType LHSType = LHS->getType();
11860 QualType RHSType = RHS->getType();
11861 if (LHSType->hasFloatingRepresentation() ||
11862 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11864 return;
11865
11866 // WebAssembly Tables cannot be compared, therefore shouldn't emit
11867 // Tautological diagnostics.
11868 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
11869 return;
11870
11871 // Comparisons between two array types are ill-formed for operator<=>, so
11872 // we shouldn't emit any additional warnings about it.
11873 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11874 return;
11875
11876 // For non-floating point types, check for self-comparisons of the form
11877 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11878 // often indicate logic errors in the program.
11879 //
11880 // NOTE: Don't warn about comparison expressions resulting from macro
11881 // expansion. Also don't warn about comparisons which are only self
11882 // comparisons within a template instantiation. The warnings should catch
11883 // obvious cases in the definition of the template anyways. The idea is to
11884 // warn when the typed comparison operator will always evaluate to the same
11885 // result.
11886
11887 // Used for indexing into %select in warn_comparison_always
11888 enum {
11889 AlwaysConstant,
11890 AlwaysTrue,
11891 AlwaysFalse,
11892 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11893 };
11894
11895 // C++1a [array.comp]:
11896 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11897 // operands of array type.
11898 // C++2a [depr.array.comp]:
11899 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11900 // operands of array type are deprecated.
11901 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
11902 RHSStripped->getType()->isArrayType()) {
11903 auto IsDeprArrayComparionIgnored =
11904 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
11905 auto DiagID = S.getLangOpts().CPlusPlus26
11906 ? diag::warn_array_comparison_cxx26
11907 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
11908 ? diag::warn_array_comparison
11909 : diag::warn_depr_array_comparison;
11910 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
11911 << LHSStripped->getType() << RHSStripped->getType();
11912 // Carry on to produce the tautological comparison warning, if this
11913 // expression is potentially-evaluated, we can resolve the array to a
11914 // non-weak declaration, and so on.
11915 }
11916
11917 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11918 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11919 unsigned Result;
11920 switch (Opc) {
11921 case BO_EQ:
11922 case BO_LE:
11923 case BO_GE:
11924 Result = AlwaysTrue;
11925 break;
11926 case BO_NE:
11927 case BO_LT:
11928 case BO_GT:
11929 Result = AlwaysFalse;
11930 break;
11931 case BO_Cmp:
11932 Result = AlwaysEqual;
11933 break;
11934 default:
11935 Result = AlwaysConstant;
11936 break;
11937 }
11938 S.DiagRuntimeBehavior(Loc, nullptr,
11939 S.PDiag(diag::warn_comparison_always)
11940 << 0 /*self-comparison*/
11941 << Result);
11942 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11943 // What is it always going to evaluate to?
11944 unsigned Result;
11945 switch (Opc) {
11946 case BO_EQ: // e.g. array1 == array2
11947 Result = AlwaysFalse;
11948 break;
11949 case BO_NE: // e.g. array1 != array2
11950 Result = AlwaysTrue;
11951 break;
11952 default: // e.g. array1 <= array2
11953 // The best we can say is 'a constant'
11954 Result = AlwaysConstant;
11955 break;
11956 }
11957 S.DiagRuntimeBehavior(Loc, nullptr,
11958 S.PDiag(diag::warn_comparison_always)
11959 << 1 /*array comparison*/
11960 << Result);
11961 } else if (std::optional<bool> Res =
11962 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
11963 S.DiagRuntimeBehavior(Loc, nullptr,
11964 S.PDiag(diag::warn_comparison_always)
11965 << 2 /*pointer comparison*/
11966 << (*Res ? AlwaysTrue : AlwaysFalse));
11967 }
11968 }
11969
11970 if (isa<CastExpr>(LHSStripped))
11971 LHSStripped = LHSStripped->IgnoreParenCasts();
11972 if (isa<CastExpr>(RHSStripped))
11973 RHSStripped = RHSStripped->IgnoreParenCasts();
11974
11975 // Warn about comparisons against a string constant (unless the other
11976 // operand is null); the user probably wants string comparison function.
11977 Expr *LiteralString = nullptr;
11978 Expr *LiteralStringStripped = nullptr;
11979 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11980 !RHSStripped->isNullPointerConstant(S.Context,
11982 LiteralString = LHS;
11983 LiteralStringStripped = LHSStripped;
11984 } else if ((isa<StringLiteral>(RHSStripped) ||
11985 isa<ObjCEncodeExpr>(RHSStripped)) &&
11986 !LHSStripped->isNullPointerConstant(S.Context,
11988 LiteralString = RHS;
11989 LiteralStringStripped = RHSStripped;
11990 }
11991
11992 if (LiteralString) {
11993 S.DiagRuntimeBehavior(Loc, nullptr,
11994 S.PDiag(diag::warn_stringcompare)
11995 << isa<ObjCEncodeExpr>(LiteralStringStripped)
11996 << LiteralString->getSourceRange());
11997 }
11998}
11999
12001 switch (CK) {
12002 default: {
12003#ifndef NDEBUG
12004 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12005 << "\n";
12006#endif
12007 llvm_unreachable("unhandled cast kind");
12008 }
12009 case CK_UserDefinedConversion:
12010 return ICK_Identity;
12011 case CK_LValueToRValue:
12012 return ICK_Lvalue_To_Rvalue;
12013 case CK_ArrayToPointerDecay:
12014 return ICK_Array_To_Pointer;
12015 case CK_FunctionToPointerDecay:
12017 case CK_IntegralCast:
12019 case CK_FloatingCast:
12021 case CK_IntegralToFloating:
12022 case CK_FloatingToIntegral:
12023 return ICK_Floating_Integral;
12024 case CK_IntegralComplexCast:
12025 case CK_FloatingComplexCast:
12026 case CK_FloatingComplexToIntegralComplex:
12027 case CK_IntegralComplexToFloatingComplex:
12029 case CK_FloatingComplexToReal:
12030 case CK_FloatingRealToComplex:
12031 case CK_IntegralComplexToReal:
12032 case CK_IntegralRealToComplex:
12033 return ICK_Complex_Real;
12034 case CK_HLSLArrayRValue:
12035 return ICK_HLSL_Array_RValue;
12036 }
12037}
12038
12040 QualType FromType,
12042 // Check for a narrowing implicit conversion.
12045 SCS.setToType(0, FromType);
12046 SCS.setToType(1, ToType);
12047 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12048 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12049
12050 APValue PreNarrowingValue;
12051 QualType PreNarrowingType;
12052 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12053 PreNarrowingType,
12054 /*IgnoreFloatToIntegralConversion*/ true)) {
12056 // Implicit conversion to a narrower type, but the expression is
12057 // value-dependent so we can't tell whether it's actually narrowing.
12058 case NK_Not_Narrowing:
12059 return false;
12060
12062 // Implicit conversion to a narrower type, and the value is not a constant
12063 // expression.
12064 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12065 << /*Constant*/ 1
12066 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12067 return true;
12068
12070 // Implicit conversion to a narrower type, and the value is not a constant
12071 // expression.
12072 case NK_Type_Narrowing:
12073 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12074 << /*Constant*/ 0 << FromType << ToType;
12075 // TODO: It's not a constant expression, but what if the user intended it
12076 // to be? Can we produce notes to help them figure out why it isn't?
12077 return true;
12078 }
12079 llvm_unreachable("unhandled case in switch");
12080}
12081
12083 ExprResult &LHS,
12084 ExprResult &RHS,
12086 QualType LHSType = LHS.get()->getType();
12087 QualType RHSType = RHS.get()->getType();
12088 // Dig out the original argument type and expression before implicit casts
12089 // were applied. These are the types/expressions we need to check the
12090 // [expr.spaceship] requirements against.
12091 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12092 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12093 QualType LHSStrippedType = LHSStripped.get()->getType();
12094 QualType RHSStrippedType = RHSStripped.get()->getType();
12095
12096 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12097 // other is not, the program is ill-formed.
12098 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12099 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12100 return QualType();
12101 }
12102
12103 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12104 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12105 RHSStrippedType->isEnumeralType();
12106 if (NumEnumArgs == 1) {
12107 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12108 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12109 if (OtherTy->hasFloatingRepresentation()) {
12110 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12111 return QualType();
12112 }
12113 }
12114 if (NumEnumArgs == 2) {
12115 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12116 // type E, the operator yields the result of converting the operands
12117 // to the underlying type of E and applying <=> to the converted operands.
12118 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12119 S.InvalidOperands(Loc, LHS, RHS);
12120 return QualType();
12121 }
12122 QualType IntType =
12123 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12124 assert(IntType->isArithmeticType());
12125
12126 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12127 // promote the boolean type, and all other promotable integer types, to
12128 // avoid this.
12129 if (S.Context.isPromotableIntegerType(IntType))
12130 IntType = S.Context.getPromotedIntegerType(IntType);
12131
12132 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12133 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12134 LHSType = RHSType = IntType;
12135 }
12136
12137 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12138 // usual arithmetic conversions are applied to the operands.
12139 QualType Type =
12141 if (LHS.isInvalid() || RHS.isInvalid())
12142 return QualType();
12143 if (Type.isNull())
12144 return S.InvalidOperands(Loc, LHS, RHS);
12145
12146 std::optional<ComparisonCategoryType> CCT =
12148 if (!CCT)
12149 return S.InvalidOperands(Loc, LHS, RHS);
12150
12151 bool HasNarrowing = checkThreeWayNarrowingConversion(
12152 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12153 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12154 RHS.get()->getBeginLoc());
12155 if (HasNarrowing)
12156 return QualType();
12157
12158 assert(!Type.isNull() && "composite type for <=> has not been set");
12159
12162}
12163
12165 ExprResult &RHS,
12167 BinaryOperatorKind Opc) {
12168 if (Opc == BO_Cmp)
12169 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12170
12171 // C99 6.5.8p3 / C99 6.5.9p4
12172 QualType Type =
12174 if (LHS.isInvalid() || RHS.isInvalid())
12175 return QualType();
12176 if (Type.isNull())
12177 return S.InvalidOperands(Loc, LHS, RHS);
12178 assert(Type->isArithmeticType() || Type->isEnumeralType());
12179
12181 return S.InvalidOperands(Loc, LHS, RHS);
12182
12183 // Check for comparisons of floating point operands using != and ==.
12185 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12186
12187 // The result of comparisons is 'bool' in C++, 'int' in C.
12189}
12190
12192 if (!NullE.get()->getType()->isAnyPointerType())
12193 return;
12194 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12195 if (!E.get()->getType()->isAnyPointerType() &&
12199 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12200 if (CL->getValue() == 0)
12201 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12202 << NullValue
12204 NullValue ? "NULL" : "(void *)0");
12205 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12206 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12208 if (T == Context.CharTy)
12209 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12210 << NullValue
12212 NullValue ? "NULL" : "(void *)0");
12213 }
12214 }
12215}
12216
12217// C99 6.5.8, C++ [expr.rel]
12220 BinaryOperatorKind Opc) {
12221 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12222 bool IsThreeWay = Opc == BO_Cmp;
12223 bool IsOrdered = IsRelational || IsThreeWay;
12224 auto IsAnyPointerType = [](ExprResult E) {
12225 QualType Ty = E.get()->getType();
12226 return Ty->isPointerType() || Ty->isMemberPointerType();
12227 };
12228
12229 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12230 // type, array-to-pointer, ..., conversions are performed on both operands to
12231 // bring them to their composite type.
12232 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12233 // any type-related checks.
12234 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12236 if (LHS.isInvalid())
12237 return QualType();
12239 if (RHS.isInvalid())
12240 return QualType();
12241 } else {
12242 LHS = DefaultLvalueConversion(LHS.get());
12243 if (LHS.isInvalid())
12244 return QualType();
12245 RHS = DefaultLvalueConversion(RHS.get());
12246 if (RHS.isInvalid())
12247 return QualType();
12248 }
12249
12250 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12254 }
12255
12256 // Handle vector comparisons separately.
12257 if (LHS.get()->getType()->isVectorType() ||
12258 RHS.get()->getType()->isVectorType())
12259 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12260
12261 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12262 RHS.get()->getType()->isSveVLSBuiltinType())
12263 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12264
12265 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12266 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12267
12268 QualType LHSType = LHS.get()->getType();
12269 QualType RHSType = RHS.get()->getType();
12270 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12271 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12272 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12273
12274 if ((LHSType->isPointerType() &&
12276 (RHSType->isPointerType() &&
12278 return InvalidOperands(Loc, LHS, RHS);
12279
12280 const Expr::NullPointerConstantKind LHSNullKind =
12282 const Expr::NullPointerConstantKind RHSNullKind =
12284 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12285 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12286
12287 auto computeResultTy = [&]() {
12288 if (Opc != BO_Cmp)
12290 assert(getLangOpts().CPlusPlus);
12291 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12292
12293 QualType CompositeTy = LHS.get()->getType();
12294 assert(!CompositeTy->isReferenceType());
12295
12296 std::optional<ComparisonCategoryType> CCT =
12298 if (!CCT)
12299 return InvalidOperands(Loc, LHS, RHS);
12300
12301 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12302 // P0946R0: Comparisons between a null pointer constant and an object
12303 // pointer result in std::strong_equality, which is ill-formed under
12304 // P1959R0.
12305 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12306 << (LHSIsNull ? LHS.get()->getSourceRange()
12307 : RHS.get()->getSourceRange());
12308 return QualType();
12309 }
12310
12313 };
12314
12315 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12316 bool IsEquality = Opc == BO_EQ;
12317 if (RHSIsNull)
12318 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12319 RHS.get()->getSourceRange());
12320 else
12321 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12322 LHS.get()->getSourceRange());
12323 }
12324
12325 if (IsOrdered && LHSType->isFunctionPointerType() &&
12326 RHSType->isFunctionPointerType()) {
12327 // Valid unless a relational comparison of function pointers
12328 bool IsError = Opc == BO_Cmp;
12329 auto DiagID =
12330 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12331 : getLangOpts().CPlusPlus
12332 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12333 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12334 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12335 << RHS.get()->getSourceRange();
12336 if (IsError)
12337 return QualType();
12338 }
12339
12340 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12341 (RHSType->isIntegerType() && !RHSIsNull)) {
12342 // Skip normal pointer conversion checks in this case; we have better
12343 // diagnostics for this below.
12344 } else if (getLangOpts().CPlusPlus) {
12345 // Equality comparison of a function pointer to a void pointer is invalid,
12346 // but we allow it as an extension.
12347 // FIXME: If we really want to allow this, should it be part of composite
12348 // pointer type computation so it works in conditionals too?
12349 if (!IsOrdered &&
12350 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12351 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12352 // This is a gcc extension compatibility comparison.
12353 // In a SFINAE context, we treat this as a hard error to maintain
12354 // conformance with the C++ standard.
12356 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12357
12358 if (isSFINAEContext())
12359 return QualType();
12360
12361 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12362 return computeResultTy();
12363 }
12364
12365 // C++ [expr.eq]p2:
12366 // If at least one operand is a pointer [...] bring them to their
12367 // composite pointer type.
12368 // C++ [expr.spaceship]p6
12369 // If at least one of the operands is of pointer type, [...] bring them
12370 // to their composite pointer type.
12371 // C++ [expr.rel]p2:
12372 // If both operands are pointers, [...] bring them to their composite
12373 // pointer type.
12374 // For <=>, the only valid non-pointer types are arrays and functions, and
12375 // we already decayed those, so this is really the same as the relational
12376 // comparison rule.
12377 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12378 (IsOrdered ? 2 : 1) &&
12379 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12380 RHSType->isObjCObjectPointerType()))) {
12381 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12382 return QualType();
12383 return computeResultTy();
12384 }
12385 } else if (LHSType->isPointerType() &&
12386 RHSType->isPointerType()) { // C99 6.5.8p2
12387 // All of the following pointer-related warnings are GCC extensions, except
12388 // when handling null pointer constants.
12389 QualType LCanPointeeTy =
12391 QualType RCanPointeeTy =
12393
12394 // C99 6.5.9p2 and C99 6.5.8p2
12395 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12396 RCanPointeeTy.getUnqualifiedType())) {
12397 if (IsRelational) {
12398 // Pointers both need to point to complete or incomplete types
12399 if ((LCanPointeeTy->isIncompleteType() !=
12400 RCanPointeeTy->isIncompleteType()) &&
12401 !getLangOpts().C11) {
12402 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12403 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12404 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12405 << RCanPointeeTy->isIncompleteType();
12406 }
12407 }
12408 } else if (!IsRelational &&
12409 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12410 // Valid unless comparison between non-null pointer and function pointer
12411 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12412 && !LHSIsNull && !RHSIsNull)
12414 /*isError*/false);
12415 } else {
12416 // Invalid
12417 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12418 }
12419 if (LCanPointeeTy != RCanPointeeTy) {
12420 // Treat NULL constant as a special case in OpenCL.
12421 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12422 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
12423 getASTContext())) {
12424 Diag(Loc,
12425 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12426 << LHSType << RHSType << 0 /* comparison */
12427 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12428 }
12429 }
12430 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12431 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12432 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12433 : CK_BitCast;
12434 if (LHSIsNull && !RHSIsNull)
12435 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12436 else
12437 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12438 }
12439 return computeResultTy();
12440 }
12441
12442
12443 // C++ [expr.eq]p4:
12444 // Two operands of type std::nullptr_t or one operand of type
12445 // std::nullptr_t and the other a null pointer constant compare
12446 // equal.
12447 // C23 6.5.9p5:
12448 // If both operands have type nullptr_t or one operand has type nullptr_t
12449 // and the other is a null pointer constant, they compare equal if the
12450 // former is a null pointer.
12451 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12452 if (LHSType->isNullPtrType()) {
12453 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12454 return computeResultTy();
12455 }
12456 if (RHSType->isNullPtrType()) {
12457 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12458 return computeResultTy();
12459 }
12460 }
12461
12462 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12463 // C23 6.5.9p6:
12464 // Otherwise, at least one operand is a pointer. If one is a pointer and
12465 // the other is a null pointer constant or has type nullptr_t, they
12466 // compare equal
12467 if (LHSIsNull && RHSType->isPointerType()) {
12468 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12469 return computeResultTy();
12470 }
12471 if (RHSIsNull && LHSType->isPointerType()) {
12472 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12473 return computeResultTy();
12474 }
12475 }
12476
12477 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12478 // These aren't covered by the composite pointer type rules.
12479 if (!IsOrdered && RHSType->isNullPtrType() &&
12480 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12481 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12482 return computeResultTy();
12483 }
12484 if (!IsOrdered && LHSType->isNullPtrType() &&
12485 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12486 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12487 return computeResultTy();
12488 }
12489
12490 if (getLangOpts().CPlusPlus) {
12491 if (IsRelational &&
12492 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12493 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12494 // HACK: Relational comparison of nullptr_t against a pointer type is
12495 // invalid per DR583, but we allow it within std::less<> and friends,
12496 // since otherwise common uses of it break.
12497 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12498 // friends to have std::nullptr_t overload candidates.
12499 DeclContext *DC = CurContext;
12500 if (isa<FunctionDecl>(DC))
12501 DC = DC->getParent();
12502 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12503 if (CTSD->isInStdNamespace() &&
12504 llvm::StringSwitch<bool>(CTSD->getName())
12505 .Cases("less", "less_equal", "greater", "greater_equal", true)
12506 .Default(false)) {
12507 if (RHSType->isNullPtrType())
12508 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12509 else
12510 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12511 return computeResultTy();
12512 }
12513 }
12514 }
12515
12516 // C++ [expr.eq]p2:
12517 // If at least one operand is a pointer to member, [...] bring them to
12518 // their composite pointer type.
12519 if (!IsOrdered &&
12520 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12521 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12522 return QualType();
12523 else
12524 return computeResultTy();
12525 }
12526 }
12527
12528 // Handle block pointer types.
12529 if (!IsOrdered && LHSType->isBlockPointerType() &&
12530 RHSType->isBlockPointerType()) {
12531 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12532 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12533
12534 if (!LHSIsNull && !RHSIsNull &&
12535 !Context.typesAreCompatible(lpointee, rpointee)) {
12536 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12537 << LHSType << RHSType << LHS.get()->getSourceRange()
12538 << RHS.get()->getSourceRange();
12539 }
12540 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12541 return computeResultTy();
12542 }
12543
12544 // Allow block pointers to be compared with null pointer constants.
12545 if (!IsOrdered
12546 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12547 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12548 if (!LHSIsNull && !RHSIsNull) {
12549 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12551 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12552 ->getPointeeType()->isVoidType())))
12553 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12554 << LHSType << RHSType << LHS.get()->getSourceRange()
12555 << RHS.get()->getSourceRange();
12556 }
12557 if (LHSIsNull && !RHSIsNull)
12558 LHS = ImpCastExprToType(LHS.get(), RHSType,
12559 RHSType->isPointerType() ? CK_BitCast
12560 : CK_AnyPointerToBlockPointerCast);
12561 else
12562 RHS = ImpCastExprToType(RHS.get(), LHSType,
12563 LHSType->isPointerType() ? CK_BitCast
12564 : CK_AnyPointerToBlockPointerCast);
12565 return computeResultTy();
12566 }
12567
12568 if (LHSType->isObjCObjectPointerType() ||
12569 RHSType->isObjCObjectPointerType()) {
12570 const PointerType *LPT = LHSType->getAs<PointerType>();
12571 const PointerType *RPT = RHSType->getAs<PointerType>();
12572 if (LPT || RPT) {
12573 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12574 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12575
12576 if (!LPtrToVoid && !RPtrToVoid &&
12577 !Context.typesAreCompatible(LHSType, RHSType)) {
12578 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12579 /*isError*/false);
12580 }
12581 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12582 // the RHS, but we have test coverage for this behavior.
12583 // FIXME: Consider using convertPointersToCompositeType in C++.
12584 if (LHSIsNull && !RHSIsNull) {
12585 Expr *E = LHS.get();
12586 if (getLangOpts().ObjCAutoRefCount)
12587 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
12589 LHS = ImpCastExprToType(E, RHSType,
12590 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12591 }
12592 else {
12593 Expr *E = RHS.get();
12594 if (getLangOpts().ObjCAutoRefCount)
12595 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
12597 /*Diagnose=*/true,
12598 /*DiagnoseCFAudited=*/false, Opc);
12599 RHS = ImpCastExprToType(E, LHSType,
12600 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12601 }
12602 return computeResultTy();
12603 }
12604 if (LHSType->isObjCObjectPointerType() &&
12605 RHSType->isObjCObjectPointerType()) {
12606 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12607 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12608 /*isError*/false);
12610 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12611
12612 if (LHSIsNull && !RHSIsNull)
12613 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12614 else
12615 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12616 return computeResultTy();
12617 }
12618
12619 if (!IsOrdered && LHSType->isBlockPointerType() &&
12621 LHS = ImpCastExprToType(LHS.get(), RHSType,
12622 CK_BlockPointerToObjCPointerCast);
12623 return computeResultTy();
12624 } else if (!IsOrdered &&
12626 RHSType->isBlockPointerType()) {
12627 RHS = ImpCastExprToType(RHS.get(), LHSType,
12628 CK_BlockPointerToObjCPointerCast);
12629 return computeResultTy();
12630 }
12631 }
12632 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12633 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12634 unsigned DiagID = 0;
12635 bool isError = false;
12636 if (LangOpts.DebuggerSupport) {
12637 // Under a debugger, allow the comparison of pointers to integers,
12638 // since users tend to want to compare addresses.
12639 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12640 (RHSIsNull && RHSType->isIntegerType())) {
12641 if (IsOrdered) {
12642 isError = getLangOpts().CPlusPlus;
12643 DiagID =
12644 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12645 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12646 }
12647 } else if (getLangOpts().CPlusPlus) {
12648 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12649 isError = true;
12650 } else if (IsOrdered)
12651 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12652 else
12653 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12654
12655 if (DiagID) {
12656 Diag(Loc, DiagID)
12657 << LHSType << RHSType << LHS.get()->getSourceRange()
12658 << RHS.get()->getSourceRange();
12659 if (isError)
12660 return QualType();
12661 }
12662
12663 if (LHSType->isIntegerType())
12664 LHS = ImpCastExprToType(LHS.get(), RHSType,
12665 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12666 else
12667 RHS = ImpCastExprToType(RHS.get(), LHSType,
12668 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12669 return computeResultTy();
12670 }
12671
12672 // Handle block pointers.
12673 if (!IsOrdered && RHSIsNull
12674 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12675 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12676 return computeResultTy();
12677 }
12678 if (!IsOrdered && LHSIsNull
12679 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12680 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12681 return computeResultTy();
12682 }
12683
12684 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12685 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12686 return computeResultTy();
12687 }
12688
12689 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12690 return computeResultTy();
12691 }
12692
12693 if (LHSIsNull && RHSType->isQueueT()) {
12694 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12695 return computeResultTy();
12696 }
12697
12698 if (LHSType->isQueueT() && RHSIsNull) {
12699 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12700 return computeResultTy();
12701 }
12702 }
12703
12704 return InvalidOperands(Loc, LHS, RHS);
12705}
12706
12708 const VectorType *VTy = V->castAs<VectorType>();
12709 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12710
12711 if (isa<ExtVectorType>(VTy)) {
12712 if (VTy->isExtVectorBoolType())
12714 if (TypeSize == Context.getTypeSize(Context.CharTy))
12716 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12718 if (TypeSize == Context.getTypeSize(Context.IntTy))
12720 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12722 if (TypeSize == Context.getTypeSize(Context.LongTy))
12724 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12725 "Unhandled vector element size in vector compare");
12727 }
12728
12729 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12732 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12735 if (TypeSize == Context.getTypeSize(Context.LongTy))
12738 if (TypeSize == Context.getTypeSize(Context.IntTy))
12741 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12744 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12745 "Unhandled vector element size in vector compare");
12748}
12749
12751 const BuiltinType *VTy = V->castAs<BuiltinType>();
12752 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
12753
12754 const QualType ETy = V->getSveEltType(Context);
12755 const auto TypeSize = Context.getTypeSize(ETy);
12756
12757 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12758 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12759 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12760}
12761
12764 BinaryOperatorKind Opc) {
12765 if (Opc == BO_Cmp) {
12766 Diag(Loc, diag::err_three_way_vector_comparison);
12767 return QualType();
12768 }
12769
12770 // Check to make sure we're operating on vectors of the same type and width,
12771 // Allowing one side to be a scalar of element type.
12772 QualType vType =
12773 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12774 /*AllowBothBool*/ true,
12775 /*AllowBoolConversions*/ getLangOpts().ZVector,
12776 /*AllowBooleanOperation*/ true,
12777 /*ReportInvalid*/ true);
12778 if (vType.isNull())
12779 return vType;
12780
12781 QualType LHSType = LHS.get()->getType();
12782
12783 // Determine the return type of a vector compare. By default clang will return
12784 // a scalar for all vector compares except vector bool and vector pixel.
12785 // With the gcc compiler we will always return a vector type and with the xl
12786 // compiler we will always return a scalar type. This switch allows choosing
12787 // which behavior is prefered.
12788 if (getLangOpts().AltiVec) {
12789 switch (getLangOpts().getAltivecSrcCompat()) {
12791 // If AltiVec, the comparison results in a numeric type, i.e.
12792 // bool for C++, int for C
12793 if (vType->castAs<VectorType>()->getVectorKind() ==
12796 else
12797 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12798 break;
12800 // For GCC we always return the vector type.
12801 break;
12804 break;
12805 }
12806 }
12807
12808 // For non-floating point types, check for self-comparisons of the form
12809 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12810 // often indicate logic errors in the program.
12811 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12812
12813 // Check for comparisons of floating point operands using != and ==.
12814 if (LHSType->hasFloatingRepresentation()) {
12815 assert(RHS.get()->getType()->hasFloatingRepresentation());
12816 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12817 }
12818
12819 // Return a signed type for the vector.
12820 return GetSignedVectorType(vType);
12821}
12822
12824 ExprResult &RHS,
12826 BinaryOperatorKind Opc) {
12827 if (Opc == BO_Cmp) {
12828 Diag(Loc, diag::err_three_way_vector_comparison);
12829 return QualType();
12830 }
12831
12832 // Check to make sure we're operating on vectors of the same type and width,
12833 // Allowing one side to be a scalar of element type.
12835 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12836
12837 if (vType.isNull())
12838 return vType;
12839
12840 QualType LHSType = LHS.get()->getType();
12841
12842 // For non-floating point types, check for self-comparisons of the form
12843 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12844 // often indicate logic errors in the program.
12845 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12846
12847 // Check for comparisons of floating point operands using != and ==.
12848 if (LHSType->hasFloatingRepresentation()) {
12849 assert(RHS.get()->getType()->hasFloatingRepresentation());
12850 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12851 }
12852
12853 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12854 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12855
12856 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12857 RHSBuiltinTy->isSVEBool())
12858 return LHSType;
12859
12860 // Return a signed type for the vector.
12861 return GetSignedSizelessVectorType(vType);
12862}
12863
12864static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12865 const ExprResult &XorRHS,
12866 const SourceLocation Loc) {
12867 // Do not diagnose macros.
12868 if (Loc.isMacroID())
12869 return;
12870
12871 // Do not diagnose if both LHS and RHS are macros.
12872 if (XorLHS.get()->getExprLoc().isMacroID() &&
12873 XorRHS.get()->getExprLoc().isMacroID())
12874 return;
12875
12876 bool Negative = false;
12877 bool ExplicitPlus = false;
12878 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12879 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12880
12881 if (!LHSInt)
12882 return;
12883 if (!RHSInt) {
12884 // Check negative literals.
12885 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12886 UnaryOperatorKind Opc = UO->getOpcode();
12887 if (Opc != UO_Minus && Opc != UO_Plus)
12888 return;
12889 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12890 if (!RHSInt)
12891 return;
12892 Negative = (Opc == UO_Minus);
12893 ExplicitPlus = !Negative;
12894 } else {
12895 return;
12896 }
12897 }
12898
12899 const llvm::APInt &LeftSideValue = LHSInt->getValue();
12900 llvm::APInt RightSideValue = RHSInt->getValue();
12901 if (LeftSideValue != 2 && LeftSideValue != 10)
12902 return;
12903
12904 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12905 return;
12906
12908 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12909 llvm::StringRef ExprStr =
12911
12912 CharSourceRange XorRange =
12914 llvm::StringRef XorStr =
12916 // Do not diagnose if xor keyword/macro is used.
12917 if (XorStr == "xor")
12918 return;
12919
12920 std::string LHSStr = std::string(Lexer::getSourceText(
12921 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12922 S.getSourceManager(), S.getLangOpts()));
12923 std::string RHSStr = std::string(Lexer::getSourceText(
12924 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12925 S.getSourceManager(), S.getLangOpts()));
12926
12927 if (Negative) {
12928 RightSideValue = -RightSideValue;
12929 RHSStr = "-" + RHSStr;
12930 } else if (ExplicitPlus) {
12931 RHSStr = "+" + RHSStr;
12932 }
12933
12934 StringRef LHSStrRef = LHSStr;
12935 StringRef RHSStrRef = RHSStr;
12936 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12937 // literals.
12938 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
12939 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
12940 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
12941 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
12942 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
12943 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
12944 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12945 return;
12946
12947 bool SuggestXor =
12948 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12949 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12950 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12951 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12952 std::string SuggestedExpr = "1 << " + RHSStr;
12953 bool Overflow = false;
12954 llvm::APInt One = (LeftSideValue - 1);
12955 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12956 if (Overflow) {
12957 if (RightSideIntValue < 64)
12958 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12959 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12960 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12961 else if (RightSideIntValue == 64)
12962 S.Diag(Loc, diag::warn_xor_used_as_pow)
12963 << ExprStr << toString(XorValue, 10, true);
12964 else
12965 return;
12966 } else {
12967 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12968 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12969 << toString(PowValue, 10, true)
12971 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12972 }
12973
12974 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12975 << ("0x2 ^ " + RHSStr) << SuggestXor;
12976 } else if (LeftSideValue == 10) {
12977 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12978 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12979 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12980 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12981 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12982 << ("0xA ^ " + RHSStr) << SuggestXor;
12983 }
12984}
12985
12988 BinaryOperatorKind Opc) {
12989 // Ensure that either both operands are of the same vector type, or
12990 // one operand is of a vector type and the other is of its element type.
12991 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12992 /*AllowBothBool*/ true,
12993 /*AllowBoolConversions*/ false,
12994 /*AllowBooleanOperation*/ false,
12995 /*ReportInvalid*/ false);
12996 if (vType.isNull())
12997 return InvalidOperands(Loc, LHS, RHS);
12998 if (getLangOpts().OpenCL &&
12999 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13001 return InvalidOperands(Loc, LHS, RHS);
13002 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13003 // usage of the logical operators && and || with vectors in C. This
13004 // check could be notionally dropped.
13005 if (!getLangOpts().CPlusPlus &&
13006 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13007 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13008 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
13009 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
13010 // `select` functions.
13011 if (getLangOpts().HLSL &&
13012 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13013 (void)InvalidOperands(Loc, LHS, RHS);
13014 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13015 return QualType();
13016 }
13017
13018 return GetSignedVectorType(LHS.get()->getType());
13019}
13020
13023 bool IsCompAssign) {
13024 if (!IsCompAssign) {
13026 if (LHS.isInvalid())
13027 return QualType();
13028 }
13030 if (RHS.isInvalid())
13031 return QualType();
13032
13033 // For conversion purposes, we ignore any qualifiers.
13034 // For example, "const float" and "float" are equivalent.
13035 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13036 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13037
13038 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13039 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13040 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13041
13042 if (Context.hasSameType(LHSType, RHSType))
13043 return Context.getCommonSugaredType(LHSType, RHSType);
13044
13045 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13046 // case we have to return InvalidOperands.
13047 ExprResult OriginalLHS = LHS;
13048 ExprResult OriginalRHS = RHS;
13049 if (LHSMatType && !RHSMatType) {
13050 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13051 if (!RHS.isInvalid())
13052 return LHSType;
13053
13054 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13055 }
13056
13057 if (!LHSMatType && RHSMatType) {
13058 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13059 if (!LHS.isInvalid())
13060 return RHSType;
13061 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13062 }
13063
13064 return InvalidOperands(Loc, LHS, RHS);
13065}
13066
13069 bool IsCompAssign) {
13070 if (!IsCompAssign) {
13072 if (LHS.isInvalid())
13073 return QualType();
13074 }
13076 if (RHS.isInvalid())
13077 return QualType();
13078
13079 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13080 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13081 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13082
13083 if (LHSMatType && RHSMatType) {
13084 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13085 return InvalidOperands(Loc, LHS, RHS);
13086
13087 if (Context.hasSameType(LHSMatType, RHSMatType))
13089 LHS.get()->getType().getUnqualifiedType(),
13090 RHS.get()->getType().getUnqualifiedType());
13091
13092 QualType LHSELTy = LHSMatType->getElementType(),
13093 RHSELTy = RHSMatType->getElementType();
13094 if (!Context.hasSameType(LHSELTy, RHSELTy))
13095 return InvalidOperands(Loc, LHS, RHS);
13096
13098 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13099 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13100 }
13101 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13102}
13103
13105 switch (Opc) {
13106 default:
13107 return false;
13108 case BO_And:
13109 case BO_AndAssign:
13110 case BO_Or:
13111 case BO_OrAssign:
13112 case BO_Xor:
13113 case BO_XorAssign:
13114 return true;
13115 }
13116}
13117
13120 BinaryOperatorKind Opc) {
13121 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13122
13123 bool IsCompAssign =
13124 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13125
13126 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13127
13128 if (LHS.get()->getType()->isVectorType() ||
13129 RHS.get()->getType()->isVectorType()) {
13130 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13132 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13133 /*AllowBothBool*/ true,
13134 /*AllowBoolConversions*/ getLangOpts().ZVector,
13135 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13136 /*ReportInvalid*/ true);
13137 return InvalidOperands(Loc, LHS, RHS);
13138 }
13139
13140 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13141 RHS.get()->getType()->isSveVLSBuiltinType()) {
13142 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13144 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13146 return InvalidOperands(Loc, LHS, RHS);
13147 }
13148
13149 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13150 RHS.get()->getType()->isSveVLSBuiltinType()) {
13151 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13153 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13155 return InvalidOperands(Loc, LHS, RHS);
13156 }
13157
13158 if (Opc == BO_And)
13159 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13160
13161 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13163 return InvalidOperands(Loc, LHS, RHS);
13164
13165 ExprResult LHSResult = LHS, RHSResult = RHS;
13167 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13168 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13169 return QualType();
13170 LHS = LHSResult.get();
13171 RHS = RHSResult.get();
13172
13173 if (Opc == BO_Xor)
13174 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13175
13176 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13177 return compType;
13178 return InvalidOperands(Loc, LHS, RHS);
13179}
13180
13181// C99 6.5.[13,14]
13184 BinaryOperatorKind Opc) {
13185 // Check vector operands differently.
13186 if (LHS.get()->getType()->isVectorType() ||
13187 RHS.get()->getType()->isVectorType())
13188 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13189
13190 bool EnumConstantInBoolContext = false;
13191 for (const ExprResult &HS : {LHS, RHS}) {
13192 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13193 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13194 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13195 EnumConstantInBoolContext = true;
13196 }
13197 }
13198
13199 if (EnumConstantInBoolContext)
13200 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13201
13202 // WebAssembly tables can't be used with logical operators.
13203 QualType LHSTy = LHS.get()->getType();
13204 QualType RHSTy = RHS.get()->getType();
13205 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13206 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13207 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13208 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13209 return InvalidOperands(Loc, LHS, RHS);
13210 }
13211
13212 // Diagnose cases where the user write a logical and/or but probably meant a
13213 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13214 // is a constant.
13215 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13216 !LHS.get()->getType()->isBooleanType() &&
13217 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13218 // Don't warn in macros or template instantiations.
13220 // If the RHS can be constant folded, and if it constant folds to something
13221 // that isn't 0 or 1 (which indicate a potential logical operation that
13222 // happened to fold to true/false) then warn.
13223 // Parens on the RHS are ignored.
13224 Expr::EvalResult EVResult;
13225 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13226 llvm::APSInt Result = EVResult.Val.getInt();
13227 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13228 !RHS.get()->getExprLoc().isMacroID()) ||
13229 (Result != 0 && Result != 1)) {
13230 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13231 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13232 // Suggest replacing the logical operator with the bitwise version
13233 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13234 << (Opc == BO_LAnd ? "&" : "|")
13237 Opc == BO_LAnd ? "&" : "|");
13238 if (Opc == BO_LAnd)
13239 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13240 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13243 RHS.get()->getEndLoc()));
13244 }
13245 }
13246 }
13247
13248 if (!Context.getLangOpts().CPlusPlus) {
13249 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13250 // not operate on the built-in scalar and vector float types.
13251 if (Context.getLangOpts().OpenCL &&
13252 Context.getLangOpts().OpenCLVersion < 120) {
13253 if (LHS.get()->getType()->isFloatingType() ||
13254 RHS.get()->getType()->isFloatingType())
13255 return InvalidOperands(Loc, LHS, RHS);
13256 }
13257
13258 LHS = UsualUnaryConversions(LHS.get());
13259 if (LHS.isInvalid())
13260 return QualType();
13261
13262 RHS = UsualUnaryConversions(RHS.get());
13263 if (RHS.isInvalid())
13264 return QualType();
13265
13266 if (!LHS.get()->getType()->isScalarType() ||
13267 !RHS.get()->getType()->isScalarType())
13268 return InvalidOperands(Loc, LHS, RHS);
13269
13270 return Context.IntTy;
13271 }
13272
13273 // The following is safe because we only use this method for
13274 // non-overloadable operands.
13275
13276 // C++ [expr.log.and]p1
13277 // C++ [expr.log.or]p1
13278 // The operands are both contextually converted to type bool.
13280 if (LHSRes.isInvalid())
13281 return InvalidOperands(Loc, LHS, RHS);
13282 LHS = LHSRes;
13283
13285 if (RHSRes.isInvalid())
13286 return InvalidOperands(Loc, LHS, RHS);
13287 RHS = RHSRes;
13288
13289 // C++ [expr.log.and]p2
13290 // C++ [expr.log.or]p2
13291 // The result is a bool.
13292 return Context.BoolTy;
13293}
13294
13295static bool IsReadonlyMessage(Expr *E, Sema &S) {
13296 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13297 if (!ME) return false;
13298 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13299 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13301 if (!Base) return false;
13302 return Base->getMethodDecl() != nullptr;
13303}
13304
13305/// Is the given expression (which must be 'const') a reference to a
13306/// variable which was originally non-const, but which has become
13307/// 'const' due to being captured within a block?
13310 assert(E->isLValue() && E->getType().isConstQualified());
13311 E = E->IgnoreParens();
13312
13313 // Must be a reference to a declaration from an enclosing scope.
13314 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13315 if (!DRE) return NCCK_None;
13317
13318 ValueDecl *Value = dyn_cast<ValueDecl>(DRE->getDecl());
13319
13320 // The declaration must be a value which is not declared 'const'.
13321 if (!Value || Value->getType().isConstQualified())
13322 return NCCK_None;
13323
13324 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
13325 if (Binding) {
13326 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
13327 assert(!isa<BlockDecl>(Binding->getDeclContext()));
13328 return NCCK_Lambda;
13329 }
13330
13331 VarDecl *Var = dyn_cast<VarDecl>(Value);
13332 if (!Var)
13333 return NCCK_None;
13334
13335 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
13336
13337 // Decide whether the first capture was for a block or a lambda.
13338 DeclContext *DC = S.CurContext, *Prev = nullptr;
13339 // Decide whether the first capture was for a block or a lambda.
13340 while (DC) {
13341 // For init-capture, it is possible that the variable belongs to the
13342 // template pattern of the current context.
13343 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13344 if (Var->isInitCapture() &&
13345 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
13346 break;
13347 if (DC == Var->getDeclContext())
13348 break;
13349 Prev = DC;
13350 DC = DC->getParent();
13351 }
13352 // Unless we have an init-capture, we've gone one step too far.
13353 if (!Var->isInitCapture())
13354 DC = Prev;
13355 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13356}
13357
13358static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13359 Ty = Ty.getNonReferenceType();
13360 if (IsDereference && Ty->isPointerType())
13361 Ty = Ty->getPointeeType();
13362 return !Ty.isConstQualified();
13363}
13364
13365// Update err_typecheck_assign_const and note_typecheck_assign_const
13366// when this enum is changed.
13367enum {
13373 ConstUnknown, // Keep as last element
13374};
13375
13376/// Emit the "read-only variable not assignable" error and print notes to give
13377/// more information about why the variable is not assignable, such as pointing
13378/// to the declaration of a const variable, showing that a method is const, or
13379/// that the function is returning a const reference.
13380static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13382 SourceRange ExprRange = E->getSourceRange();
13383
13384 // Only emit one error on the first const found. All other consts will emit
13385 // a note to the error.
13386 bool DiagnosticEmitted = false;
13387
13388 // Track if the current expression is the result of a dereference, and if the
13389 // next checked expression is the result of a dereference.
13390 bool IsDereference = false;
13391 bool NextIsDereference = false;
13392
13393 // Loop to process MemberExpr chains.
13394 while (true) {
13395 IsDereference = NextIsDereference;
13396
13398 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13399 NextIsDereference = ME->isArrow();
13400 const ValueDecl *VD = ME->getMemberDecl();
13401 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13402 // Mutable fields can be modified even if the class is const.
13403 if (Field->isMutable()) {
13404 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13405 break;
13406 }
13407
13408 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13409 if (!DiagnosticEmitted) {
13410 S.Diag(Loc, diag::err_typecheck_assign_const)
13411 << ExprRange << ConstMember << false /*static*/ << Field
13412 << Field->getType();
13413 DiagnosticEmitted = true;
13414 }
13415 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13416 << ConstMember << false /*static*/ << Field << Field->getType()
13417 << Field->getSourceRange();
13418 }
13419 E = ME->getBase();
13420 continue;
13421 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13422 if (VDecl->getType().isConstQualified()) {
13423 if (!DiagnosticEmitted) {
13424 S.Diag(Loc, diag::err_typecheck_assign_const)
13425 << ExprRange << ConstMember << true /*static*/ << VDecl
13426 << VDecl->getType();
13427 DiagnosticEmitted = true;
13428 }
13429 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13430 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13431 << VDecl->getSourceRange();
13432 }
13433 // Static fields do not inherit constness from parents.
13434 break;
13435 }
13436 break; // End MemberExpr
13437 } else if (const ArraySubscriptExpr *ASE =
13438 dyn_cast<ArraySubscriptExpr>(E)) {
13439 E = ASE->getBase()->IgnoreParenImpCasts();
13440 continue;
13441 } else if (const ExtVectorElementExpr *EVE =
13442 dyn_cast<ExtVectorElementExpr>(E)) {
13443 E = EVE->getBase()->IgnoreParenImpCasts();
13444 continue;
13445 }
13446 break;
13447 }
13448
13449 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13450 // Function calls
13451 const FunctionDecl *FD = CE->getDirectCallee();
13452 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13453 if (!DiagnosticEmitted) {
13454 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13455 << ConstFunction << FD;
13456 DiagnosticEmitted = true;
13457 }
13459 diag::note_typecheck_assign_const)
13460 << ConstFunction << FD << FD->getReturnType()
13461 << FD->getReturnTypeSourceRange();
13462 }
13463 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13464 // Point to variable declaration.
13465 if (const ValueDecl *VD = DRE->getDecl()) {
13466 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13467 if (!DiagnosticEmitted) {
13468 S.Diag(Loc, diag::err_typecheck_assign_const)
13469 << ExprRange << ConstVariable << VD << VD->getType();
13470 DiagnosticEmitted = true;
13471 }
13472 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13473 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13474 }
13475 }
13476 } else if (isa<CXXThisExpr>(E)) {
13477 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13478 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13479 if (MD->isConst()) {
13480 if (!DiagnosticEmitted) {
13481 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13482 << ConstMethod << MD;
13483 DiagnosticEmitted = true;
13484 }
13485 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13486 << ConstMethod << MD << MD->getSourceRange();
13487 }
13488 }
13489 }
13490 }
13491
13492 if (DiagnosticEmitted)
13493 return;
13494
13495 // Can't determine a more specific message, so display the generic error.
13496 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13497}
13498
13504
13506 const RecordType *Ty,
13508 OriginalExprKind OEK,
13509 bool &DiagnosticEmitted) {
13510 std::vector<const RecordType *> RecordTypeList;
13511 RecordTypeList.push_back(Ty);
13512 unsigned NextToCheckIndex = 0;
13513 // We walk the record hierarchy breadth-first to ensure that we print
13514 // diagnostics in field nesting order.
13515 while (RecordTypeList.size() > NextToCheckIndex) {
13516 bool IsNested = NextToCheckIndex > 0;
13517 for (const FieldDecl *Field :
13518 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13519 // First, check every field for constness.
13520 QualType FieldTy = Field->getType();
13521 if (FieldTy.isConstQualified()) {
13522 if (!DiagnosticEmitted) {
13523 S.Diag(Loc, diag::err_typecheck_assign_const)
13524 << Range << NestedConstMember << OEK << VD
13525 << IsNested << Field;
13526 DiagnosticEmitted = true;
13527 }
13528 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13529 << NestedConstMember << IsNested << Field
13530 << FieldTy << Field->getSourceRange();
13531 }
13532
13533 // Then we append it to the list to check next in order.
13534 FieldTy = FieldTy.getCanonicalType();
13535 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13536 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13537 RecordTypeList.push_back(FieldRecTy);
13538 }
13539 }
13540 ++NextToCheckIndex;
13541 }
13542}
13543
13544/// Emit an error for the case where a record we are trying to assign to has a
13545/// const-qualified field somewhere in its hierarchy.
13548 QualType Ty = E->getType();
13549 assert(Ty->isRecordType() && "lvalue was not record?");
13551 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13552 bool DiagEmitted = false;
13553
13554 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13555 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13556 Range, OEK_Member, DiagEmitted);
13557 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13558 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13559 Range, OEK_Variable, DiagEmitted);
13560 else
13561 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13562 Range, OEK_LValue, DiagEmitted);
13563 if (!DiagEmitted)
13565}
13566
13567/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13568/// emit an error and return true. If so, return false.
13570 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13571
13573
13574 SourceLocation OrigLoc = Loc;
13576 &Loc);
13577 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13579 if (IsLV == Expr::MLV_Valid)
13580 return false;
13581
13582 unsigned DiagID = 0;
13583 bool NeedType = false;
13584 switch (IsLV) { // C99 6.5.16p2
13586 // Use a specialized diagnostic when we're assigning to an object
13587 // from an enclosing function or block.
13589 if (NCCK == NCCK_Block)
13590 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13591 else
13592 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13593 break;
13594 }
13595
13596 // In ARC, use some specialized diagnostics for occasions where we
13597 // infer 'const'. These are always pseudo-strong variables.
13598 if (S.getLangOpts().ObjCAutoRefCount) {
13599 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13600 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13601 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13602
13603 // Use the normal diagnostic if it's pseudo-__strong but the
13604 // user actually wrote 'const'.
13605 if (var->isARCPseudoStrong() &&
13606 (!var->getTypeSourceInfo() ||
13607 !var->getTypeSourceInfo()->getType().isConstQualified())) {
13608 // There are three pseudo-strong cases:
13609 // - self
13610 ObjCMethodDecl *method = S.getCurMethodDecl();
13611 if (method && var == method->getSelfDecl()) {
13612 DiagID = method->isClassMethod()
13613 ? diag::err_typecheck_arc_assign_self_class_method
13614 : diag::err_typecheck_arc_assign_self;
13615
13616 // - Objective-C externally_retained attribute.
13617 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13618 isa<ParmVarDecl>(var)) {
13619 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13620
13621 // - fast enumeration variables
13622 } else {
13623 DiagID = diag::err_typecheck_arr_assign_enumeration;
13624 }
13625
13626 SourceRange Assign;
13627 if (Loc != OrigLoc)
13628 Assign = SourceRange(OrigLoc, OrigLoc);
13629 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13630 // We need to preserve the AST regardless, so migration tool
13631 // can do its job.
13632 return false;
13633 }
13634 }
13635 }
13636
13637 // If none of the special cases above are triggered, then this is a
13638 // simple const assignment.
13639 if (DiagID == 0) {
13641 return true;
13642 }
13643
13644 break;
13647 return true;
13650 return true;
13653 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13654 NeedType = true;
13655 break;
13657 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13658 NeedType = true;
13659 break;
13661 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13662 break;
13663 case Expr::MLV_Valid:
13664 llvm_unreachable("did not take early return for MLV_Valid");
13668 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13669 break;
13672 return S.RequireCompleteType(Loc, E->getType(),
13673 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13675 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13676 break;
13678 llvm_unreachable("readonly properties should be processed differently");
13680 DiagID = diag::err_readonly_message_assignment;
13681 break;
13683 DiagID = diag::err_no_subobject_property_setting;
13684 break;
13685 }
13686
13687 SourceRange Assign;
13688 if (Loc != OrigLoc)
13689 Assign = SourceRange(OrigLoc, OrigLoc);
13690 if (NeedType)
13691 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13692 else
13693 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13694 return true;
13695}
13696
13697static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13699 Sema &Sema) {
13701 return;
13703 return;
13704 if (Loc.isInvalid() || Loc.isMacroID())
13705 return;
13706 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13707 return;
13708
13709 // C / C++ fields
13710 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13711 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13712 if (ML && MR) {
13713 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13714 return;
13715 const ValueDecl *LHSDecl =
13716 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13717 const ValueDecl *RHSDecl =
13718 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13719 if (LHSDecl != RHSDecl)
13720 return;
13721 if (LHSDecl->getType().isVolatileQualified())
13722 return;
13723 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13724 if (RefTy->getPointeeType().isVolatileQualified())
13725 return;
13726
13727 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13728 }
13729
13730 // Objective-C instance variables
13731 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13732 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13733 if (OL && OR && OL->getDecl() == OR->getDecl()) {
13734 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13735 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13736 if (RL && RR && RL->getDecl() == RR->getDecl())
13737 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13738 }
13739}
13740
13741// C99 6.5.16.1
13744 QualType CompoundType,
13745 BinaryOperatorKind Opc) {
13746 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13747
13748 // Verify that LHS is a modifiable lvalue, and emit error if not.
13749 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13750 return QualType();
13751
13752 QualType LHSType = LHSExpr->getType();
13753 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13754 CompoundType;
13755 // OpenCL v1.2 s6.1.1.1 p2:
13756 // The half data type can only be used to declare a pointer to a buffer that
13757 // contains half values
13758 if (getLangOpts().OpenCL &&
13759 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13760 LHSType->isHalfType()) {
13761 Diag(Loc, diag::err_opencl_half_load_store) << 1
13762 << LHSType.getUnqualifiedType();
13763 return QualType();
13764 }
13765
13766 // WebAssembly tables can't be used on RHS of an assignment expression.
13767 if (RHSType->isWebAssemblyTableType()) {
13768 Diag(Loc, diag::err_wasm_table_art) << 0;
13769 return QualType();
13770 }
13771
13772 AssignConvertType ConvTy;
13773 if (CompoundType.isNull()) {
13774 Expr *RHSCheck = RHS.get();
13775
13776 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13777
13778 QualType LHSTy(LHSType);
13779 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13780 if (RHS.isInvalid())
13781 return QualType();
13782 // Special case of NSObject attributes on c-style pointer types.
13783 if (ConvTy == IncompatiblePointer &&
13784 ((Context.isObjCNSObjectType(LHSType) &&
13785 RHSType->isObjCObjectPointerType()) ||
13786 (Context.isObjCNSObjectType(RHSType) &&
13787 LHSType->isObjCObjectPointerType())))
13788 ConvTy = Compatible;
13789
13790 if (ConvTy == Compatible &&
13791 LHSType->isObjCObjectType())
13792 Diag(Loc, diag::err_objc_object_assignment)
13793 << LHSType;
13794
13795 // If the RHS is a unary plus or minus, check to see if they = and + are
13796 // right next to each other. If so, the user may have typo'd "x =+ 4"
13797 // instead of "x += 4".
13798 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13799 RHSCheck = ICE->getSubExpr();
13800 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13801 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13802 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13803 // Only if the two operators are exactly adjacent.
13804 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13805 // And there is a space or other character before the subexpr of the
13806 // unary +/-. We don't want to warn on "x=-1".
13807 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13808 UO->getSubExpr()->getBeginLoc().isFileID()) {
13809 Diag(Loc, diag::warn_not_compound_assign)
13810 << (UO->getOpcode() == UO_Plus ? "+" : "-")
13811 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13812 }
13813 }
13814
13815 if (ConvTy == Compatible) {
13816 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13817 // Warn about retain cycles where a block captures the LHS, but
13818 // not if the LHS is a simple variable into which the block is
13819 // being stored...unless that variable can be captured by reference!
13820 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13821 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13822 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13823 ObjC().checkRetainCycles(LHSExpr, RHS.get());
13824 }
13825
13826 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13828 // It is safe to assign a weak reference into a strong variable.
13829 // Although this code can still have problems:
13830 // id x = self.weakProp;
13831 // id y = self.weakProp;
13832 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13833 // paths through the function. This should be revisited if
13834 // -Wrepeated-use-of-weak is made flow-sensitive.
13835 // For ObjCWeak only, we do not warn if the assign is to a non-weak
13836 // variable, which will be valid for the current autorelease scope.
13837 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13838 RHS.get()->getBeginLoc()))
13840
13841 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13842 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13843 }
13844 }
13845 } else {
13846 // Compound assignment "x += y"
13847 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13848 }
13849
13850 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
13852 return QualType();
13853
13854 CheckForNullPointerDereference(*this, LHSExpr);
13855
13856 AssignedEntity AE{LHSExpr};
13857 checkAssignmentLifetime(*this, AE, RHS.get());
13858
13859 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13860 if (CompoundType.isNull()) {
13861 // C++2a [expr.ass]p5:
13862 // A simple-assignment whose left operand is of a volatile-qualified
13863 // type is deprecated unless the assignment is either a discarded-value
13864 // expression or an unevaluated operand
13865 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13866 }
13867 }
13868
13869 // C11 6.5.16p3: The type of an assignment expression is the type of the
13870 // left operand would have after lvalue conversion.
13871 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13872 // qualified type, the value has the unqualified version of the type of the
13873 // lvalue; additionally, if the lvalue has atomic type, the value has the
13874 // non-atomic version of the type of the lvalue.
13875 // C++ 5.17p1: the type of the assignment expression is that of its left
13876 // operand.
13877 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13878}
13879
13880// Scenarios to ignore if expression E is:
13881// 1. an explicit cast expression into void
13882// 2. a function call expression that returns void
13883static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
13884 E = E->IgnoreParens();
13885
13886 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13887 if (CE->getCastKind() == CK_ToVoid) {
13888 return true;
13889 }
13890
13891 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13892 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13893 CE->getSubExpr()->getType()->isDependentType()) {
13894 return true;
13895 }
13896 }
13897
13898 if (const auto *CE = dyn_cast<CallExpr>(E))
13899 return CE->getCallReturnType(Context)->isVoidType();
13900 return false;
13901}
13902
13904 // No warnings in macros
13905 if (Loc.isMacroID())
13906 return;
13907
13908 // Don't warn in template instantiations.
13910 return;
13911
13912 // Scope isn't fine-grained enough to explicitly list the specific cases, so
13913 // instead, skip more than needed, then call back into here with the
13914 // CommaVisitor in SemaStmt.cpp.
13915 // The listed locations are the initialization and increment portions
13916 // of a for loop. The additional checks are on the condition of
13917 // if statements, do/while loops, and for loops.
13918 // Differences in scope flags for C89 mode requires the extra logic.
13919 const unsigned ForIncrementFlags =
13920 getLangOpts().C99 || getLangOpts().CPlusPlus
13923 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13924 const unsigned ScopeFlags = getCurScope()->getFlags();
13925 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13926 (ScopeFlags & ForInitFlags) == ForInitFlags)
13927 return;
13928
13929 // If there are multiple comma operators used together, get the RHS of the
13930 // of the comma operator as the LHS.
13931 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13932 if (BO->getOpcode() != BO_Comma)
13933 break;
13934 LHS = BO->getRHS();
13935 }
13936
13937 // Only allow some expressions on LHS to not warn.
13938 if (IgnoreCommaOperand(LHS, Context))
13939 return;
13940
13941 Diag(Loc, diag::warn_comma_operator);
13942 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13943 << LHS->getSourceRange()
13945 LangOpts.CPlusPlus ? "static_cast<void>("
13946 : "(void)(")
13948 ")");
13949}
13950
13951// C99 6.5.17
13954 LHS = S.CheckPlaceholderExpr(LHS.get());
13955 RHS = S.CheckPlaceholderExpr(RHS.get());
13956 if (LHS.isInvalid() || RHS.isInvalid())
13957 return QualType();
13958
13959 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13960 // operands, but not unary promotions.
13961 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13962
13963 // So we treat the LHS as a ignored value, and in C++ we allow the
13964 // containing site to determine what should be done with the RHS.
13965 LHS = S.IgnoredValueConversions(LHS.get());
13966 if (LHS.isInvalid())
13967 return QualType();
13968
13969 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13970
13971 if (!S.getLangOpts().CPlusPlus) {
13973 if (RHS.isInvalid())
13974 return QualType();
13975 if (!RHS.get()->getType()->isVoidType())
13976 S.RequireCompleteType(Loc, RHS.get()->getType(),
13977 diag::err_incomplete_type);
13978 }
13979
13980 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13981 S.DiagnoseCommaOperator(LHS.get(), Loc);
13982
13983 return RHS.get()->getType();
13984}
13985
13986/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13987/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13989 ExprValueKind &VK,
13990 ExprObjectKind &OK,
13991 SourceLocation OpLoc, bool IsInc,
13992 bool IsPrefix) {
13993 QualType ResType = Op->getType();
13994 // Atomic types can be used for increment / decrement where the non-atomic
13995 // versions can, so ignore the _Atomic() specifier for the purpose of
13996 // checking.
13997 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13998 ResType = ResAtomicType->getValueType();
13999
14000 assert(!ResType.isNull() && "no type for increment/decrement expression");
14001
14002 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14003 // Decrement of bool is not allowed.
14004 if (!IsInc) {
14005 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14006 return QualType();
14007 }
14008 // Increment of bool sets it to true, but is deprecated.
14009 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14010 : diag::warn_increment_bool)
14011 << Op->getSourceRange();
14012 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14013 // Error on enum increments and decrements in C++ mode
14014 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14015 return QualType();
14016 } else if (ResType->isRealType()) {
14017 // OK!
14018 } else if (ResType->isPointerType()) {
14019 // C99 6.5.2.4p2, 6.5.6p2
14020 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14021 return QualType();
14022 } else if (ResType->isObjCObjectPointerType()) {
14023 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14024 // Otherwise, we just need a complete type.
14025 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14026 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14027 return QualType();
14028 } else if (ResType->isAnyComplexType()) {
14029 // C99 does not support ++/-- on complex types, we allow as an extension.
14030 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14031 : diag::ext_c2y_increment_complex)
14032 << IsInc << Op->getSourceRange();
14033 } else if (ResType->isPlaceholderType()) {
14035 if (PR.isInvalid()) return QualType();
14036 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14037 IsInc, IsPrefix);
14038 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14039 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14040 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14041 (ResType->castAs<VectorType>()->getVectorKind() !=
14043 // The z vector extensions allow ++ and -- for non-bool vectors.
14044 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14045 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14046 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14047 } else {
14048 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14049 << ResType << int(IsInc) << Op->getSourceRange();
14050 return QualType();
14051 }
14052 // At this point, we know we have a real, complex or pointer type.
14053 // Now make sure the operand is a modifiable lvalue.
14054 if (CheckForModifiableLvalue(Op, OpLoc, S))
14055 return QualType();
14056 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14057 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14058 // An operand with volatile-qualified type is deprecated
14059 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14060 << IsInc << ResType;
14061 }
14062 // In C++, a prefix increment is the same type as the operand. Otherwise
14063 // (in C or with postfix), the increment is the unqualified type of the
14064 // operand.
14065 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14066 VK = VK_LValue;
14067 OK = Op->getObjectKind();
14068 return ResType;
14069 } else {
14070 VK = VK_PRValue;
14071 return ResType.getUnqualifiedType();
14072 }
14073}
14074
14075/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14076/// This routine allows us to typecheck complex/recursive expressions
14077/// where the declaration is needed for type checking. We only need to
14078/// handle cases when the expression references a function designator
14079/// or is an lvalue. Here are some examples:
14080/// - &(x) => x
14081/// - &*****f => f for f a function designator.
14082/// - &s.xx => s
14083/// - &s.zz[1].yy -> s, if zz is an array
14084/// - *(x + 1) -> x, if x is an array
14085/// - &"123"[2] -> 0
14086/// - & __real__ x -> x
14087///
14088/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14089/// members.
14091 switch (E->getStmtClass()) {
14092 case Stmt::DeclRefExprClass:
14093 return cast<DeclRefExpr>(E)->getDecl();
14094 case Stmt::MemberExprClass:
14095 // If this is an arrow operator, the address is an offset from
14096 // the base's value, so the object the base refers to is
14097 // irrelevant.
14098 if (cast<MemberExpr>(E)->isArrow())
14099 return nullptr;
14100 // Otherwise, the expression refers to a part of the base
14101 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14102 case Stmt::ArraySubscriptExprClass: {
14103 // FIXME: This code shouldn't be necessary! We should catch the implicit
14104 // promotion of register arrays earlier.
14105 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14106 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14107 if (ICE->getSubExpr()->getType()->isArrayType())
14108 return getPrimaryDecl(ICE->getSubExpr());
14109 }
14110 return nullptr;
14111 }
14112 case Stmt::UnaryOperatorClass: {
14113 UnaryOperator *UO = cast<UnaryOperator>(E);
14114
14115 switch(UO->getOpcode()) {
14116 case UO_Real:
14117 case UO_Imag:
14118 case UO_Extension:
14119 return getPrimaryDecl(UO->getSubExpr());
14120 default:
14121 return nullptr;
14122 }
14123 }
14124 case Stmt::ParenExprClass:
14125 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14126 case Stmt::ImplicitCastExprClass:
14127 // If the result of an implicit cast is an l-value, we care about
14128 // the sub-expression; otherwise, the result here doesn't matter.
14129 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14130 case Stmt::CXXUuidofExprClass:
14131 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14132 default:
14133 return nullptr;
14134 }
14135}
14136
14137namespace {
14138enum {
14139 AO_Bit_Field = 0,
14140 AO_Vector_Element = 1,
14141 AO_Property_Expansion = 2,
14142 AO_Register_Variable = 3,
14143 AO_Matrix_Element = 4,
14144 AO_No_Error = 5
14145};
14146}
14147/// Diagnose invalid operand for address of operations.
14148///
14149/// \param Type The type of operand which cannot have its address taken.
14151 Expr *E, unsigned Type) {
14152 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14153}
14154
14156 const Expr *Op,
14157 const CXXMethodDecl *MD) {
14158 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14159
14160 if (Op != DRE)
14161 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14162 << Op->getSourceRange();
14163
14164 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14165 if (isa<CXXDestructorDecl>(MD))
14166 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14167 << DRE->getSourceRange();
14168
14169 if (DRE->getQualifier())
14170 return false;
14171
14172 if (MD->getParent()->getName().empty())
14173 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14174 << DRE->getSourceRange();
14175
14176 SmallString<32> Str;
14177 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14178 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14179 << DRE->getSourceRange()
14180 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14181}
14182
14184 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14185 if (PTy->getKind() == BuiltinType::Overload) {
14186 Expr *E = OrigOp.get()->IgnoreParens();
14187 if (!isa<OverloadExpr>(E)) {
14188 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14189 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14190 << OrigOp.get()->getSourceRange();
14191 return QualType();
14192 }
14193
14194 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14195 if (isa<UnresolvedMemberExpr>(Ovl))
14197 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14198 << OrigOp.get()->getSourceRange();
14199 return QualType();
14200 }
14201
14202 return Context.OverloadTy;
14203 }
14204
14205 if (PTy->getKind() == BuiltinType::UnknownAny)
14206 return Context.UnknownAnyTy;
14207
14208 if (PTy->getKind() == BuiltinType::BoundMember) {
14209 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14210 << OrigOp.get()->getSourceRange();
14211 return QualType();
14212 }
14213
14214 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14215 if (OrigOp.isInvalid()) return QualType();
14216 }
14217
14218 if (OrigOp.get()->isTypeDependent())
14219 return Context.DependentTy;
14220
14221 assert(!OrigOp.get()->hasPlaceholderType());
14222
14223 // Make sure to ignore parentheses in subsequent checks
14224 Expr *op = OrigOp.get()->IgnoreParens();
14225
14226 // In OpenCL captures for blocks called as lambda functions
14227 // are located in the private address space. Blocks used in
14228 // enqueue_kernel can be located in a different address space
14229 // depending on a vendor implementation. Thus preventing
14230 // taking an address of the capture to avoid invalid AS casts.
14231 if (LangOpts.OpenCL) {
14232 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14233 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14234 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14235 return QualType();
14236 }
14237 }
14238
14239 if (getLangOpts().C99) {
14240 // Implement C99-only parts of addressof rules.
14241 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14242 if (uOp->getOpcode() == UO_Deref)
14243 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14244 // (assuming the deref expression is valid).
14245 return uOp->getSubExpr()->getType();
14246 }
14247 // Technically, there should be a check for array subscript
14248 // expressions here, but the result of one is always an lvalue anyway.
14249 }
14250 ValueDecl *dcl = getPrimaryDecl(op);
14251
14252 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14253 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14254 op->getBeginLoc()))
14255 return QualType();
14256
14258 unsigned AddressOfError = AO_No_Error;
14259
14260 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14261 bool sfinae = (bool)isSFINAEContext();
14262 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14263 : diag::ext_typecheck_addrof_temporary)
14264 << op->getType() << op->getSourceRange();
14265 if (sfinae)
14266 return QualType();
14267 // Materialize the temporary as an lvalue so that we can take its address.
14268 OrigOp = op =
14269 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14270 } else if (isa<ObjCSelectorExpr>(op)) {
14271 return Context.getPointerType(op->getType());
14272 } else if (lval == Expr::LV_MemberFunction) {
14273 // If it's an instance method, make a member pointer.
14274 // The expression must have exactly the form &A::foo.
14275
14276 // If the underlying expression isn't a decl ref, give up.
14277 if (!isa<DeclRefExpr>(op)) {
14278 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14279 << OrigOp.get()->getSourceRange();
14280 return QualType();
14281 }
14282 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14283 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14284
14285 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14286
14289
14290 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14291 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14292 // When pointer authentication is enabled, argument and return types of
14293 // vitual member functions must be complete. This is because vitrual
14294 // member function pointers are implemented using virtual dispatch
14295 // thunks and the thunks cannot be emitted if the argument or return
14296 // types are incomplete.
14297 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
14298 SourceLocation DeclRefLoc,
14299 SourceLocation RetArgTypeLoc) {
14300 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
14301 Diag(DeclRefLoc,
14302 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
14303 Diag(RetArgTypeLoc,
14304 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
14305 << T;
14306 return true;
14307 }
14308 return false;
14309 };
14310 QualType RetTy = MD->getReturnType();
14311 bool IsIncomplete =
14312 !RetTy->isVoidType() &&
14313 ReturnOrParamTypeIsIncomplete(
14314 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
14315 for (auto *PVD : MD->parameters())
14316 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
14317 PVD->getBeginLoc());
14318 if (IsIncomplete)
14319 return QualType();
14320 }
14321
14322 // Under the MS ABI, lock down the inheritance model now.
14324 (void)isCompleteType(OpLoc, MPTy);
14325 return MPTy;
14326 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14327 // C99 6.5.3.2p1
14328 // The operand must be either an l-value or a function designator
14329 if (!op->getType()->isFunctionType()) {
14330 // Use a special diagnostic for loads from property references.
14331 if (isa<PseudoObjectExpr>(op)) {
14332 AddressOfError = AO_Property_Expansion;
14333 } else {
14334 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14335 << op->getType() << op->getSourceRange();
14336 return QualType();
14337 }
14338 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14339 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14340 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14341 }
14342
14343 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14344 // The operand cannot be a bit-field
14345 AddressOfError = AO_Bit_Field;
14346 } else if (op->getObjectKind() == OK_VectorComponent) {
14347 // The operand cannot be an element of a vector
14348 AddressOfError = AO_Vector_Element;
14349 } else if (op->getObjectKind() == OK_MatrixComponent) {
14350 // The operand cannot be an element of a matrix.
14351 AddressOfError = AO_Matrix_Element;
14352 } else if (dcl) { // C99 6.5.3.2p1
14353 // We have an lvalue with a decl. Make sure the decl is not declared
14354 // with the register storage-class specifier.
14355 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14356 // in C++ it is not error to take address of a register
14357 // variable (c++03 7.1.1P3)
14358 if (vd->getStorageClass() == SC_Register &&
14360 AddressOfError = AO_Register_Variable;
14361 }
14362 } else if (isa<MSPropertyDecl>(dcl)) {
14363 AddressOfError = AO_Property_Expansion;
14364 } else if (isa<FunctionTemplateDecl>(dcl)) {
14365 return Context.OverloadTy;
14366 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14367 // Okay: we can take the address of a field.
14368 // Could be a pointer to member, though, if there is an explicit
14369 // scope qualifier for the class.
14370
14371 // [C++26] [expr.prim.id.general]
14372 // If an id-expression E denotes a non-static non-type member
14373 // of some class C [...] and if E is a qualified-id, E is
14374 // not the un-parenthesized operand of the unary & operator [...]
14375 // the id-expression is transformed into a class member access expression.
14376 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
14377 !isa<ParenExpr>(OrigOp.get())) {
14378 DeclContext *Ctx = dcl->getDeclContext();
14379 if (Ctx && Ctx->isRecord()) {
14380 if (dcl->getType()->isReferenceType()) {
14381 Diag(OpLoc,
14382 diag::err_cannot_form_pointer_to_member_of_reference_type)
14383 << dcl->getDeclName() << dcl->getType();
14384 return QualType();
14385 }
14386
14387 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14388 Ctx = Ctx->getParent();
14389
14391 op->getType(),
14392 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14393 // Under the MS ABI, lock down the inheritance model now.
14395 (void)isCompleteType(OpLoc, MPTy);
14396 return MPTy;
14397 }
14398 }
14401 llvm_unreachable("Unknown/unexpected decl type");
14402 }
14403
14404 if (AddressOfError != AO_No_Error) {
14405 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14406 return QualType();
14407 }
14408
14409 if (lval == Expr::LV_IncompleteVoidType) {
14410 // Taking the address of a void variable is technically illegal, but we
14411 // allow it in cases which are otherwise valid.
14412 // Example: "extern void x; void* y = &x;".
14413 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14414 }
14415
14416 // If the operand has type "type", the result has type "pointer to type".
14417 if (op->getType()->isObjCObjectType())
14419
14420 // Cannot take the address of WebAssembly references or tables.
14421 if (Context.getTargetInfo().getTriple().isWasm()) {
14422 QualType OpTy = op->getType();
14423 if (OpTy.isWebAssemblyReferenceType()) {
14424 Diag(OpLoc, diag::err_wasm_ca_reference)
14425 << 1 << OrigOp.get()->getSourceRange();
14426 return QualType();
14427 }
14428 if (OpTy->isWebAssemblyTableType()) {
14429 Diag(OpLoc, diag::err_wasm_table_pr)
14430 << 1 << OrigOp.get()->getSourceRange();
14431 return QualType();
14432 }
14433 }
14434
14435 CheckAddressOfPackedMember(op);
14436
14437 return Context.getPointerType(op->getType());
14438}
14439
14440static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14441 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14442 if (!DRE)
14443 return;
14444 const Decl *D = DRE->getDecl();
14445 if (!D)
14446 return;
14447 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14448 if (!Param)
14449 return;
14450 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14451 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14452 return;
14453 if (FunctionScopeInfo *FD = S.getCurFunction())
14454 FD->ModifiedNonNullParams.insert(Param);
14455}
14456
14457/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14459 SourceLocation OpLoc,
14460 bool IsAfterAmp = false) {
14461 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14462 if (ConvResult.isInvalid())
14463 return QualType();
14464 Op = ConvResult.get();
14465 QualType OpTy = Op->getType();
14467
14468 if (isa<CXXReinterpretCastExpr>(Op)) {
14469 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14470 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14471 Op->getSourceRange());
14472 }
14473
14474 if (const PointerType *PT = OpTy->getAs<PointerType>())
14475 {
14476 Result = PT->getPointeeType();
14477 }
14478 else if (const ObjCObjectPointerType *OPT =
14480 Result = OPT->getPointeeType();
14481 else {
14483 if (PR.isInvalid()) return QualType();
14484 if (PR.get() != Op)
14485 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14486 }
14487
14488 if (Result.isNull()) {
14489 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14490 << OpTy << Op->getSourceRange();
14491 return QualType();
14492 }
14493
14494 if (Result->isVoidType()) {
14495 // C++ [expr.unary.op]p1:
14496 // [...] the expression to which [the unary * operator] is applied shall
14497 // be a pointer to an object type, or a pointer to a function type
14498 LangOptions LO = S.getLangOpts();
14499 if (LO.CPlusPlus)
14500 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
14501 << OpTy << Op->getSourceRange();
14502 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14503 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14504 << OpTy << Op->getSourceRange();
14505 }
14506
14507 // Dereferences are usually l-values...
14508 VK = VK_LValue;
14509
14510 // ...except that certain expressions are never l-values in C.
14511 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14512 VK = VK_PRValue;
14513
14514 return Result;
14515}
14516
14517BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14519 switch (Kind) {
14520 default: llvm_unreachable("Unknown binop!");
14521 case tok::periodstar: Opc = BO_PtrMemD; break;
14522 case tok::arrowstar: Opc = BO_PtrMemI; break;
14523 case tok::star: Opc = BO_Mul; break;
14524 case tok::slash: Opc = BO_Div; break;
14525 case tok::percent: Opc = BO_Rem; break;
14526 case tok::plus: Opc = BO_Add; break;
14527 case tok::minus: Opc = BO_Sub; break;
14528 case tok::lessless: Opc = BO_Shl; break;
14529 case tok::greatergreater: Opc = BO_Shr; break;
14530 case tok::lessequal: Opc = BO_LE; break;
14531 case tok::less: Opc = BO_LT; break;
14532 case tok::greaterequal: Opc = BO_GE; break;
14533 case tok::greater: Opc = BO_GT; break;
14534 case tok::exclaimequal: Opc = BO_NE; break;
14535 case tok::equalequal: Opc = BO_EQ; break;
14536 case tok::spaceship: Opc = BO_Cmp; break;
14537 case tok::amp: Opc = BO_And; break;
14538 case tok::caret: Opc = BO_Xor; break;
14539 case tok::pipe: Opc = BO_Or; break;
14540 case tok::ampamp: Opc = BO_LAnd; break;
14541 case tok::pipepipe: Opc = BO_LOr; break;
14542 case tok::equal: Opc = BO_Assign; break;
14543 case tok::starequal: Opc = BO_MulAssign; break;
14544 case tok::slashequal: Opc = BO_DivAssign; break;
14545 case tok::percentequal: Opc = BO_RemAssign; break;
14546 case tok::plusequal: Opc = BO_AddAssign; break;
14547 case tok::minusequal: Opc = BO_SubAssign; break;
14548 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14549 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14550 case tok::ampequal: Opc = BO_AndAssign; break;
14551 case tok::caretequal: Opc = BO_XorAssign; break;
14552 case tok::pipeequal: Opc = BO_OrAssign; break;
14553 case tok::comma: Opc = BO_Comma; break;
14554 }
14555 return Opc;
14556}
14557
14559 tok::TokenKind Kind) {
14561 switch (Kind) {
14562 default: llvm_unreachable("Unknown unary op!");
14563 case tok::plusplus: Opc = UO_PreInc; break;
14564 case tok::minusminus: Opc = UO_PreDec; break;
14565 case tok::amp: Opc = UO_AddrOf; break;
14566 case tok::star: Opc = UO_Deref; break;
14567 case tok::plus: Opc = UO_Plus; break;
14568 case tok::minus: Opc = UO_Minus; break;
14569 case tok::tilde: Opc = UO_Not; break;
14570 case tok::exclaim: Opc = UO_LNot; break;
14571 case tok::kw___real: Opc = UO_Real; break;
14572 case tok::kw___imag: Opc = UO_Imag; break;
14573 case tok::kw___extension__: Opc = UO_Extension; break;
14574 }
14575 return Opc;
14576}
14577
14578const FieldDecl *
14580 // Explore the case for adding 'this->' to the LHS of a self assignment, very
14581 // common for setters.
14582 // struct A {
14583 // int X;
14584 // -void setX(int X) { X = X; }
14585 // +void setX(int X) { this->X = X; }
14586 // };
14587
14588 // Only consider parameters for self assignment fixes.
14589 if (!isa<ParmVarDecl>(SelfAssigned))
14590 return nullptr;
14591 const auto *Method =
14592 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14593 if (!Method)
14594 return nullptr;
14595
14596 const CXXRecordDecl *Parent = Method->getParent();
14597 // In theory this is fixable if the lambda explicitly captures this, but
14598 // that's added complexity that's rarely going to be used.
14599 if (Parent->isLambda())
14600 return nullptr;
14601
14602 // FIXME: Use an actual Lookup operation instead of just traversing fields
14603 // in order to get base class fields.
14604 auto Field =
14605 llvm::find_if(Parent->fields(),
14606 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14607 return F->getDeclName() == Name;
14608 });
14609 return (Field != Parent->field_end()) ? *Field : nullptr;
14610}
14611
14612/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14613/// This warning suppressed in the event of macro expansions.
14614static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14615 SourceLocation OpLoc, bool IsBuiltin) {
14617 return;
14618 if (S.isUnevaluatedContext())
14619 return;
14620 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14621 return;
14622 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14623 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14624 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14625 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14626 if (!LHSDeclRef || !RHSDeclRef ||
14627 LHSDeclRef->getLocation().isMacroID() ||
14628 RHSDeclRef->getLocation().isMacroID())
14629 return;
14630 const ValueDecl *LHSDecl =
14631 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14632 const ValueDecl *RHSDecl =
14633 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14634 if (LHSDecl != RHSDecl)
14635 return;
14636 if (LHSDecl->getType().isVolatileQualified())
14637 return;
14638 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14639 if (RefTy->getPointeeType().isVolatileQualified())
14640 return;
14641
14642 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14643 : diag::warn_self_assignment_overloaded)
14644 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14645 << RHSExpr->getSourceRange();
14646 if (const FieldDecl *SelfAssignField =
14648 Diag << 1 << SelfAssignField
14649 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14650 else
14651 Diag << 0;
14652}
14653
14654/// Check if a bitwise-& is performed on an Objective-C pointer. This
14655/// is usually indicative of introspection within the Objective-C pointer.
14657 SourceLocation OpLoc) {
14658 if (!S.getLangOpts().ObjC)
14659 return;
14660
14661 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14662 const Expr *LHS = L.get();
14663 const Expr *RHS = R.get();
14664
14666 ObjCPointerExpr = LHS;
14667 OtherExpr = RHS;
14668 }
14669 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14670 ObjCPointerExpr = RHS;
14671 OtherExpr = LHS;
14672 }
14673
14674 // This warning is deliberately made very specific to reduce false
14675 // positives with logic that uses '&' for hashing. This logic mainly
14676 // looks for code trying to introspect into tagged pointers, which
14677 // code should generally never do.
14678 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14679 unsigned Diag = diag::warn_objc_pointer_masking;
14680 // Determine if we are introspecting the result of performSelectorXXX.
14681 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14682 // Special case messages to -performSelector and friends, which
14683 // can return non-pointer values boxed in a pointer value.
14684 // Some clients may wish to silence warnings in this subcase.
14685 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14686 Selector S = ME->getSelector();
14687 StringRef SelArg0 = S.getNameForSlot(0);
14688 if (SelArg0.starts_with("performSelector"))
14689 Diag = diag::warn_objc_pointer_masking_performSelector;
14690 }
14691
14692 S.Diag(OpLoc, Diag)
14693 << ObjCPointerExpr->getSourceRange();
14694 }
14695}
14696
14698 if (!E)
14699 return nullptr;
14700 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14701 return DRE->getDecl();
14702 if (auto *ME = dyn_cast<MemberExpr>(E))
14703 return ME->getMemberDecl();
14704 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14705 return IRE->getDecl();
14706 return nullptr;
14707}
14708
14709// This helper function promotes a binary operator's operands (which are of a
14710// half vector type) to a vector of floats and then truncates the result to
14711// a vector of either half or short.
14713 BinaryOperatorKind Opc, QualType ResultTy,
14715 bool IsCompAssign, SourceLocation OpLoc,
14716 FPOptionsOverride FPFeatures) {
14717 auto &Context = S.getASTContext();
14718 assert((isVector(ResultTy, Context.HalfTy) ||
14719 isVector(ResultTy, Context.ShortTy)) &&
14720 "Result must be a vector of half or short");
14721 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14722 isVector(RHS.get()->getType(), Context.HalfTy) &&
14723 "both operands expected to be a half vector");
14724
14725 RHS = convertVector(RHS.get(), Context.FloatTy, S);
14726 QualType BinOpResTy = RHS.get()->getType();
14727
14728 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14729 // change BinOpResTy to a vector of ints.
14730 if (isVector(ResultTy, Context.ShortTy))
14731 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14732
14733 if (IsCompAssign)
14734 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14735 ResultTy, VK, OK, OpLoc, FPFeatures,
14736 BinOpResTy, BinOpResTy);
14737
14738 LHS = convertVector(LHS.get(), Context.FloatTy, S);
14739 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14740 BinOpResTy, VK, OK, OpLoc, FPFeatures);
14741 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14742}
14743
14744static std::pair<ExprResult, ExprResult>
14746 Expr *RHSExpr) {
14747 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14748 if (!S.Context.isDependenceAllowed()) {
14749 // C cannot handle TypoExpr nodes on either side of a binop because it
14750 // doesn't handle dependent types properly, so make sure any TypoExprs have
14751 // been dealt with before checking the operands.
14752 LHS = S.CorrectDelayedTyposInExpr(LHS);
14754 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14755 [Opc, LHS](Expr *E) {
14756 if (Opc != BO_Assign)
14757 return ExprResult(E);
14758 // Avoid correcting the RHS to the same Expr as the LHS.
14759 Decl *D = getDeclFromExpr(E);
14760 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14761 });
14762 }
14763 return std::make_pair(LHS, RHS);
14764}
14765
14766/// Returns true if conversion between vectors of halfs and vectors of floats
14767/// is needed.
14768static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14769 Expr *E0, Expr *E1 = nullptr) {
14770 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14772 return false;
14773
14774 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14775 QualType Ty = E->IgnoreImplicit()->getType();
14776
14777 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14778 // to vectors of floats. Although the element type of the vectors is __fp16,
14779 // the vectors shouldn't be treated as storage-only types. See the
14780 // discussion here: https://reviews.llvm.org/rG825235c140e7
14781 if (const VectorType *VT = Ty->getAs<VectorType>()) {
14782 if (VT->getVectorKind() == VectorKind::Neon)
14783 return false;
14784 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14785 }
14786 return false;
14787 };
14788
14789 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14790}
14791
14794 Expr *LHSExpr, Expr *RHSExpr) {
14795 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14796 // The syntax only allows initializer lists on the RHS of assignment,
14797 // so we don't need to worry about accepting invalid code for
14798 // non-assignment operators.
14799 // C++11 5.17p9:
14800 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14801 // of x = {} is x = T().
14803 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14804 InitializedEntity Entity =
14806 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14807 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14808 if (Init.isInvalid())
14809 return Init;
14810 RHSExpr = Init.get();
14811 }
14812
14813 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14814 QualType ResultTy; // Result type of the binary operator.
14815 // The following two variables are used for compound assignment operators
14816 QualType CompLHSTy; // Type of LHS after promotions for computation
14817 QualType CompResultTy; // Type of computation result
14820 bool ConvertHalfVec = false;
14821
14822 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14823 if (!LHS.isUsable() || !RHS.isUsable())
14824 return ExprError();
14825
14826 if (getLangOpts().OpenCL) {
14827 QualType LHSTy = LHSExpr->getType();
14828 QualType RHSTy = RHSExpr->getType();
14829 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14830 // the ATOMIC_VAR_INIT macro.
14831 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14832 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14833 if (BO_Assign == Opc)
14834 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14835 else
14836 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14837 return ExprError();
14838 }
14839
14840 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14841 // only with a builtin functions and therefore should be disallowed here.
14842 if (LHSTy->isImageType() || RHSTy->isImageType() ||
14843 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14844 LHSTy->isPipeType() || RHSTy->isPipeType() ||
14845 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14846 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14847 return ExprError();
14848 }
14849 }
14850
14851 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14852 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14853
14854 switch (Opc) {
14855 case BO_Assign:
14856 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
14857 if (getLangOpts().CPlusPlus &&
14858 LHS.get()->getObjectKind() != OK_ObjCProperty) {
14859 VK = LHS.get()->getValueKind();
14860 OK = LHS.get()->getObjectKind();
14861 }
14862 if (!ResultTy.isNull()) {
14863 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14864 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14865
14866 // Avoid copying a block to the heap if the block is assigned to a local
14867 // auto variable that is declared in the same scope as the block. This
14868 // optimization is unsafe if the local variable is declared in an outer
14869 // scope. For example:
14870 //
14871 // BlockTy b;
14872 // {
14873 // b = ^{...};
14874 // }
14875 // // It is unsafe to invoke the block here if it wasn't copied to the
14876 // // heap.
14877 // b();
14878
14879 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14880 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14881 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14882 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14883 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14884
14886 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14888 }
14889 RecordModifiableNonNullParam(*this, LHS.get());
14890 break;
14891 case BO_PtrMemD:
14892 case BO_PtrMemI:
14893 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14894 Opc == BO_PtrMemI);
14895 break;
14896 case BO_Mul:
14897 case BO_Div:
14898 ConvertHalfVec = true;
14899 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14900 Opc == BO_Div);
14901 break;
14902 case BO_Rem:
14903 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14904 break;
14905 case BO_Add:
14906 ConvertHalfVec = true;
14907 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14908 break;
14909 case BO_Sub:
14910 ConvertHalfVec = true;
14911 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14912 break;
14913 case BO_Shl:
14914 case BO_Shr:
14915 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14916 break;
14917 case BO_LE:
14918 case BO_LT:
14919 case BO_GE:
14920 case BO_GT:
14921 ConvertHalfVec = true;
14922 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14923
14924 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
14925 BI && BI->isComparisonOp())
14926 Diag(OpLoc, diag::warn_consecutive_comparison);
14927
14928 break;
14929 case BO_EQ:
14930 case BO_NE:
14931 ConvertHalfVec = true;
14932 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14933 break;
14934 case BO_Cmp:
14935 ConvertHalfVec = true;
14936 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14937 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14938 break;
14939 case BO_And:
14940 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14941 [[fallthrough]];
14942 case BO_Xor:
14943 case BO_Or:
14944 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14945 break;
14946 case BO_LAnd:
14947 case BO_LOr:
14948 ConvertHalfVec = true;
14949 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14950 break;
14951 case BO_MulAssign:
14952 case BO_DivAssign:
14953 ConvertHalfVec = true;
14954 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14955 Opc == BO_DivAssign);
14956 CompLHSTy = CompResultTy;
14957 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14958 ResultTy =
14959 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14960 break;
14961 case BO_RemAssign:
14962 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14963 CompLHSTy = CompResultTy;
14964 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14965 ResultTy =
14966 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14967 break;
14968 case BO_AddAssign:
14969 ConvertHalfVec = true;
14970 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14971 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14972 ResultTy =
14973 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14974 break;
14975 case BO_SubAssign:
14976 ConvertHalfVec = true;
14977 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14978 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14979 ResultTy =
14980 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14981 break;
14982 case BO_ShlAssign:
14983 case BO_ShrAssign:
14984 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14985 CompLHSTy = CompResultTy;
14986 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14987 ResultTy =
14988 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14989 break;
14990 case BO_AndAssign:
14991 case BO_OrAssign: // fallthrough
14992 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14993 [[fallthrough]];
14994 case BO_XorAssign:
14995 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14996 CompLHSTy = CompResultTy;
14997 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14998 ResultTy =
14999 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15000 break;
15001 case BO_Comma:
15002 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15003 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15004 VK = RHS.get()->getValueKind();
15005 OK = RHS.get()->getObjectKind();
15006 }
15007 break;
15008 }
15009 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15010 return ExprError();
15011
15012 // Some of the binary operations require promoting operands of half vector to
15013 // float vectors and truncating the result back to half vector. For now, we do
15014 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15015 // arm64).
15016 assert(
15017 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15018 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15019 "both sides are half vectors or neither sides are");
15020 ConvertHalfVec =
15021 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15022
15023 // Check for array bounds violations for both sides of the BinaryOperator
15024 CheckArrayAccess(LHS.get());
15025 CheckArrayAccess(RHS.get());
15026
15027 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15028 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15029 &Context.Idents.get("object_setClass"),
15031 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15032 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15033 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15035 "object_setClass(")
15036 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15037 ",")
15038 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15039 }
15040 else
15041 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15042 }
15043 else if (const ObjCIvarRefExpr *OIRE =
15044 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15045 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15046
15047 // Opc is not a compound assignment if CompResultTy is null.
15048 if (CompResultTy.isNull()) {
15049 if (ConvertHalfVec)
15050 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15051 OpLoc, CurFPFeatureOverrides());
15052 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15053 VK, OK, OpLoc, CurFPFeatureOverrides());
15054 }
15055
15056 // Handle compound assignments.
15057 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15059 VK = VK_LValue;
15060 OK = LHS.get()->getObjectKind();
15061 }
15062
15063 // The LHS is not converted to the result type for fixed-point compound
15064 // assignment as the common type is computed on demand. Reset the CompLHSTy
15065 // to the LHS type we would have gotten after unary conversions.
15066 if (CompResultTy->isFixedPointType())
15067 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15068
15069 if (ConvertHalfVec)
15070 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15071 OpLoc, CurFPFeatureOverrides());
15072
15074 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15075 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15076}
15077
15078/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15079/// operators are mixed in a way that suggests that the programmer forgot that
15080/// comparison operators have higher precedence. The most typical example of
15081/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15083 SourceLocation OpLoc, Expr *LHSExpr,
15084 Expr *RHSExpr) {
15085 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15086 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15087
15088 // Check that one of the sides is a comparison operator and the other isn't.
15089 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15090 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15091 if (isLeftComp == isRightComp)
15092 return;
15093
15094 // Bitwise operations are sometimes used as eager logical ops.
15095 // Don't diagnose this.
15096 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15097 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15098 if (isLeftBitwise || isRightBitwise)
15099 return;
15100
15101 SourceRange DiagRange = isLeftComp
15102 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15103 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15104 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15105 SourceRange ParensRange =
15106 isLeftComp
15107 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15108 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15109
15110 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15111 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15112 SuggestParentheses(Self, OpLoc,
15113 Self.PDiag(diag::note_precedence_silence) << OpStr,
15114 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15115 SuggestParentheses(Self, OpLoc,
15116 Self.PDiag(diag::note_precedence_bitwise_first)
15118 ParensRange);
15119}
15120
15121/// It accepts a '&&' expr that is inside a '||' one.
15122/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15123/// in parentheses.
15124static void
15126 BinaryOperator *Bop) {
15127 assert(Bop->getOpcode() == BO_LAnd);
15128 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15129 << Bop->getSourceRange() << OpLoc;
15131 Self.PDiag(diag::note_precedence_silence)
15132 << Bop->getOpcodeStr(),
15133 Bop->getSourceRange());
15134}
15135
15136/// Look for '&&' in the left hand of a '||' expr.
15138 Expr *LHSExpr, Expr *RHSExpr) {
15139 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15140 if (Bop->getOpcode() == BO_LAnd) {
15141 // If it's "string_literal && a || b" don't warn since the precedence
15142 // doesn't matter.
15143 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15144 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15145 } else if (Bop->getOpcode() == BO_LOr) {
15146 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15147 // If it's "a || b && string_literal || c" we didn't warn earlier for
15148 // "a || b && string_literal", but warn now.
15149 if (RBop->getOpcode() == BO_LAnd &&
15150 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15151 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15152 }
15153 }
15154 }
15155}
15156
15157/// Look for '&&' in the right hand of a '||' expr.
15159 Expr *LHSExpr, Expr *RHSExpr) {
15160 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15161 if (Bop->getOpcode() == BO_LAnd) {
15162 // If it's "a || b && string_literal" don't warn since the precedence
15163 // doesn't matter.
15164 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15165 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15166 }
15167 }
15168}
15169
15170/// Look for bitwise op in the left or right hand of a bitwise op with
15171/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15172/// the '&' expression in parentheses.
15174 SourceLocation OpLoc, Expr *SubExpr) {
15175 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15176 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15177 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15178 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15179 << Bop->getSourceRange() << OpLoc;
15180 SuggestParentheses(S, Bop->getOperatorLoc(),
15181 S.PDiag(diag::note_precedence_silence)
15182 << Bop->getOpcodeStr(),
15183 Bop->getSourceRange());
15184 }
15185 }
15186}
15187
15189 Expr *SubExpr, StringRef Shift) {
15190 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15191 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15192 StringRef Op = Bop->getOpcodeStr();
15193 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15194 << Bop->getSourceRange() << OpLoc << Shift << Op;
15195 SuggestParentheses(S, Bop->getOperatorLoc(),
15196 S.PDiag(diag::note_precedence_silence) << Op,
15197 Bop->getSourceRange());
15198 }
15199 }
15200}
15201
15203 Expr *LHSExpr, Expr *RHSExpr) {
15204 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15205 if (!OCE)
15206 return;
15207
15208 FunctionDecl *FD = OCE->getDirectCallee();
15209 if (!FD || !FD->isOverloadedOperator())
15210 return;
15211
15213 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15214 return;
15215
15216 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15217 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15218 << (Kind == OO_LessLess);
15220 S.PDiag(diag::note_precedence_silence)
15221 << (Kind == OO_LessLess ? "<<" : ">>"),
15222 OCE->getSourceRange());
15224 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15225 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15226}
15227
15228/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15229/// precedence.
15231 SourceLocation OpLoc, Expr *LHSExpr,
15232 Expr *RHSExpr){
15233 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15235 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15236
15237 // Diagnose "arg1 & arg2 | arg3"
15238 if ((Opc == BO_Or || Opc == BO_Xor) &&
15239 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15240 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15241 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15242 }
15243
15244 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15245 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15246 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15247 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15248 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15249 }
15250
15251 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15252 || Opc == BO_Shr) {
15253 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15254 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15255 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15256 }
15257
15258 // Warn on overloaded shift operators and comparisons, such as:
15259 // cout << 5 == 4;
15261 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15262}
15263
15265 Expr *Operand) {
15266 if (auto *CT = Operand->getType()->getAs<ComplexType>()) {
15267 QualType ElementType = CT->getElementType();
15268 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
15270 if (ElementType->isFloatingType() && IsComplexRangePromoted) {
15271 ASTContext &Ctx = S.getASTContext();
15272 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
15273 const llvm::fltSemantics &ElementTypeSemantics =
15274 Ctx.getFloatTypeSemantics(ElementType);
15275 const llvm::fltSemantics &HigherElementTypeSemantics =
15276 Ctx.getFloatTypeSemantics(HigherElementType);
15277 if (llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
15278 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) {
15279 // Retain the location of the first use of higher precision type.
15282 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
15283 if (Type == HigherElementType) {
15284 Num++;
15285 return;
15286 }
15287 }
15288 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
15289 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
15290 }
15291 }
15292 }
15293}
15294
15296 tok::TokenKind Kind,
15297 Expr *LHSExpr, Expr *RHSExpr) {
15298 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15299 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15300 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15301
15302 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15303 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15304
15305 // Emit warnings if the requested higher precision type equal to the current
15306 // type precision.
15307 if (Kind == tok::TokenKind::slash)
15308 DetectPrecisionLossInComplexDivision(*this, TokLoc, LHSExpr);
15309
15310 BuiltinCountedByRefKind K =
15311 BinaryOperator::isAssignmentOp(Opc) ? AssignmentKind : BinaryExprKind;
15312
15313 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
15314 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
15315
15316 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15317}
15318
15320 UnresolvedSetImpl &Functions) {
15322 if (OverOp != OO_None && OverOp != OO_Equal)
15323 LookupOverloadedOperatorName(OverOp, S, Functions);
15324
15325 // In C++20 onwards, we may have a second operator to look up.
15326 if (getLangOpts().CPlusPlus20) {
15328 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15329 }
15330}
15331
15332/// Build an overloaded binary operator expression in the given scope.
15335 Expr *LHS, Expr *RHS) {
15336 switch (Opc) {
15337 case BO_Assign:
15338 // In the non-overloaded case, we warn about self-assignment (x = x) for
15339 // both simple assignment and certain compound assignments where algebra
15340 // tells us the operation yields a constant result. When the operator is
15341 // overloaded, we can't do the latter because we don't want to assume that
15342 // those algebraic identities still apply; for example, a path-building
15343 // library might use operator/= to append paths. But it's still reasonable
15344 // to assume that simple assignment is just moving/copying values around
15345 // and so self-assignment is likely a bug.
15346 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15347 [[fallthrough]];
15348 case BO_DivAssign:
15349 case BO_RemAssign:
15350 case BO_SubAssign:
15351 case BO_AndAssign:
15352 case BO_OrAssign:
15353 case BO_XorAssign:
15354 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15355 break;
15356 default:
15357 break;
15358 }
15359
15360 // Find all of the overloaded operators visible from this point.
15361 UnresolvedSet<16> Functions;
15362 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15363
15364 // Build the (potentially-overloaded, potentially-dependent)
15365 // binary operation.
15366 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15367}
15368
15371 Expr *LHSExpr, Expr *RHSExpr) {
15372 ExprResult LHS, RHS;
15373 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15374 if (!LHS.isUsable() || !RHS.isUsable())
15375 return ExprError();
15376 LHSExpr = LHS.get();
15377 RHSExpr = RHS.get();
15378
15379 // We want to end up calling one of SemaPseudoObject::checkAssignment
15380 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15381 // both expressions are overloadable or either is type-dependent),
15382 // or CreateBuiltinBinOp (in any other case). We also want to get
15383 // any placeholder types out of the way.
15384
15385 // Handle pseudo-objects in the LHS.
15386 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15387 // Assignments with a pseudo-object l-value need special analysis.
15388 if (pty->getKind() == BuiltinType::PseudoObject &&
15390 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15391
15392 // Don't resolve overloads if the other type is overloadable.
15393 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15394 // We can't actually test that if we still have a placeholder,
15395 // though. Fortunately, none of the exceptions we see in that
15396 // code below are valid when the LHS is an overload set. Note
15397 // that an overload set can be dependently-typed, but it never
15398 // instantiates to having an overloadable type.
15399 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15400 if (resolvedRHS.isInvalid()) return ExprError();
15401 RHSExpr = resolvedRHS.get();
15402
15403 if (RHSExpr->isTypeDependent() ||
15404 RHSExpr->getType()->isOverloadableType())
15405 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15406 }
15407
15408 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15409 // template, diagnose the missing 'template' keyword instead of diagnosing
15410 // an invalid use of a bound member function.
15411 //
15412 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15413 // to C++1z [over.over]/1.4, but we already checked for that case above.
15414 if (Opc == BO_LT && inTemplateInstantiation() &&
15415 (pty->getKind() == BuiltinType::BoundMember ||
15416 pty->getKind() == BuiltinType::Overload)) {
15417 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15418 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15419 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15420 return isa<FunctionTemplateDecl>(ND);
15421 })) {
15422 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15423 : OE->getNameLoc(),
15424 diag::err_template_kw_missing)
15425 << OE->getName().getAsString() << "";
15426 return ExprError();
15427 }
15428 }
15429
15430 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15431 if (LHS.isInvalid()) return ExprError();
15432 LHSExpr = LHS.get();
15433 }
15434
15435 // Handle pseudo-objects in the RHS.
15436 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15437 // An overload in the RHS can potentially be resolved by the type
15438 // being assigned to.
15439 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15440 if (getLangOpts().CPlusPlus &&
15441 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15442 LHSExpr->getType()->isOverloadableType()))
15443 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15444
15445 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15446 }
15447
15448 // Don't resolve overloads if the other type is overloadable.
15449 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15450 LHSExpr->getType()->isOverloadableType())
15451 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15452
15453 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15454 if (!resolvedRHS.isUsable()) return ExprError();
15455 RHSExpr = resolvedRHS.get();
15456 }
15457
15458 if (getLangOpts().CPlusPlus) {
15459 // Otherwise, build an overloaded op if either expression is type-dependent
15460 // or has an overloadable type.
15461 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15462 LHSExpr->getType()->isOverloadableType() ||
15463 RHSExpr->getType()->isOverloadableType())
15464 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15465 }
15466
15467 if (getLangOpts().RecoveryAST &&
15468 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15469 assert(!getLangOpts().CPlusPlus);
15470 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15471 "Should only occur in error-recovery path.");
15473 // C [6.15.16] p3:
15474 // An assignment expression has the value of the left operand after the
15475 // assignment, but is not an lvalue.
15477 Context, LHSExpr, RHSExpr, Opc,
15479 OpLoc, CurFPFeatureOverrides());
15480 QualType ResultType;
15481 switch (Opc) {
15482 case BO_Assign:
15483 ResultType = LHSExpr->getType().getUnqualifiedType();
15484 break;
15485 case BO_LT:
15486 case BO_GT:
15487 case BO_LE:
15488 case BO_GE:
15489 case BO_EQ:
15490 case BO_NE:
15491 case BO_LAnd:
15492 case BO_LOr:
15493 // These operators have a fixed result type regardless of operands.
15494 ResultType = Context.IntTy;
15495 break;
15496 case BO_Comma:
15497 ResultType = RHSExpr->getType();
15498 break;
15499 default:
15500 ResultType = Context.DependentTy;
15501 break;
15502 }
15503 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15504 VK_PRValue, OK_Ordinary, OpLoc,
15506 }
15507
15508 // Build a built-in binary operation.
15509 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15510}
15511
15513 if (T.isNull() || T->isDependentType())
15514 return false;
15515
15516 if (!Ctx.isPromotableIntegerType(T))
15517 return true;
15518
15519 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15520}
15521
15523 UnaryOperatorKind Opc, Expr *InputExpr,
15524 bool IsAfterAmp) {
15525 ExprResult Input = InputExpr;
15528 QualType resultType;
15529 bool CanOverflow = false;
15530
15531 bool ConvertHalfVec = false;
15532 if (getLangOpts().OpenCL) {
15533 QualType Ty = InputExpr->getType();
15534 // The only legal unary operation for atomics is '&'.
15535 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15536 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15537 // only with a builtin functions and therefore should be disallowed here.
15538 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15539 || Ty->isBlockPointerType())) {
15540 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15541 << InputExpr->getType()
15542 << Input.get()->getSourceRange());
15543 }
15544 }
15545
15546 if (getLangOpts().HLSL && OpLoc.isValid()) {
15547 if (Opc == UO_AddrOf)
15548 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15549 if (Opc == UO_Deref)
15550 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15551 }
15552
15553 if (InputExpr->isTypeDependent() &&
15554 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
15555 resultType = Context.DependentTy;
15556 } else {
15557 switch (Opc) {
15558 case UO_PreInc:
15559 case UO_PreDec:
15560 case UO_PostInc:
15561 case UO_PostDec:
15562 resultType =
15563 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
15564 Opc == UO_PreInc || Opc == UO_PostInc,
15565 Opc == UO_PreInc || Opc == UO_PreDec);
15566 CanOverflow = isOverflowingIntegerType(Context, resultType);
15567 break;
15568 case UO_AddrOf:
15569 resultType = CheckAddressOfOperand(Input, OpLoc);
15570 CheckAddressOfNoDeref(InputExpr);
15571 RecordModifiableNonNullParam(*this, InputExpr);
15572 break;
15573 case UO_Deref: {
15575 if (Input.isInvalid())
15576 return ExprError();
15577 resultType =
15578 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15579 break;
15580 }
15581 case UO_Plus:
15582 case UO_Minus:
15583 CanOverflow = Opc == UO_Minus &&
15585 Input = UsualUnaryConversions(Input.get());
15586 if (Input.isInvalid())
15587 return ExprError();
15588 // Unary plus and minus require promoting an operand of half vector to a
15589 // float vector and truncating the result back to a half vector. For now,
15590 // we do this only when HalfArgsAndReturns is set (that is, when the
15591 // target is arm or arm64).
15592 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15593
15594 // If the operand is a half vector, promote it to a float vector.
15595 if (ConvertHalfVec)
15596 Input = convertVector(Input.get(), Context.FloatTy, *this);
15597 resultType = Input.get()->getType();
15598 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15599 break;
15600 else if (resultType->isVectorType() &&
15601 // The z vector extensions don't allow + or - with bool vectors.
15602 (!Context.getLangOpts().ZVector ||
15603 resultType->castAs<VectorType>()->getVectorKind() !=
15605 break;
15606 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
15607 break;
15608 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15609 Opc == UO_Plus && resultType->isPointerType())
15610 break;
15611
15612 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15613 << resultType << Input.get()->getSourceRange());
15614
15615 case UO_Not: // bitwise complement
15616 Input = UsualUnaryConversions(Input.get());
15617 if (Input.isInvalid())
15618 return ExprError();
15619 resultType = Input.get()->getType();
15620 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15621 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15622 // C99 does not support '~' for complex conjugation.
15623 Diag(OpLoc, diag::ext_integer_complement_complex)
15624 << resultType << Input.get()->getSourceRange();
15625 else if (resultType->hasIntegerRepresentation())
15626 break;
15627 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15628 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15629 // on vector float types.
15630 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15631 if (!T->isIntegerType())
15632 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15633 << resultType << Input.get()->getSourceRange());
15634 } else {
15635 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15636 << resultType << Input.get()->getSourceRange());
15637 }
15638 break;
15639
15640 case UO_LNot: // logical negation
15641 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15643 if (Input.isInvalid())
15644 return ExprError();
15645 resultType = Input.get()->getType();
15646
15647 // Though we still have to promote half FP to float...
15648 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15649 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
15650 .get();
15651 resultType = Context.FloatTy;
15652 }
15653
15654 // WebAsembly tables can't be used in unary expressions.
15655 if (resultType->isPointerType() &&
15657 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15658 << resultType << Input.get()->getSourceRange());
15659 }
15660
15661 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15662 // C99 6.5.3.3p1: ok, fallthrough;
15663 if (Context.getLangOpts().CPlusPlus) {
15664 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15665 // operand contextually converted to bool.
15666 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15667 ScalarTypeToBooleanCastKind(resultType));
15668 } else if (Context.getLangOpts().OpenCL &&
15669 Context.getLangOpts().OpenCLVersion < 120) {
15670 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15671 // operate on scalar float types.
15672 if (!resultType->isIntegerType() && !resultType->isPointerType())
15673 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15674 << resultType << Input.get()->getSourceRange());
15675 }
15676 } else if (resultType->isExtVectorType()) {
15677 if (Context.getLangOpts().OpenCL &&
15679 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15680 // operate on vector float types.
15681 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15682 if (!T->isIntegerType())
15683 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15684 << resultType << Input.get()->getSourceRange());
15685 }
15686 // Vector logical not returns the signed variant of the operand type.
15687 resultType = GetSignedVectorType(resultType);
15688 break;
15689 } else if (Context.getLangOpts().CPlusPlus &&
15690 resultType->isVectorType()) {
15691 const VectorType *VTy = resultType->castAs<VectorType>();
15692 if (VTy->getVectorKind() != VectorKind::Generic)
15693 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15694 << resultType << Input.get()->getSourceRange());
15695
15696 // Vector logical not returns the signed variant of the operand type.
15697 resultType = GetSignedVectorType(resultType);
15698 break;
15699 } else {
15700 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15701 << resultType << Input.get()->getSourceRange());
15702 }
15703
15704 // LNot always has type int. C99 6.5.3.3p5.
15705 // In C++, it's bool. C++ 5.3.1p8
15706 resultType = Context.getLogicalOperationType();
15707 break;
15708 case UO_Real:
15709 case UO_Imag:
15710 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15711 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
15712 // ordinary complex l-values to ordinary l-values and all other values to
15713 // r-values.
15714 if (Input.isInvalid())
15715 return ExprError();
15716 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15717 if (Input.get()->isGLValue() &&
15718 Input.get()->getObjectKind() == OK_Ordinary)
15719 VK = Input.get()->getValueKind();
15720 } else if (!getLangOpts().CPlusPlus) {
15721 // In C, a volatile scalar is read by __imag. In C++, it is not.
15722 Input = DefaultLvalueConversion(Input.get());
15723 }
15724 break;
15725 case UO_Extension:
15726 resultType = Input.get()->getType();
15727 VK = Input.get()->getValueKind();
15728 OK = Input.get()->getObjectKind();
15729 break;
15730 case UO_Coawait:
15731 // It's unnecessary to represent the pass-through operator co_await in the
15732 // AST; just return the input expression instead.
15733 assert(!Input.get()->getType()->isDependentType() &&
15734 "the co_await expression must be non-dependant before "
15735 "building operator co_await");
15736 return Input;
15737 }
15738 }
15739 if (resultType.isNull() || Input.isInvalid())
15740 return ExprError();
15741
15742 // Check for array bounds violations in the operand of the UnaryOperator,
15743 // except for the '*' and '&' operators that have to be handled specially
15744 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15745 // that are explicitly defined as valid by the standard).
15746 if (Opc != UO_AddrOf && Opc != UO_Deref)
15747 CheckArrayAccess(Input.get());
15748
15749 auto *UO =
15750 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15751 OpLoc, CanOverflow, CurFPFeatureOverrides());
15752
15753 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15754 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15756 ExprEvalContexts.back().PossibleDerefs.insert(UO);
15757
15758 // Convert the result back to a half vector.
15759 if (ConvertHalfVec)
15760 return convertVector(UO, Context.HalfTy, *this);
15761 return UO;
15762}
15763
15765 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15766 if (!DRE->getQualifier())
15767 return false;
15768
15769 ValueDecl *VD = DRE->getDecl();
15770 if (!VD->isCXXClassMember())
15771 return false;
15772
15773 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15774 return true;
15775 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15776 return Method->isImplicitObjectMemberFunction();
15777
15778 return false;
15779 }
15780
15781 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15782 if (!ULE->getQualifier())
15783 return false;
15784
15785 for (NamedDecl *D : ULE->decls()) {
15786 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15787 if (Method->isImplicitObjectMemberFunction())
15788 return true;
15789 } else {
15790 // Overload set does not contain methods.
15791 break;
15792 }
15793 }
15794
15795 return false;
15796 }
15797
15798 return false;
15799}
15800
15802 UnaryOperatorKind Opc, Expr *Input,
15803 bool IsAfterAmp) {
15804 // First things first: handle placeholders so that the
15805 // overloaded-operator check considers the right type.
15806 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15807 // Increment and decrement of pseudo-object references.
15808 if (pty->getKind() == BuiltinType::PseudoObject &&
15810 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
15811
15812 // extension is always a builtin operator.
15813 if (Opc == UO_Extension)
15814 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15815
15816 // & gets special logic for several kinds of placeholder.
15817 // The builtin code knows what to do.
15818 if (Opc == UO_AddrOf &&
15819 (pty->getKind() == BuiltinType::Overload ||
15820 pty->getKind() == BuiltinType::UnknownAny ||
15821 pty->getKind() == BuiltinType::BoundMember))
15822 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15823
15824 // Anything else needs to be handled now.
15826 if (Result.isInvalid()) return ExprError();
15827 Input = Result.get();
15828 }
15829
15830 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15832 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15833 // Find all of the overloaded operators visible from this point.
15834 UnresolvedSet<16> Functions;
15836 if (S && OverOp != OO_None)
15837 LookupOverloadedOperatorName(OverOp, S, Functions);
15838
15839 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15840 }
15841
15842 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
15843}
15844
15846 Expr *Input, bool IsAfterAmp) {
15847 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
15848 IsAfterAmp);
15849}
15850
15852 LabelDecl *TheDecl) {
15853 TheDecl->markUsed(Context);
15854 // Create the AST node. The address of a label always has type 'void*'.
15855 auto *Res = new (Context) AddrLabelExpr(
15856 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
15857
15858 if (getCurFunction())
15859 getCurFunction()->AddrLabels.push_back(Res);
15860
15861 return Res;
15862}
15863
15866 // Make sure we diagnose jumping into a statement expression.
15868}
15869
15871 // Note that function is also called by TreeTransform when leaving a
15872 // StmtExpr scope without rebuilding anything.
15873
15876}
15877
15879 SourceLocation RPLoc) {
15880 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15881}
15882
15884 SourceLocation RPLoc, unsigned TemplateDepth) {
15885 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15886 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15887
15890 assert(!Cleanup.exprNeedsCleanups() &&
15891 "cleanups within StmtExpr not correctly bound!");
15893
15894 // FIXME: there are a variety of strange constraints to enforce here, for
15895 // example, it is not possible to goto into a stmt expression apparently.
15896 // More semantic analysis is needed.
15897
15898 // If there are sub-stmts in the compound stmt, take the type of the last one
15899 // as the type of the stmtexpr.
15900 QualType Ty = Context.VoidTy;
15901 bool StmtExprMayBindToTemp = false;
15902 if (!Compound->body_empty()) {
15903 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15904 if (const auto *LastStmt =
15905 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15906 if (const Expr *Value = LastStmt->getExprStmt()) {
15907 StmtExprMayBindToTemp = true;
15908 Ty = Value->getType();
15909 }
15910 }
15911 }
15912
15913 // FIXME: Check that expression type is complete/non-abstract; statement
15914 // expressions are not lvalues.
15915 Expr *ResStmtExpr =
15916 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15917 if (StmtExprMayBindToTemp)
15918 return MaybeBindToTemporary(ResStmtExpr);
15919 return ResStmtExpr;
15920}
15921
15923 if (ER.isInvalid())
15924 return ExprError();
15925
15926 // Do function/array conversion on the last expression, but not
15927 // lvalue-to-rvalue. However, initialize an unqualified type.
15929 if (ER.isInvalid())
15930 return ExprError();
15931 Expr *E = ER.get();
15932
15933 if (E->isTypeDependent())
15934 return E;
15935
15936 // In ARC, if the final expression ends in a consume, splice
15937 // the consume out and bind it later. In the alternate case
15938 // (when dealing with a retainable type), the result
15939 // initialization will create a produce. In both cases the
15940 // result will be +1, and we'll need to balance that out with
15941 // a bind.
15942 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15943 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15944 return Cast->getSubExpr();
15945
15946 // FIXME: Provide a better location for the initialization.
15950 SourceLocation(), E);
15951}
15952
15954 TypeSourceInfo *TInfo,
15955 ArrayRef<OffsetOfComponent> Components,
15956 SourceLocation RParenLoc) {
15957 QualType ArgTy = TInfo->getType();
15958 bool Dependent = ArgTy->isDependentType();
15959 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15960
15961 // We must have at least one component that refers to the type, and the first
15962 // one is known to be a field designator. Verify that the ArgTy represents
15963 // a struct/union/class.
15964 if (!Dependent && !ArgTy->isRecordType())
15965 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15966 << ArgTy << TypeRange);
15967
15968 // Type must be complete per C99 7.17p3 because a declaring a variable
15969 // with an incomplete type would be ill-formed.
15970 if (!Dependent
15971 && RequireCompleteType(BuiltinLoc, ArgTy,
15972 diag::err_offsetof_incomplete_type, TypeRange))
15973 return ExprError();
15974
15975 bool DidWarnAboutNonPOD = false;
15976 QualType CurrentType = ArgTy;
15979 for (const OffsetOfComponent &OC : Components) {
15980 if (OC.isBrackets) {
15981 // Offset of an array sub-field. TODO: Should we allow vector elements?
15982 if (!CurrentType->isDependentType()) {
15983 const ArrayType *AT = Context.getAsArrayType(CurrentType);
15984 if(!AT)
15985 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15986 << CurrentType);
15987 CurrentType = AT->getElementType();
15988 } else
15989 CurrentType = Context.DependentTy;
15990
15991 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15992 if (IdxRval.isInvalid())
15993 return ExprError();
15994 Expr *Idx = IdxRval.get();
15995
15996 // The expression must be an integral expression.
15997 // FIXME: An integral constant expression?
15998 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15999 !Idx->getType()->isIntegerType())
16000 return ExprError(
16001 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16002 << Idx->getSourceRange());
16003
16004 // Record this array index.
16005 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16006 Exprs.push_back(Idx);
16007 continue;
16008 }
16009
16010 // Offset of a field.
16011 if (CurrentType->isDependentType()) {
16012 // We have the offset of a field, but we can't look into the dependent
16013 // type. Just record the identifier of the field.
16014 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16015 CurrentType = Context.DependentTy;
16016 continue;
16017 }
16018
16019 // We need to have a complete type to look into.
16020 if (RequireCompleteType(OC.LocStart, CurrentType,
16021 diag::err_offsetof_incomplete_type))
16022 return ExprError();
16023
16024 // Look for the designated field.
16025 const RecordType *RC = CurrentType->getAs<RecordType>();
16026 if (!RC)
16027 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16028 << CurrentType);
16029 RecordDecl *RD = RC->getDecl();
16030
16031 // C++ [lib.support.types]p5:
16032 // The macro offsetof accepts a restricted set of type arguments in this
16033 // International Standard. type shall be a POD structure or a POD union
16034 // (clause 9).
16035 // C++11 [support.types]p4:
16036 // If type is not a standard-layout class (Clause 9), the results are
16037 // undefined.
16038 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16039 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16040 unsigned DiagID =
16041 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16042 : diag::ext_offsetof_non_pod_type;
16043
16044 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16045 Diag(BuiltinLoc, DiagID)
16046 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16047 DidWarnAboutNonPOD = true;
16048 }
16049 }
16050
16051 // Look for the field.
16052 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16053 LookupQualifiedName(R, RD);
16054 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16055 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16056 if (!MemberDecl) {
16057 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16058 MemberDecl = IndirectMemberDecl->getAnonField();
16059 }
16060
16061 if (!MemberDecl) {
16062 // Lookup could be ambiguous when looking up a placeholder variable
16063 // __builtin_offsetof(S, _).
16064 // In that case we would already have emitted a diagnostic
16065 if (!R.isAmbiguous())
16066 Diag(BuiltinLoc, diag::err_no_member)
16067 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16068 return ExprError();
16069 }
16070
16071 // C99 7.17p3:
16072 // (If the specified member is a bit-field, the behavior is undefined.)
16073 //
16074 // We diagnose this as an error.
16075 if (MemberDecl->isBitField()) {
16076 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16077 << MemberDecl->getDeclName()
16078 << SourceRange(BuiltinLoc, RParenLoc);
16079 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16080 return ExprError();
16081 }
16082
16083 RecordDecl *Parent = MemberDecl->getParent();
16084 if (IndirectMemberDecl)
16085 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16086
16087 // If the member was found in a base class, introduce OffsetOfNodes for
16088 // the base class indirections.
16089 CXXBasePaths Paths;
16090 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16091 Paths)) {
16092 if (Paths.getDetectedVirtual()) {
16093 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16094 << MemberDecl->getDeclName()
16095 << SourceRange(BuiltinLoc, RParenLoc);
16096 return ExprError();
16097 }
16098
16099 CXXBasePath &Path = Paths.front();
16100 for (const CXXBasePathElement &B : Path)
16101 Comps.push_back(OffsetOfNode(B.Base));
16102 }
16103
16104 if (IndirectMemberDecl) {
16105 for (auto *FI : IndirectMemberDecl->chain()) {
16106 assert(isa<FieldDecl>(FI));
16107 Comps.push_back(OffsetOfNode(OC.LocStart,
16108 cast<FieldDecl>(FI), OC.LocEnd));
16109 }
16110 } else
16111 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16112
16113 CurrentType = MemberDecl->getType().getNonReferenceType();
16114 }
16115
16116 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16117 Comps, Exprs, RParenLoc);
16118}
16119
16121 SourceLocation BuiltinLoc,
16123 ParsedType ParsedArgTy,
16124 ArrayRef<OffsetOfComponent> Components,
16125 SourceLocation RParenLoc) {
16126
16127 TypeSourceInfo *ArgTInfo;
16128 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16129 if (ArgTy.isNull())
16130 return ExprError();
16131
16132 if (!ArgTInfo)
16133 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16134
16135 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16136}
16137
16138
16140 Expr *CondExpr,
16141 Expr *LHSExpr, Expr *RHSExpr,
16142 SourceLocation RPLoc) {
16143 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16144
16147 QualType resType;
16148 bool CondIsTrue = false;
16149 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16150 resType = Context.DependentTy;
16151 } else {
16152 // The conditional expression is required to be a constant expression.
16153 llvm::APSInt condEval(32);
16155 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16156 if (CondICE.isInvalid())
16157 return ExprError();
16158 CondExpr = CondICE.get();
16159 CondIsTrue = condEval.getZExtValue();
16160
16161 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16162 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16163
16164 resType = ActiveExpr->getType();
16165 VK = ActiveExpr->getValueKind();
16166 OK = ActiveExpr->getObjectKind();
16167 }
16168
16169 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16170 resType, VK, OK, RPLoc, CondIsTrue);
16171}
16172
16173//===----------------------------------------------------------------------===//
16174// Clang Extensions.
16175//===----------------------------------------------------------------------===//
16176
16177void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16179
16180 if (LangOpts.CPlusPlus) {
16182 Decl *ManglingContextDecl;
16183 std::tie(MCtx, ManglingContextDecl) =
16184 getCurrentMangleNumberContext(Block->getDeclContext());
16185 if (MCtx) {
16186 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16187 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16188 }
16189 }
16190
16191 PushBlockScope(CurScope, Block);
16193 if (CurScope)
16194 PushDeclContext(CurScope, Block);
16195 else
16196 CurContext = Block;
16197
16199
16200 // Enter a new evaluation context to insulate the block from any
16201 // cleanups from the enclosing full-expression.
16204}
16205
16207 Scope *CurScope) {
16208 assert(ParamInfo.getIdentifier() == nullptr &&
16209 "block-id should have no identifier!");
16210 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16211 BlockScopeInfo *CurBlock = getCurBlock();
16212
16213 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16214 QualType T = Sig->getType();
16216
16217 // GetTypeForDeclarator always produces a function type for a block
16218 // literal signature. Furthermore, it is always a FunctionProtoType
16219 // unless the function was written with a typedef.
16220 assert(T->isFunctionType() &&
16221 "GetTypeForDeclarator made a non-function block signature");
16222
16223 // Look for an explicit signature in that function type.
16224 FunctionProtoTypeLoc ExplicitSignature;
16225
16226 if ((ExplicitSignature = Sig->getTypeLoc()
16228
16229 // Check whether that explicit signature was synthesized by
16230 // GetTypeForDeclarator. If so, don't save that as part of the
16231 // written signature.
16232 if (ExplicitSignature.getLocalRangeBegin() ==
16233 ExplicitSignature.getLocalRangeEnd()) {
16234 // This would be much cheaper if we stored TypeLocs instead of
16235 // TypeSourceInfos.
16236 TypeLoc Result = ExplicitSignature.getReturnLoc();
16237 unsigned Size = Result.getFullDataSize();
16238 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16239 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16240
16241 ExplicitSignature = FunctionProtoTypeLoc();
16242 }
16243 }
16244
16245 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16246 CurBlock->FunctionType = T;
16247
16248 const auto *Fn = T->castAs<FunctionType>();
16249 QualType RetTy = Fn->getReturnType();
16250 bool isVariadic =
16251 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16252
16253 CurBlock->TheDecl->setIsVariadic(isVariadic);
16254
16255 // Context.DependentTy is used as a placeholder for a missing block
16256 // return type. TODO: what should we do with declarators like:
16257 // ^ * { ... }
16258 // If the answer is "apply template argument deduction"....
16259 if (RetTy != Context.DependentTy) {
16260 CurBlock->ReturnType = RetTy;
16261 CurBlock->TheDecl->setBlockMissingReturnType(false);
16262 CurBlock->HasImplicitReturnType = false;
16263 }
16264
16265 // Push block parameters from the declarator if we had them.
16267 if (ExplicitSignature) {
16268 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16269 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16270 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16271 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16272 // Diagnose this as an extension in C17 and earlier.
16273 if (!getLangOpts().C23)
16274 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16275 }
16276 Params.push_back(Param);
16277 }
16278
16279 // Fake up parameter variables if we have a typedef, like
16280 // ^ fntype { ... }
16281 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16282 for (const auto &I : Fn->param_types()) {
16284 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16285 Params.push_back(Param);
16286 }
16287 }
16288
16289 // Set the parameters on the block decl.
16290 if (!Params.empty()) {
16291 CurBlock->TheDecl->setParams(Params);
16293 /*CheckParameterNames=*/false);
16294 }
16295
16296 // Finally we can process decl attributes.
16297 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16298
16299 // Put the parameter variables in scope.
16300 for (auto *AI : CurBlock->TheDecl->parameters()) {
16301 AI->setOwningFunction(CurBlock->TheDecl);
16302
16303 // If this has an identifier, add it to the scope stack.
16304 if (AI->getIdentifier()) {
16305 CheckShadow(CurBlock->TheScope, AI);
16306
16307 PushOnScopeChains(AI, CurBlock->TheScope);
16308 }
16309
16310 if (AI->isInvalidDecl())
16311 CurBlock->TheDecl->setInvalidDecl();
16312 }
16313}
16314
16315void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16316 // Leave the expression-evaluation context.
16319
16320 // Pop off CurBlock, handle nested blocks.
16323}
16324
16326 Stmt *Body, Scope *CurScope) {
16327 // If blocks are disabled, emit an error.
16328 if (!LangOpts.Blocks)
16329 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16330
16331 // Leave the expression-evaluation context.
16334 assert(!Cleanup.exprNeedsCleanups() &&
16335 "cleanups within block not correctly bound!");
16337
16338 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16339 BlockDecl *BD = BSI->TheDecl;
16340
16342
16343 if (BSI->HasImplicitReturnType)
16345
16346 QualType RetTy = Context.VoidTy;
16347 if (!BSI->ReturnType.isNull())
16348 RetTy = BSI->ReturnType;
16349
16350 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16351 QualType BlockTy;
16352
16353 // If the user wrote a function type in some form, try to use that.
16354 if (!BSI->FunctionType.isNull()) {
16355 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16356
16357 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16358 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16359
16360 // Turn protoless block types into nullary block types.
16361 if (isa<FunctionNoProtoType>(FTy)) {
16363 EPI.ExtInfo = Ext;
16364 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16365
16366 // Otherwise, if we don't need to change anything about the function type,
16367 // preserve its sugar structure.
16368 } else if (FTy->getReturnType() == RetTy &&
16369 (!NoReturn || FTy->getNoReturnAttr())) {
16370 BlockTy = BSI->FunctionType;
16371
16372 // Otherwise, make the minimal modifications to the function type.
16373 } else {
16374 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16376 EPI.TypeQuals = Qualifiers();
16377 EPI.ExtInfo = Ext;
16378 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16379 }
16380
16381 // If we don't have a function type, just build one from nothing.
16382 } else {
16384 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16385 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16386 }
16387
16389 BlockTy = Context.getBlockPointerType(BlockTy);
16390
16391 // If needed, diagnose invalid gotos and switches in the block.
16392 if (getCurFunction()->NeedsScopeChecking() &&
16394 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16395
16396 BD->setBody(cast<CompoundStmt>(Body));
16397
16398 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16400
16401 // Try to apply the named return value optimization. We have to check again
16402 // if we can do this, though, because blocks keep return statements around
16403 // to deduce an implicit return type.
16404 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16405 !BD->isDependentContext())
16406 computeNRVO(Body, BSI);
16407
16412
16414
16415 // Set the captured variables on the block.
16417 for (Capture &Cap : BSI->Captures) {
16418 if (Cap.isInvalid() || Cap.isThisCapture())
16419 continue;
16420 // Cap.getVariable() is always a VarDecl because
16421 // blocks cannot capture structured bindings or other ValueDecl kinds.
16422 auto *Var = cast<VarDecl>(Cap.getVariable());
16423 Expr *CopyExpr = nullptr;
16424 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16425 if (const RecordType *Record =
16426 Cap.getCaptureType()->getAs<RecordType>()) {
16427 // The capture logic needs the destructor, so make sure we mark it.
16428 // Usually this is unnecessary because most local variables have
16429 // their destructors marked at declaration time, but parameters are
16430 // an exception because it's technically only the call site that
16431 // actually requires the destructor.
16432 if (isa<ParmVarDecl>(Var))
16434
16435 // Enter a separate potentially-evaluated context while building block
16436 // initializers to isolate their cleanups from those of the block
16437 // itself.
16438 // FIXME: Is this appropriate even when the block itself occurs in an
16439 // unevaluated operand?
16442
16444
16446 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16447
16448 // According to the blocks spec, the capture of a variable from
16449 // the stack requires a const copy constructor. This is not true
16450 // of the copy/move done to move a __block variable to the heap.
16451 if (!Result.isInvalid() &&
16452 !Result.get()->getType().isConstQualified()) {
16454 Result.get()->getType().withConst(),
16455 CK_NoOp, VK_LValue);
16456 }
16457
16458 if (!Result.isInvalid()) {
16460 InitializedEntity::InitializeBlock(Var->getLocation(),
16461 Cap.getCaptureType()),
16462 Loc, Result.get());
16463 }
16464
16465 // Build a full-expression copy expression if initialization
16466 // succeeded and used a non-trivial constructor. Recover from
16467 // errors by pretending that the copy isn't necessary.
16468 if (!Result.isInvalid() &&
16469 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16470 ->isTrivial()) {
16472 CopyExpr = Result.get();
16473 }
16474 }
16475 }
16476
16477 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16478 CopyExpr);
16479 Captures.push_back(NewCap);
16480 }
16481 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16482
16483 // Pop the block scope now but keep it alive to the end of this function.
16485 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16486
16487 BlockExpr *Result = new (Context)
16488 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
16489
16490 // If the block isn't obviously global, i.e. it captures anything at
16491 // all, then we need to do a few things in the surrounding context:
16492 if (Result->getBlockDecl()->hasCaptures()) {
16493 // First, this expression has a new cleanup object.
16494 ExprCleanupObjects.push_back(Result->getBlockDecl());
16496
16497 // It also gets a branch-protected scope if any of the captured
16498 // variables needs destruction.
16499 for (const auto &CI : Result->getBlockDecl()->captures()) {
16500 const VarDecl *var = CI.getVariable();
16501 if (var->getType().isDestructedType() != QualType::DK_none) {
16503 break;
16504 }
16505 }
16506 }
16507
16508 if (getCurFunction())
16509 getCurFunction()->addBlock(BD);
16510
16511 // This can happen if the block's return type is deduced, but
16512 // the return expression is invalid.
16513 if (BD->isInvalidDecl())
16514 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
16515 {Result}, Result->getType());
16516 return Result;
16517}
16518
16520 SourceLocation RPLoc) {
16521 TypeSourceInfo *TInfo;
16522 GetTypeFromParser(Ty, &TInfo);
16523 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16524}
16525
16527 Expr *E, TypeSourceInfo *TInfo,
16528 SourceLocation RPLoc) {
16529 Expr *OrigExpr = E;
16530 bool IsMS = false;
16531
16532 // CUDA device code does not support varargs.
16533 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16534 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16538 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16539 }
16540 }
16541
16542 // NVPTX does not support va_arg expression.
16543 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16544 Context.getTargetInfo().getTriple().isNVPTX())
16545 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16546
16547 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16548 // as Microsoft ABI on an actual Microsoft platform, where
16549 // __builtin_ms_va_list and __builtin_va_list are the same.)
16552 QualType MSVaListType = Context.getBuiltinMSVaListType();
16553 if (Context.hasSameType(MSVaListType, E->getType())) {
16554 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16555 return ExprError();
16556 IsMS = true;
16557 }
16558 }
16559
16560 // Get the va_list type
16561 QualType VaListType = Context.getBuiltinVaListType();
16562 if (!IsMS) {
16563 if (VaListType->isArrayType()) {
16564 // Deal with implicit array decay; for example, on x86-64,
16565 // va_list is an array, but it's supposed to decay to
16566 // a pointer for va_arg.
16567 VaListType = Context.getArrayDecayedType(VaListType);
16568 // Make sure the input expression also decays appropriately.
16570 if (Result.isInvalid())
16571 return ExprError();
16572 E = Result.get();
16573 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16574 // If va_list is a record type and we are compiling in C++ mode,
16575 // check the argument using reference binding.
16577 Context, Context.getLValueReferenceType(VaListType), false);
16579 if (Init.isInvalid())
16580 return ExprError();
16581 E = Init.getAs<Expr>();
16582 } else {
16583 // Otherwise, the va_list argument must be an l-value because
16584 // it is modified by va_arg.
16585 if (!E->isTypeDependent() &&
16586 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16587 return ExprError();
16588 }
16589 }
16590
16591 if (!IsMS && !E->isTypeDependent() &&
16592 !Context.hasSameType(VaListType, E->getType()))
16593 return ExprError(
16594 Diag(E->getBeginLoc(),
16595 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16596 << OrigExpr->getType() << E->getSourceRange());
16597
16598 if (!TInfo->getType()->isDependentType()) {
16599 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16600 diag::err_second_parameter_to_va_arg_incomplete,
16601 TInfo->getTypeLoc()))
16602 return ExprError();
16603
16605 TInfo->getType(),
16606 diag::err_second_parameter_to_va_arg_abstract,
16607 TInfo->getTypeLoc()))
16608 return ExprError();
16609
16610 if (!TInfo->getType().isPODType(Context)) {
16611 Diag(TInfo->getTypeLoc().getBeginLoc(),
16612 TInfo->getType()->isObjCLifetimeType()
16613 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16614 : diag::warn_second_parameter_to_va_arg_not_pod)
16615 << TInfo->getType()
16616 << TInfo->getTypeLoc().getSourceRange();
16617 }
16618
16619 if (TInfo->getType()->isArrayType()) {
16621 PDiag(diag::warn_second_parameter_to_va_arg_array)
16622 << TInfo->getType()
16623 << TInfo->getTypeLoc().getSourceRange());
16624 }
16625
16626 // Check for va_arg where arguments of the given type will be promoted
16627 // (i.e. this va_arg is guaranteed to have undefined behavior).
16628 QualType PromoteType;
16629 if (Context.isPromotableIntegerType(TInfo->getType())) {
16630 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16631 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16632 // and C23 7.16.1.1p2 says, in part:
16633 // If type is not compatible with the type of the actual next argument
16634 // (as promoted according to the default argument promotions), the
16635 // behavior is undefined, except for the following cases:
16636 // - both types are pointers to qualified or unqualified versions of
16637 // compatible types;
16638 // - one type is compatible with a signed integer type, the other
16639 // type is compatible with the corresponding unsigned integer type,
16640 // and the value is representable in both types;
16641 // - one type is pointer to qualified or unqualified void and the
16642 // other is a pointer to a qualified or unqualified character type;
16643 // - or, the type of the next argument is nullptr_t and type is a
16644 // pointer type that has the same representation and alignment
16645 // requirements as a pointer to a character type.
16646 // Given that type compatibility is the primary requirement (ignoring
16647 // qualifications), you would think we could call typesAreCompatible()
16648 // directly to test this. However, in C++, that checks for *same type*,
16649 // which causes false positives when passing an enumeration type to
16650 // va_arg. Instead, get the underlying type of the enumeration and pass
16651 // that.
16652 QualType UnderlyingType = TInfo->getType();
16653 if (const auto *ET = UnderlyingType->getAs<EnumType>())
16654 UnderlyingType = ET->getDecl()->getIntegerType();
16655 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16656 /*CompareUnqualified*/ true))
16657 PromoteType = QualType();
16658
16659 // If the types are still not compatible, we need to test whether the
16660 // promoted type and the underlying type are the same except for
16661 // signedness. Ask the AST for the correctly corresponding type and see
16662 // if that's compatible.
16663 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16664 PromoteType->isUnsignedIntegerType() !=
16665 UnderlyingType->isUnsignedIntegerType()) {
16666 UnderlyingType =
16667 UnderlyingType->isUnsignedIntegerType()
16668 ? Context.getCorrespondingSignedType(UnderlyingType)
16669 : Context.getCorrespondingUnsignedType(UnderlyingType);
16670 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16671 /*CompareUnqualified*/ true))
16672 PromoteType = QualType();
16673 }
16674 }
16675 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16676 PromoteType = Context.DoubleTy;
16677 if (!PromoteType.isNull())
16679 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16680 << TInfo->getType()
16681 << PromoteType
16682 << TInfo->getTypeLoc().getSourceRange());
16683 }
16684
16686 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16687}
16688
16690 // The type of __null will be int or long, depending on the size of
16691 // pointers on the target.
16692 QualType Ty;
16694 if (pw == Context.getTargetInfo().getIntWidth())
16695 Ty = Context.IntTy;
16696 else if (pw == Context.getTargetInfo().getLongWidth())
16697 Ty = Context.LongTy;
16698 else if (pw == Context.getTargetInfo().getLongLongWidth())
16699 Ty = Context.LongLongTy;
16700 else {
16701 llvm_unreachable("I don't know size of pointer!");
16702 }
16703
16704 return new (Context) GNUNullExpr(Ty, TokenLoc);
16705}
16706
16708 CXXRecordDecl *ImplDecl = nullptr;
16709
16710 // Fetch the std::source_location::__impl decl.
16711 if (NamespaceDecl *Std = S.getStdNamespace()) {
16712 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16714 if (S.LookupQualifiedName(ResultSL, Std)) {
16715 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16716 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16718 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16719 S.LookupQualifiedName(ResultImpl, SLDecl)) {
16720 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16721 }
16722 }
16723 }
16724 }
16725
16726 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16727 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16728 return nullptr;
16729 }
16730
16731 // Verify that __impl is a trivial struct type, with no base classes, and with
16732 // only the four expected fields.
16733 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16734 ImplDecl->getNumBases() != 0) {
16735 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16736 return nullptr;
16737 }
16738
16739 unsigned Count = 0;
16740 for (FieldDecl *F : ImplDecl->fields()) {
16741 StringRef Name = F->getName();
16742
16743 if (Name == "_M_file_name") {
16744 if (F->getType() !=
16746 break;
16747 Count++;
16748 } else if (Name == "_M_function_name") {
16749 if (F->getType() !=
16751 break;
16752 Count++;
16753 } else if (Name == "_M_line") {
16754 if (!F->getType()->isIntegerType())
16755 break;
16756 Count++;
16757 } else if (Name == "_M_column") {
16758 if (!F->getType()->isIntegerType())
16759 break;
16760 Count++;
16761 } else {
16762 Count = 100; // invalid
16763 break;
16764 }
16765 }
16766 if (Count != 4) {
16767 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16768 return nullptr;
16769 }
16770
16771 return ImplDecl;
16772}
16773
16775 SourceLocation BuiltinLoc,
16776 SourceLocation RPLoc) {
16777 QualType ResultTy;
16778 switch (Kind) {
16784 ResultTy =
16786 break;
16787 }
16790 ResultTy = Context.UnsignedIntTy;
16791 break;
16795 LookupStdSourceLocationImpl(*this, BuiltinLoc);
16797 return ExprError();
16798 }
16799 ResultTy = Context.getPointerType(
16801 break;
16802 }
16803
16804 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16805}
16806
16808 SourceLocation BuiltinLoc,
16809 SourceLocation RPLoc,
16810 DeclContext *ParentContext) {
16811 return new (Context)
16812 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16813}
16814
16816 StringLiteral *BinaryData) {
16818 Data->BinaryData = BinaryData;
16819 return new (Context)
16820 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
16821 Data->getDataElementCount());
16822}
16823
16825 const Expr *SrcExpr) {
16826 if (!DstType->isFunctionPointerType() ||
16827 !SrcExpr->getType()->isFunctionType())
16828 return false;
16829
16830 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16831 if (!DRE)
16832 return false;
16833
16834 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16835 if (!FD)
16836 return false;
16837
16839 /*Complain=*/true,
16840 SrcExpr->getBeginLoc());
16841}
16842
16845 QualType DstType, QualType SrcType,
16846 Expr *SrcExpr, AssignmentAction Action,
16847 bool *Complained) {
16848 if (Complained)
16849 *Complained = false;
16850
16851 // Decode the result (notice that AST's are still created for extensions).
16852 bool CheckInferredResultType = false;
16853 bool isInvalid = false;
16854 unsigned DiagKind = 0;
16855 ConversionFixItGenerator ConvHints;
16856 bool MayHaveConvFixit = false;
16857 bool MayHaveFunctionDiff = false;
16858 const ObjCInterfaceDecl *IFace = nullptr;
16859 const ObjCProtocolDecl *PDecl = nullptr;
16860
16861 switch (ConvTy) {
16862 case Compatible:
16863 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16864 return false;
16865
16866 case PointerToInt:
16867 if (getLangOpts().CPlusPlus) {
16868 DiagKind = diag::err_typecheck_convert_pointer_int;
16869 isInvalid = true;
16870 } else {
16871 DiagKind = diag::ext_typecheck_convert_pointer_int;
16872 }
16873 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16874 MayHaveConvFixit = true;
16875 break;
16876 case IntToPointer:
16877 if (getLangOpts().CPlusPlus) {
16878 DiagKind = diag::err_typecheck_convert_int_pointer;
16879 isInvalid = true;
16880 } else {
16881 DiagKind = diag::ext_typecheck_convert_int_pointer;
16882 }
16883 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16884 MayHaveConvFixit = true;
16885 break;
16887 DiagKind =
16888 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
16889 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16890 MayHaveConvFixit = true;
16891 break;
16893 if (getLangOpts().CPlusPlus) {
16894 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16895 isInvalid = true;
16896 } else {
16897 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16898 }
16899 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16900 MayHaveConvFixit = true;
16901 break;
16904 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16905 } else if (getLangOpts().CPlusPlus) {
16906 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16907 isInvalid = true;
16908 } else {
16909 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16910 }
16911 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16912 SrcType->isObjCObjectPointerType();
16913 if (CheckInferredResultType) {
16914 SrcType = SrcType.getUnqualifiedType();
16915 DstType = DstType.getUnqualifiedType();
16916 } else {
16917 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16918 }
16919 MayHaveConvFixit = true;
16920 break;
16922 if (getLangOpts().CPlusPlus) {
16923 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16924 isInvalid = true;
16925 } else {
16926 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16927 }
16928 break;
16930 if (getLangOpts().CPlusPlus) {
16931 DiagKind = diag::err_typecheck_convert_pointer_void_func;
16932 isInvalid = true;
16933 } else {
16934 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16935 }
16936 break;
16938 // Perform array-to-pointer decay if necessary.
16939 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16940
16941 isInvalid = true;
16942
16943 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16944 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16945 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16946 DiagKind = diag::err_typecheck_incompatible_address_space;
16947 break;
16948 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16949 DiagKind = diag::err_typecheck_incompatible_ownership;
16950 break;
16951 }
16952
16953 llvm_unreachable("unknown error case for discarding qualifiers!");
16954 // fallthrough
16955 }
16957 // If the qualifiers lost were because we were applying the
16958 // (deprecated) C++ conversion from a string literal to a char*
16959 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
16960 // Ideally, this check would be performed in
16961 // checkPointerTypesForAssignment. However, that would require a
16962 // bit of refactoring (so that the second argument is an
16963 // expression, rather than a type), which should be done as part
16964 // of a larger effort to fix checkPointerTypesForAssignment for
16965 // C++ semantics.
16966 if (getLangOpts().CPlusPlus &&
16968 return false;
16969 if (getLangOpts().CPlusPlus) {
16970 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
16971 isInvalid = true;
16972 } else {
16973 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
16974 }
16975
16976 break;
16978 if (getLangOpts().CPlusPlus) {
16979 isInvalid = true;
16980 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16981 } else {
16982 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16983 }
16984 break;
16986 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16987 isInvalid = true;
16988 break;
16989 case IntToBlockPointer:
16990 DiagKind = diag::err_int_to_block_pointer;
16991 isInvalid = true;
16992 break;
16994 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16995 isInvalid = true;
16996 break;
16998 if (SrcType->isObjCQualifiedIdType()) {
16999 const ObjCObjectPointerType *srcOPT =
17000 SrcType->castAs<ObjCObjectPointerType>();
17001 for (auto *srcProto : srcOPT->quals()) {
17002 PDecl = srcProto;
17003 break;
17004 }
17005 if (const ObjCInterfaceType *IFaceT =
17007 IFace = IFaceT->getDecl();
17008 }
17009 else if (DstType->isObjCQualifiedIdType()) {
17010 const ObjCObjectPointerType *dstOPT =
17011 DstType->castAs<ObjCObjectPointerType>();
17012 for (auto *dstProto : dstOPT->quals()) {
17013 PDecl = dstProto;
17014 break;
17015 }
17016 if (const ObjCInterfaceType *IFaceT =
17018 IFace = IFaceT->getDecl();
17019 }
17020 if (getLangOpts().CPlusPlus) {
17021 DiagKind = diag::err_incompatible_qualified_id;
17022 isInvalid = true;
17023 } else {
17024 DiagKind = diag::warn_incompatible_qualified_id;
17025 }
17026 break;
17027 }
17029 if (getLangOpts().CPlusPlus) {
17030 DiagKind = diag::err_incompatible_vectors;
17031 isInvalid = true;
17032 } else {
17033 DiagKind = diag::warn_incompatible_vectors;
17034 }
17035 break;
17037 DiagKind = diag::err_arc_weak_unavailable_assign;
17038 isInvalid = true;
17039 break;
17040 case Incompatible:
17041 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17042 if (Complained)
17043 *Complained = true;
17044 return true;
17045 }
17046
17047 DiagKind = diag::err_typecheck_convert_incompatible;
17048 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17049 MayHaveConvFixit = true;
17050 isInvalid = true;
17051 MayHaveFunctionDiff = true;
17052 break;
17053 }
17054
17055 QualType FirstType, SecondType;
17056 switch (Action) {
17059 // The destination type comes first.
17060 FirstType = DstType;
17061 SecondType = SrcType;
17062 break;
17063
17070 // The source type comes first.
17071 FirstType = SrcType;
17072 SecondType = DstType;
17073 break;
17074 }
17075
17076 PartialDiagnostic FDiag = PDiag(DiagKind);
17077 AssignmentAction ActionForDiag = Action;
17079 ActionForDiag = AssignmentAction::Passing;
17080
17081 FDiag << FirstType << SecondType << ActionForDiag
17082 << SrcExpr->getSourceRange();
17083
17084 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17085 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17086 auto isPlainChar = [](const clang::Type *Type) {
17087 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17088 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17089 };
17090 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17091 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17092 }
17093
17094 // If we can fix the conversion, suggest the FixIts.
17095 if (!ConvHints.isNull()) {
17096 for (FixItHint &H : ConvHints.Hints)
17097 FDiag << H;
17098 }
17099
17100 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17101
17102 if (MayHaveFunctionDiff)
17103 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17104
17105 Diag(Loc, FDiag);
17106 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17107 DiagKind == diag::err_incompatible_qualified_id) &&
17108 PDecl && IFace && !IFace->hasDefinition())
17109 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17110 << IFace << PDecl;
17111
17112 if (SecondType == Context.OverloadTy)
17114 FirstType, /*TakingAddress=*/true);
17115
17116 if (CheckInferredResultType)
17118
17119 if (Action == AssignmentAction::Returning && ConvTy == IncompatiblePointer)
17121
17122 if (Complained)
17123 *Complained = true;
17124 return isInvalid;
17125}
17126
17128 llvm::APSInt *Result,
17129 AllowFoldKind CanFold) {
17130 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17131 public:
17132 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17133 QualType T) override {
17134 return S.Diag(Loc, diag::err_ice_not_integral)
17135 << T << S.LangOpts.CPlusPlus;
17136 }
17137 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17138 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17139 }
17140 } Diagnoser;
17141
17142 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17143}
17144
17146 llvm::APSInt *Result,
17147 unsigned DiagID,
17148 AllowFoldKind CanFold) {
17149 class IDDiagnoser : public VerifyICEDiagnoser {
17150 unsigned DiagID;
17151
17152 public:
17153 IDDiagnoser(unsigned DiagID)
17154 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17155
17156 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17157 return S.Diag(Loc, DiagID);
17158 }
17159 } Diagnoser(DiagID);
17160
17161 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17162}
17163
17166 QualType T) {
17167 return diagnoseNotICE(S, Loc);
17168}
17169
17172 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17173}
17174
17177 VerifyICEDiagnoser &Diagnoser,
17178 AllowFoldKind CanFold) {
17179 SourceLocation DiagLoc = E->getBeginLoc();
17180
17181 if (getLangOpts().CPlusPlus11) {
17182 // C++11 [expr.const]p5:
17183 // If an expression of literal class type is used in a context where an
17184 // integral constant expression is required, then that class type shall
17185 // have a single non-explicit conversion function to an integral or
17186 // unscoped enumeration type
17187 ExprResult Converted;
17188 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17189 VerifyICEDiagnoser &BaseDiagnoser;
17190 public:
17191 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17192 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17193 BaseDiagnoser.Suppress, true),
17194 BaseDiagnoser(BaseDiagnoser) {}
17195
17196 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17197 QualType T) override {
17198 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17199 }
17200
17201 SemaDiagnosticBuilder diagnoseIncomplete(
17202 Sema &S, SourceLocation Loc, QualType T) override {
17203 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17204 }
17205
17206 SemaDiagnosticBuilder diagnoseExplicitConv(
17207 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17208 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17209 }
17210
17211 SemaDiagnosticBuilder noteExplicitConv(
17212 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17213 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17214 << ConvTy->isEnumeralType() << ConvTy;
17215 }
17216
17217 SemaDiagnosticBuilder diagnoseAmbiguous(
17218 Sema &S, SourceLocation Loc, QualType T) override {
17219 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17220 }
17221
17222 SemaDiagnosticBuilder noteAmbiguous(
17223 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17224 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17225 << ConvTy->isEnumeralType() << ConvTy;
17226 }
17227
17228 SemaDiagnosticBuilder diagnoseConversion(
17229 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17230 llvm_unreachable("conversion functions are permitted");
17231 }
17232 } ConvertDiagnoser(Diagnoser);
17233
17234 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17235 ConvertDiagnoser);
17236 if (Converted.isInvalid())
17237 return Converted;
17238 E = Converted.get();
17239 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17240 // don't try to evaluate it later. We also don't want to return the
17241 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17242 // this function will attempt to use 'Value'.
17243 if (isa<RecoveryExpr>(E))
17244 return ExprError();
17246 return ExprError();
17247 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17248 // An ICE must be of integral or unscoped enumeration type.
17249 if (!Diagnoser.Suppress)
17250 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17251 << E->getSourceRange();
17252 return ExprError();
17253 }
17254
17255 ExprResult RValueExpr = DefaultLvalueConversion(E);
17256 if (RValueExpr.isInvalid())
17257 return ExprError();
17258
17259 E = RValueExpr.get();
17260
17261 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17262 // in the non-ICE case.
17265 if (Result)
17267 if (!isa<ConstantExpr>(E))
17270
17271 if (Notes.empty())
17272 return E;
17273
17274 // If our only note is the usual "invalid subexpression" note, just point
17275 // the caret at its location rather than producing an essentially
17276 // redundant note.
17277 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17278 diag::note_invalid_subexpr_in_const_expr) {
17279 DiagLoc = Notes[0].first;
17280 Notes.clear();
17281 }
17282
17283 if (getLangOpts().CPlusPlus) {
17284 if (!Diagnoser.Suppress) {
17285 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17286 for (const PartialDiagnosticAt &Note : Notes)
17287 Diag(Note.first, Note.second);
17288 }
17289 return ExprError();
17290 }
17291
17292 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17293 for (const PartialDiagnosticAt &Note : Notes)
17294 Diag(Note.first, Note.second);
17295
17296 return E;
17297 }
17298
17299 Expr::EvalResult EvalResult;
17301 EvalResult.Diag = &Notes;
17302
17303 // Try to evaluate the expression, and produce diagnostics explaining why it's
17304 // not a constant expression as a side-effect.
17305 bool Folded =
17306 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17307 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17308 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17309
17310 if (!isa<ConstantExpr>(E))
17311 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17312
17313 // In C++11, we can rely on diagnostics being produced for any expression
17314 // which is not a constant expression. If no diagnostics were produced, then
17315 // this is a constant expression.
17316 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17317 if (Result)
17318 *Result = EvalResult.Val.getInt();
17319 return E;
17320 }
17321
17322 // If our only note is the usual "invalid subexpression" note, just point
17323 // the caret at its location rather than producing an essentially
17324 // redundant note.
17325 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17326 diag::note_invalid_subexpr_in_const_expr) {
17327 DiagLoc = Notes[0].first;
17328 Notes.clear();
17329 }
17330
17331 if (!Folded || !CanFold) {
17332 if (!Diagnoser.Suppress) {
17333 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17334 for (const PartialDiagnosticAt &Note : Notes)
17335 Diag(Note.first, Note.second);
17336 }
17337
17338 return ExprError();
17339 }
17340
17341 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17342 for (const PartialDiagnosticAt &Note : Notes)
17343 Diag(Note.first, Note.second);
17344
17345 if (Result)
17346 *Result = EvalResult.Val.getInt();
17347 return E;
17348}
17349
17350namespace {
17351 // Handle the case where we conclude a expression which we speculatively
17352 // considered to be unevaluated is actually evaluated.
17353 class TransformToPE : public TreeTransform<TransformToPE> {
17354 typedef TreeTransform<TransformToPE> BaseTransform;
17355
17356 public:
17357 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17358
17359 // Make sure we redo semantic analysis
17360 bool AlwaysRebuild() { return true; }
17361 bool ReplacingOriginal() { return true; }
17362
17363 // We need to special-case DeclRefExprs referring to FieldDecls which
17364 // are not part of a member pointer formation; normal TreeTransforming
17365 // doesn't catch this case because of the way we represent them in the AST.
17366 // FIXME: This is a bit ugly; is it really the best way to handle this
17367 // case?
17368 //
17369 // Error on DeclRefExprs referring to FieldDecls.
17370 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17371 if (isa<FieldDecl>(E->getDecl()) &&
17372 !SemaRef.isUnevaluatedContext())
17373 return SemaRef.Diag(E->getLocation(),
17374 diag::err_invalid_non_static_member_use)
17375 << E->getDecl() << E->getSourceRange();
17376
17377 return BaseTransform::TransformDeclRefExpr(E);
17378 }
17379
17380 // Exception: filter out member pointer formation
17381 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17382 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17383 return E;
17384
17385 return BaseTransform::TransformUnaryOperator(E);
17386 }
17387
17388 // The body of a lambda-expression is in a separate expression evaluation
17389 // context so never needs to be transformed.
17390 // FIXME: Ideally we wouldn't transform the closure type either, and would
17391 // just recreate the capture expressions and lambda expression.
17392 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17393 return SkipLambdaBody(E, Body);
17394 }
17395 };
17396}
17397
17399 assert(isUnevaluatedContext() &&
17400 "Should only transform unevaluated expressions");
17401 ExprEvalContexts.back().Context =
17402 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17404 return E;
17405 return TransformToPE(*this).TransformExpr(E);
17406}
17407
17409 assert(isUnevaluatedContext() &&
17410 "Should only transform unevaluated expressions");
17413 return TInfo;
17414 return TransformToPE(*this).TransformType(TInfo);
17415}
17416
17417void
17419 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17421 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17422 LambdaContextDecl, ExprContext);
17423
17424 // Discarded statements and immediate contexts nested in other
17425 // discarded statements or immediate context are themselves
17426 // a discarded statement or an immediate context, respectively.
17427 ExprEvalContexts.back().InDiscardedStatement =
17429
17430 // C++23 [expr.const]/p15
17431 // An expression or conversion is in an immediate function context if [...]
17432 // it is a subexpression of a manifestly constant-evaluated expression or
17433 // conversion.
17434 const auto &Prev = parentEvaluationContext();
17435 ExprEvalContexts.back().InImmediateFunctionContext =
17436 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17437
17438 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17439 Prev.InImmediateEscalatingFunctionContext;
17440
17441 Cleanup.reset();
17442 if (!MaybeODRUseExprs.empty())
17443 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17444}
17445
17446void
17450 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17451 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17452}
17453
17454namespace {
17455
17456const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17457 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17458 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17459 if (E->getOpcode() == UO_Deref)
17460 return CheckPossibleDeref(S, E->getSubExpr());
17461 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17462 return CheckPossibleDeref(S, E->getBase());
17463 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17464 return CheckPossibleDeref(S, E->getBase());
17465 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17466 QualType Inner;
17467 QualType Ty = E->getType();
17468 if (const auto *Ptr = Ty->getAs<PointerType>())
17469 Inner = Ptr->getPointeeType();
17470 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17471 Inner = Arr->getElementType();
17472 else
17473 return nullptr;
17474
17475 if (Inner->hasAttr(attr::NoDeref))
17476 return E;
17477 }
17478 return nullptr;
17479}
17480
17481} // namespace
17482
17484 for (const Expr *E : Rec.PossibleDerefs) {
17485 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17486 if (DeclRef) {
17487 const ValueDecl *Decl = DeclRef->getDecl();
17488 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17489 << Decl->getName() << E->getSourceRange();
17490 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17491 } else {
17492 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17493 << E->getSourceRange();
17494 }
17495 }
17496 Rec.PossibleDerefs.clear();
17497}
17498
17501 return;
17502
17503 // Note: ignoring parens here is not justified by the standard rules, but
17504 // ignoring parentheses seems like a more reasonable approach, and this only
17505 // drives a deprecation warning so doesn't affect conformance.
17506 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17507 if (BO->getOpcode() == BO_Assign) {
17508 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17509 llvm::erase(LHSs, BO->getLHS());
17510 }
17511 }
17512}
17513
17515 assert(getLangOpts().CPlusPlus20 &&
17516 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17517 "Cannot mark an immediate escalating expression outside of an "
17518 "immediate escalating context");
17519 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
17520 Call && Call->getCallee()) {
17521 if (auto *DeclRef =
17522 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17523 DeclRef->setIsImmediateEscalating(true);
17524 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
17525 Ctr->setIsImmediateEscalating(true);
17526 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
17527 DeclRef->setIsImmediateEscalating(true);
17528 } else {
17529 assert(false && "expected an immediately escalating expression");
17530 }
17532 FI->FoundImmediateEscalatingExpression = true;
17533}
17534
17536 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17537 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
17540 return E;
17541
17542 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17543 /// It's OK if this fails; we'll also remove this in
17544 /// HandleImmediateInvocations, but catching it here allows us to avoid
17545 /// walking the AST looking for it in simple cases.
17546 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17547 if (auto *DeclRef =
17548 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17549 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17550
17551 // C++23 [expr.const]/p16
17552 // An expression or conversion is immediate-escalating if it is not initially
17553 // in an immediate function context and it is [...] an immediate invocation
17554 // that is not a constant expression and is not a subexpression of an
17555 // immediate invocation.
17556 APValue Cached;
17557 auto CheckConstantExpressionAndKeepResult = [&]() {
17559 Expr::EvalResult Eval;
17560 Eval.Diag = &Notes;
17561 bool Res = E.get()->EvaluateAsConstantExpr(
17562 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
17563 if (Res && Notes.empty()) {
17564 Cached = std::move(Eval.Val);
17565 return true;
17566 }
17567 return false;
17568 };
17569
17570 if (!E.get()->isValueDependent() &&
17571 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17572 !CheckConstantExpressionAndKeepResult()) {
17574 return E;
17575 }
17576
17577 if (Cleanup.exprNeedsCleanups()) {
17578 // Since an immediate invocation is a full expression itself - it requires
17579 // an additional ExprWithCleanups node, but it can participate to a bigger
17580 // full expression which actually requires cleanups to be run after so
17581 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
17582 // may discard cleanups for outer expression too early.
17583
17584 // Note that ExprWithCleanups created here must always have empty cleanup
17585 // objects:
17586 // - compound literals do not create cleanup objects in C++ and immediate
17587 // invocations are C++-only.
17588 // - blocks are not allowed inside constant expressions and compiler will
17589 // issue an error if they appear there.
17590 //
17591 // Hence, in correct code any cleanup objects created inside current
17592 // evaluation context must be outside the immediate invocation.
17595 }
17596
17598 getASTContext(), E.get(),
17599 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17600 getASTContext()),
17601 /*IsImmediateInvocation*/ true);
17602 if (Cached.hasValue())
17603 Res->MoveIntoResult(Cached, getASTContext());
17604 /// Value-dependent constant expressions should not be immediately
17605 /// evaluated until they are instantiated.
17606 if (!Res->isValueDependent())
17607 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17608 return Res;
17609}
17610
17614 Expr::EvalResult Eval;
17615 Eval.Diag = &Notes;
17616 ConstantExpr *CE = Candidate.getPointer();
17617 bool Result = CE->EvaluateAsConstantExpr(
17618 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17619 if (!Result || !Notes.empty()) {
17621 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17622 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17623 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
17624 FunctionDecl *FD = nullptr;
17625 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17626 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17627 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17628 FD = Call->getConstructor();
17629 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
17630 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
17631
17632 assert(FD && FD->isImmediateFunction() &&
17633 "could not find an immediate function in this expression");
17634 if (FD->isInvalidDecl())
17635 return;
17636 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
17637 << FD << FD->isConsteval();
17638 if (auto Context =
17640 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17641 << Context->Decl;
17642 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17643 }
17644 if (!FD->isConsteval())
17646 for (auto &Note : Notes)
17647 SemaRef.Diag(Note.first, Note.second);
17648 return;
17649 }
17651}
17652
17656 struct ComplexRemove : TreeTransform<ComplexRemove> {
17658 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17661 CurrentII;
17662 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17665 4>::reverse_iterator Current)
17666 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17667 void RemoveImmediateInvocation(ConstantExpr* E) {
17668 auto It = std::find_if(CurrentII, IISet.rend(),
17670 return Elem.getPointer() == E;
17671 });
17672 // It is possible that some subexpression of the current immediate
17673 // invocation was handled from another expression evaluation context. Do
17674 // not handle the current immediate invocation if some of its
17675 // subexpressions failed before.
17676 if (It == IISet.rend()) {
17677 if (SemaRef.FailedImmediateInvocations.contains(E))
17678 CurrentII->setInt(1);
17679 } else {
17680 It->setInt(1); // Mark as deleted
17681 }
17682 }
17683 ExprResult TransformConstantExpr(ConstantExpr *E) {
17684 if (!E->isImmediateInvocation())
17685 return Base::TransformConstantExpr(E);
17686 RemoveImmediateInvocation(E);
17687 return Base::TransformExpr(E->getSubExpr());
17688 }
17689 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17690 /// we need to remove its DeclRefExpr from the DRSet.
17691 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17692 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17693 return Base::TransformCXXOperatorCallExpr(E);
17694 }
17695 /// Base::TransformUserDefinedLiteral doesn't preserve the
17696 /// UserDefinedLiteral node.
17697 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
17698 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
17699 /// here.
17700 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17701 if (!Init)
17702 return Init;
17703
17704 // We cannot use IgnoreImpCasts because we need to preserve
17705 // full expressions.
17706 while (true) {
17707 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
17708 Init = ICE->getSubExpr();
17709 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
17710 Init = ICE->getSubExpr();
17711 else
17712 break;
17713 }
17714 /// ConstantExprs are the first layer of implicit node to be removed so if
17715 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17716 if (auto *CE = dyn_cast<ConstantExpr>(Init);
17717 CE && CE->isImmediateInvocation())
17718 RemoveImmediateInvocation(CE);
17719 return Base::TransformInitializer(Init, NotCopyInit);
17720 }
17721 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17722 DRSet.erase(E);
17723 return E;
17724 }
17725 ExprResult TransformLambdaExpr(LambdaExpr *E) {
17726 // Do not rebuild lambdas to avoid creating a new type.
17727 // Lambdas have already been processed inside their eval contexts.
17728 return E;
17729 }
17730 bool AlwaysRebuild() { return false; }
17731 bool ReplacingOriginal() { return true; }
17732 bool AllowSkippingCXXConstructExpr() {
17733 bool Res = AllowSkippingFirstCXXConstructExpr;
17734 AllowSkippingFirstCXXConstructExpr = true;
17735 return Res;
17736 }
17737 bool AllowSkippingFirstCXXConstructExpr = true;
17738 } Transformer(SemaRef, Rec.ReferenceToConsteval,
17740
17741 /// CXXConstructExpr with a single argument are getting skipped by
17742 /// TreeTransform in some situtation because they could be implicit. This
17743 /// can only occur for the top-level CXXConstructExpr because it is used
17744 /// nowhere in the expression being transformed therefore will not be rebuilt.
17745 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17746 /// skipping the first CXXConstructExpr.
17747 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17748 Transformer.AllowSkippingFirstCXXConstructExpr = false;
17749
17750 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17751 // The result may not be usable in case of previous compilation errors.
17752 // In this case evaluation of the expression may result in crash so just
17753 // don't do anything further with the result.
17754 if (Res.isUsable()) {
17756 It->getPointer()->setSubExpr(Res.get());
17757 }
17758}
17759
17760static void
17763 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17764 Rec.ReferenceToConsteval.size() == 0) ||
17766 return;
17767
17768 /// When we have more than 1 ImmediateInvocationCandidates or previously
17769 /// failed immediate invocations, we need to check for nested
17770 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
17771 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
17772 /// invocation.
17773 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
17775
17776 /// Prevent sema calls during the tree transform from adding pointers that
17777 /// are already in the sets.
17778 llvm::SaveAndRestore DisableIITracking(
17780
17781 /// Prevent diagnostic during tree transfrom as they are duplicates
17783
17784 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17785 It != Rec.ImmediateInvocationCandidates.rend(); It++)
17786 if (!It->getInt())
17788 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17789 Rec.ReferenceToConsteval.size()) {
17790 struct SimpleRemove : DynamicRecursiveASTVisitor {
17791 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17792 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17793 bool VisitDeclRefExpr(DeclRefExpr *E) override {
17794 DRSet.erase(E);
17795 return DRSet.size();
17796 }
17797 } Visitor(Rec.ReferenceToConsteval);
17798 Visitor.TraverseStmt(
17799 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17800 }
17801 for (auto CE : Rec.ImmediateInvocationCandidates)
17802 if (!CE.getInt())
17804 for (auto *DR : Rec.ReferenceToConsteval) {
17805 // If the expression is immediate escalating, it is not an error;
17806 // The outer context itself becomes immediate and further errors,
17807 // if any, will be handled by DiagnoseImmediateEscalatingReason.
17808 if (DR->isImmediateEscalating())
17809 continue;
17810 auto *FD = cast<FunctionDecl>(DR->getDecl());
17811 const NamedDecl *ND = FD;
17812 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
17813 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
17814 ND = MD->getParent();
17815
17816 // C++23 [expr.const]/p16
17817 // An expression or conversion is immediate-escalating if it is not
17818 // initially in an immediate function context and it is [...] a
17819 // potentially-evaluated id-expression that denotes an immediate function
17820 // that is not a subexpression of an immediate invocation.
17821 bool ImmediateEscalating = false;
17822 bool IsPotentiallyEvaluated =
17823 Rec.Context ==
17825 Rec.Context ==
17827 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
17828 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
17829
17831 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
17832 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17833 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
17834 if (!FD->getBuiltinID())
17835 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
17836 if (auto Context =
17838 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17839 << Context->Decl;
17840 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17841 }
17842 if (FD->isImmediateEscalating() && !FD->isConsteval())
17844
17845 } else {
17847 }
17848 }
17849}
17850
17853 unsigned NumTypos = Rec.NumTypos;
17854
17855 if (!Rec.Lambdas.empty()) {
17857 if (!getLangOpts().CPlusPlus20 &&
17858 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17859 Rec.isUnevaluated() ||
17861 unsigned D;
17862 if (Rec.isUnevaluated()) {
17863 // C++11 [expr.prim.lambda]p2:
17864 // A lambda-expression shall not appear in an unevaluated operand
17865 // (Clause 5).
17866 D = diag::err_lambda_unevaluated_operand;
17867 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17868 // C++1y [expr.const]p2:
17869 // A conditional-expression e is a core constant expression unless the
17870 // evaluation of e, following the rules of the abstract machine, would
17871 // evaluate [...] a lambda-expression.
17872 D = diag::err_lambda_in_constant_expression;
17873 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17874 // C++17 [expr.prim.lamda]p2:
17875 // A lambda-expression shall not appear [...] in a template-argument.
17876 D = diag::err_lambda_in_invalid_context;
17877 } else
17878 llvm_unreachable("Couldn't infer lambda error message.");
17879
17880 for (const auto *L : Rec.Lambdas)
17881 Diag(L->getBeginLoc(), D);
17882 }
17883 }
17884
17885 // Append the collected materialized temporaries into previous context before
17886 // exit if the previous also is a lifetime extending context.
17888 parentEvaluationContext().InLifetimeExtendingContext &&
17889 !Rec.ForRangeLifetimeExtendTemps.empty()) {
17892 }
17893
17895 HandleImmediateInvocations(*this, Rec);
17896
17897 // Warn on any volatile-qualified simple-assignments that are not discarded-
17898 // value expressions nor unevaluated operands (those cases get removed from
17899 // this list by CheckUnusedVolatileAssignment).
17900 for (auto *BO : Rec.VolatileAssignmentLHSs)
17901 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17902 << BO->getType();
17903
17904 // When are coming out of an unevaluated context, clear out any
17905 // temporaries that we may have created as part of the evaluation of
17906 // the expression in that context: they aren't relevant because they
17907 // will never be constructed.
17908 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17910 ExprCleanupObjects.end());
17911 Cleanup = Rec.ParentCleanup;
17914 // Otherwise, merge the contexts together.
17915 } else {
17917 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17918 Rec.SavedMaybeODRUseExprs.end());
17919 }
17920
17921 // Pop the current expression evaluation context off the stack.
17922 ExprEvalContexts.pop_back();
17923
17924 // The global expression evaluation context record is never popped.
17925 ExprEvalContexts.back().NumTypos += NumTypos;
17926}
17927
17929 ExprCleanupObjects.erase(
17930 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17931 ExprCleanupObjects.end());
17932 Cleanup.reset();
17933 MaybeODRUseExprs.clear();
17934}
17935
17938 if (Result.isInvalid())
17939 return ExprError();
17940 E = Result.get();
17941 if (!E->getType()->isVariablyModifiedType())
17942 return E;
17944}
17945
17946/// Are we in a context that is potentially constant evaluated per C++20
17947/// [expr.const]p12?
17949 /// C++2a [expr.const]p12:
17950 // An expression or conversion is potentially constant evaluated if it is
17951 switch (SemaRef.ExprEvalContexts.back().Context) {
17954
17955 // -- a manifestly constant-evaluated expression,
17959 // -- a potentially-evaluated expression,
17961 // -- an immediate subexpression of a braced-init-list,
17962
17963 // -- [FIXME] an expression of the form & cast-expression that occurs
17964 // within a templated entity
17965 // -- a subexpression of one of the above that is not a subexpression of
17966 // a nested unevaluated operand.
17967 return true;
17968
17971 // Expressions in this context are never evaluated.
17972 return false;
17973 }
17974 llvm_unreachable("Invalid context");
17975}
17976
17977/// Return true if this function has a calling convention that requires mangling
17978/// in the size of the parameter pack.
17980 // These manglings don't do anything on non-Windows or non-x86 platforms, so
17981 // we don't need parameter type sizes.
17982 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17983 if (!TT.isOSWindows() || !TT.isX86())
17984 return false;
17985
17986 // If this is C++ and this isn't an extern "C" function, parameters do not
17987 // need to be complete. In this case, C++ mangling will apply, which doesn't
17988 // use the size of the parameters.
17989 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17990 return false;
17991
17992 // Stdcall, fastcall, and vectorcall need this special treatment.
17993 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17994 switch (CC) {
17995 case CC_X86StdCall:
17996 case CC_X86FastCall:
17997 case CC_X86VectorCall:
17998 return true;
17999 default:
18000 break;
18001 }
18002 return false;
18003}
18004
18005/// Require that all of the parameter types of function be complete. Normally,
18006/// parameter types are only required to be complete when a function is called
18007/// or defined, but to mangle functions with certain calling conventions, the
18008/// mangler needs to know the size of the parameter list. In this situation,
18009/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18010/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18011/// result in a linker error. Clang doesn't implement this behavior, and instead
18012/// attempts to error at compile time.
18015 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18016 FunctionDecl *FD;
18017 ParmVarDecl *Param;
18018
18019 public:
18020 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18021 : FD(FD), Param(Param) {}
18022
18023 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18024 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18025 StringRef CCName;
18026 switch (CC) {
18027 case CC_X86StdCall:
18028 CCName = "stdcall";
18029 break;
18030 case CC_X86FastCall:
18031 CCName = "fastcall";
18032 break;
18033 case CC_X86VectorCall:
18034 CCName = "vectorcall";
18035 break;
18036 default:
18037 llvm_unreachable("CC does not need mangling");
18038 }
18039
18040 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18041 << Param->getDeclName() << FD->getDeclName() << CCName;
18042 }
18043 };
18044
18045 for (ParmVarDecl *Param : FD->parameters()) {
18046 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18047 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18048 }
18049}
18050
18051namespace {
18052enum class OdrUseContext {
18053 /// Declarations in this context are not odr-used.
18054 None,
18055 /// Declarations in this context are formally odr-used, but this is a
18056 /// dependent context.
18057 Dependent,
18058 /// Declarations in this context are odr-used but not actually used (yet).
18059 FormallyOdrUsed,
18060 /// Declarations in this context are used.
18061 Used
18062};
18063}
18064
18065/// Are we within a context in which references to resolved functions or to
18066/// variables result in odr-use?
18067static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18068 OdrUseContext Result;
18069
18070 switch (SemaRef.ExprEvalContexts.back().Context) {
18074 return OdrUseContext::None;
18075
18079 Result = OdrUseContext::Used;
18080 break;
18081
18083 Result = OdrUseContext::FormallyOdrUsed;
18084 break;
18085
18087 // A default argument formally results in odr-use, but doesn't actually
18088 // result in a use in any real sense until it itself is used.
18089 Result = OdrUseContext::FormallyOdrUsed;
18090 break;
18091 }
18092
18094 return OdrUseContext::Dependent;
18095
18096 return Result;
18097}
18098
18100 if (!Func->isConstexpr())
18101 return false;
18102
18103 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18104 return true;
18105 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18106 return CCD && CCD->getInheritedConstructor();
18107}
18108
18110 bool MightBeOdrUse) {
18111 assert(Func && "No function?");
18112
18113 Func->setReferenced();
18114
18115 // Recursive functions aren't really used until they're used from some other
18116 // context.
18117 bool IsRecursiveCall = CurContext == Func;
18118
18119 // C++11 [basic.def.odr]p3:
18120 // A function whose name appears as a potentially-evaluated expression is
18121 // odr-used if it is the unique lookup result or the selected member of a
18122 // set of overloaded functions [...].
18123 //
18124 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18125 // can just check that here.
18126 OdrUseContext OdrUse =
18127 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18128 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18129 OdrUse = OdrUseContext::FormallyOdrUsed;
18130
18131 // Trivial default constructors and destructors are never actually used.
18132 // FIXME: What about other special members?
18133 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18134 OdrUse == OdrUseContext::Used) {
18135 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18136 if (Constructor->isDefaultConstructor())
18137 OdrUse = OdrUseContext::FormallyOdrUsed;
18138 if (isa<CXXDestructorDecl>(Func))
18139 OdrUse = OdrUseContext::FormallyOdrUsed;
18140 }
18141
18142 // C++20 [expr.const]p12:
18143 // A function [...] is needed for constant evaluation if it is [...] a
18144 // constexpr function that is named by an expression that is potentially
18145 // constant evaluated
18146 bool NeededForConstantEvaluation =
18149
18150 // Determine whether we require a function definition to exist, per
18151 // C++11 [temp.inst]p3:
18152 // Unless a function template specialization has been explicitly
18153 // instantiated or explicitly specialized, the function template
18154 // specialization is implicitly instantiated when the specialization is
18155 // referenced in a context that requires a function definition to exist.
18156 // C++20 [temp.inst]p7:
18157 // The existence of a definition of a [...] function is considered to
18158 // affect the semantics of the program if the [...] function is needed for
18159 // constant evaluation by an expression
18160 // C++20 [basic.def.odr]p10:
18161 // Every program shall contain exactly one definition of every non-inline
18162 // function or variable that is odr-used in that program outside of a
18163 // discarded statement
18164 // C++20 [special]p1:
18165 // The implementation will implicitly define [defaulted special members]
18166 // if they are odr-used or needed for constant evaluation.
18167 //
18168 // Note that we skip the implicit instantiation of templates that are only
18169 // used in unused default arguments or by recursive calls to themselves.
18170 // This is formally non-conforming, but seems reasonable in practice.
18171 bool NeedDefinition =
18172 !IsRecursiveCall &&
18173 (OdrUse == OdrUseContext::Used ||
18174 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18175
18176 // C++14 [temp.expl.spec]p6:
18177 // If a template [...] is explicitly specialized then that specialization
18178 // shall be declared before the first use of that specialization that would
18179 // cause an implicit instantiation to take place, in every translation unit
18180 // in which such a use occurs
18181 if (NeedDefinition &&
18182 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18183 Func->getMemberSpecializationInfo()))
18185
18186 if (getLangOpts().CUDA)
18187 CUDA().CheckCall(Loc, Func);
18188
18189 // If we need a definition, try to create one.
18190 if (NeedDefinition && !Func->getBody()) {
18192 if (CXXConstructorDecl *Constructor =
18193 dyn_cast<CXXConstructorDecl>(Func)) {
18194 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18195 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18196 if (Constructor->isDefaultConstructor()) {
18197 if (Constructor->isTrivial() &&
18198 !Constructor->hasAttr<DLLExportAttr>())
18199 return;
18201 } else if (Constructor->isCopyConstructor()) {
18202 DefineImplicitCopyConstructor(Loc, Constructor);
18203 } else if (Constructor->isMoveConstructor()) {
18204 DefineImplicitMoveConstructor(Loc, Constructor);
18205 }
18206 } else if (Constructor->getInheritedConstructor()) {
18207 DefineInheritingConstructor(Loc, Constructor);
18208 }
18209 } else if (CXXDestructorDecl *Destructor =
18210 dyn_cast<CXXDestructorDecl>(Func)) {
18211 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18212 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18213 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18214 return;
18216 }
18217 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18218 MarkVTableUsed(Loc, Destructor->getParent());
18219 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18220 if (MethodDecl->isOverloadedOperator() &&
18221 MethodDecl->getOverloadedOperator() == OO_Equal) {
18222 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18223 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18224 if (MethodDecl->isCopyAssignmentOperator())
18225 DefineImplicitCopyAssignment(Loc, MethodDecl);
18226 else if (MethodDecl->isMoveAssignmentOperator())
18227 DefineImplicitMoveAssignment(Loc, MethodDecl);
18228 }
18229 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18230 MethodDecl->getParent()->isLambda()) {
18231 CXXConversionDecl *Conversion =
18232 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18233 if (Conversion->isLambdaToBlockPointerConversion())
18235 else
18237 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18238 MarkVTableUsed(Loc, MethodDecl->getParent());
18239 }
18240
18241 if (Func->isDefaulted() && !Func->isDeleted()) {
18245 }
18246
18247 // Implicit instantiation of function templates and member functions of
18248 // class templates.
18249 if (Func->isImplicitlyInstantiable()) {
18251 Func->getTemplateSpecializationKindForInstantiation();
18252 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18253 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18254 if (FirstInstantiation) {
18255 PointOfInstantiation = Loc;
18256 if (auto *MSI = Func->getMemberSpecializationInfo())
18257 MSI->setPointOfInstantiation(Loc);
18258 // FIXME: Notify listener.
18259 else
18260 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18261 } else if (TSK != TSK_ImplicitInstantiation) {
18262 // Use the point of use as the point of instantiation, instead of the
18263 // point of explicit instantiation (which we track as the actual point
18264 // of instantiation). This gives better backtraces in diagnostics.
18265 PointOfInstantiation = Loc;
18266 }
18267
18268 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18269 Func->isConstexpr()) {
18270 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18271 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18272 CodeSynthesisContexts.size())
18274 std::make_pair(Func, PointOfInstantiation));
18275 else if (Func->isConstexpr())
18276 // Do not defer instantiations of constexpr functions, to avoid the
18277 // expression evaluator needing to call back into Sema if it sees a
18278 // call to such a function.
18279 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18280 else {
18281 Func->setInstantiationIsPending(true);
18282 PendingInstantiations.push_back(
18283 std::make_pair(Func, PointOfInstantiation));
18284 if (llvm::isTimeTraceVerbose()) {
18285 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
18286 std::string Name;
18287 llvm::raw_string_ostream OS(Name);
18288 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
18289 /*Qualified=*/true);
18290 return Name;
18291 });
18292 }
18293 // Notify the consumer that a function was implicitly instantiated.
18295 }
18296 }
18297 } else {
18298 // Walk redefinitions, as some of them may be instantiable.
18299 for (auto *i : Func->redecls()) {
18300 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18301 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18302 }
18303 }
18304 });
18305 }
18306
18307 // If a constructor was defined in the context of a default parameter
18308 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18309 // context), its initializers may not be referenced yet.
18310 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18312 *this,
18313 Constructor->isImmediateFunction()
18316 Constructor);
18317 for (CXXCtorInitializer *Init : Constructor->inits()) {
18318 if (Init->isInClassMemberInitializer())
18319 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18320 MarkDeclarationsReferencedInExpr(Init->getInit());
18321 });
18322 }
18323 }
18324
18325 // C++14 [except.spec]p17:
18326 // An exception-specification is considered to be needed when:
18327 // - the function is odr-used or, if it appears in an unevaluated operand,
18328 // would be odr-used if the expression were potentially-evaluated;
18329 //
18330 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18331 // function is a pure virtual function we're calling, and in that case the
18332 // function was selected by overload resolution and we need to resolve its
18333 // exception specification for a different reason.
18334 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18337
18338 // A callee could be called by a host function then by a device function.
18339 // If we only try recording once, we will miss recording the use on device
18340 // side. Therefore keep trying until it is recorded.
18341 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18344
18345 // If this is the first "real" use, act on that.
18346 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18347 // Keep track of used but undefined functions.
18348 if (!Func->isDefined()) {
18349 if (mightHaveNonExternalLinkage(Func))
18350 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18351 else if (Func->getMostRecentDecl()->isInlined() &&
18352 !LangOpts.GNUInline &&
18353 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18354 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18356 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18357 }
18358
18359 // Some x86 Windows calling conventions mangle the size of the parameter
18360 // pack into the name. Computing the size of the parameters requires the
18361 // parameter types to be complete. Check that now.
18364
18365 // In the MS C++ ABI, the compiler emits destructor variants where they are
18366 // used. If the destructor is used here but defined elsewhere, mark the
18367 // virtual base destructors referenced. If those virtual base destructors
18368 // are inline, this will ensure they are defined when emitting the complete
18369 // destructor variant. This checking may be redundant if the destructor is
18370 // provided later in this TU.
18372 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18373 CXXRecordDecl *Parent = Dtor->getParent();
18374 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18376 }
18377 }
18378
18379 Func->markUsed(Context);
18380 }
18381}
18382
18383/// Directly mark a variable odr-used. Given a choice, prefer to use
18384/// MarkVariableReferenced since it does additional checks and then
18385/// calls MarkVarDeclODRUsed.
18386/// If the variable must be captured:
18387/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18388/// - else capture it in the DeclContext that maps to the
18389/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18390static void
18392 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18393 // Keep track of used but undefined variables.
18394 // FIXME: We shouldn't suppress this warning for static data members.
18395 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18396 assert(Var && "expected a capturable variable");
18397
18399 (!Var->isExternallyVisible() || Var->isInline() ||
18401 !(Var->isStaticDataMember() && Var->hasInit())) {
18403 if (old.isInvalid())
18404 old = Loc;
18405 }
18406 QualType CaptureType, DeclRefType;
18407 if (SemaRef.LangOpts.OpenMP)
18410 /*EllipsisLoc*/ SourceLocation(),
18411 /*BuildAndDiagnose*/ true, CaptureType,
18412 DeclRefType, FunctionScopeIndexToStopAt);
18413
18414 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18415 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18416 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
18417 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
18418 if (VarTarget == SemaCUDA::CVT_Host &&
18419 (UserTarget == CUDAFunctionTarget::Device ||
18420 UserTarget == CUDAFunctionTarget::HostDevice ||
18421 UserTarget == CUDAFunctionTarget::Global)) {
18422 // Diagnose ODR-use of host global variables in device functions.
18423 // Reference of device global variables in host functions is allowed
18424 // through shadow variables therefore it is not diagnosed.
18425 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18426 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18427 << /*host*/ 2 << /*variable*/ 1 << Var
18428 << llvm::to_underlying(UserTarget);
18430 Var->getType().isConstQualified()
18431 ? diag::note_cuda_const_var_unpromoted
18432 : diag::note_cuda_host_var);
18433 }
18434 } else if (VarTarget == SemaCUDA::CVT_Device &&
18435 !Var->hasAttr<CUDASharedAttr>() &&
18436 (UserTarget == CUDAFunctionTarget::Host ||
18437 UserTarget == CUDAFunctionTarget::HostDevice)) {
18438 // Record a CUDA/HIP device side variable if it is ODR-used
18439 // by host code. This is done conservatively, when the variable is
18440 // referenced in any of the following contexts:
18441 // - a non-function context
18442 // - a host function
18443 // - a host device function
18444 // This makes the ODR-use of the device side variable by host code to
18445 // be visible in the device compilation for the compiler to be able to
18446 // emit template variables instantiated by host code only and to
18447 // externalize the static device side variable ODR-used by host code.
18448 if (!Var->hasExternalStorage())
18450 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18451 (!FD || (!FD->getDescribedFunctionTemplate() &&
18455 }
18456 }
18457
18458 V->markUsed(SemaRef.Context);
18459}
18460
18463 unsigned CapturingScopeIndex) {
18464 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18465}
18466
18468 ValueDecl *var) {
18469 DeclContext *VarDC = var->getDeclContext();
18470
18471 // If the parameter still belongs to the translation unit, then
18472 // we're actually just using one parameter in the declaration of
18473 // the next.
18474 if (isa<ParmVarDecl>(var) &&
18475 isa<TranslationUnitDecl>(VarDC))
18476 return;
18477
18478 // For C code, don't diagnose about capture if we're not actually in code
18479 // right now; it's impossible to write a non-constant expression outside of
18480 // function context, so we'll get other (more useful) diagnostics later.
18481 //
18482 // For C++, things get a bit more nasty... it would be nice to suppress this
18483 // diagnostic for certain cases like using a local variable in an array bound
18484 // for a member of a local class, but the correct predicate is not obvious.
18485 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18486 return;
18487
18488 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18489 unsigned ContextKind = 3; // unknown
18490 if (isa<CXXMethodDecl>(VarDC) &&
18491 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18492 ContextKind = 2;
18493 } else if (isa<FunctionDecl>(VarDC)) {
18494 ContextKind = 0;
18495 } else if (isa<BlockDecl>(VarDC)) {
18496 ContextKind = 1;
18497 }
18498
18499 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18500 << var << ValueKind << ContextKind << VarDC;
18501 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18502 << var;
18503
18504 // FIXME: Add additional diagnostic info about class etc. which prevents
18505 // capture.
18506}
18507
18509 ValueDecl *Var,
18510 bool &SubCapturesAreNested,
18511 QualType &CaptureType,
18512 QualType &DeclRefType) {
18513 // Check whether we've already captured it.
18514 if (CSI->CaptureMap.count(Var)) {
18515 // If we found a capture, any subcaptures are nested.
18516 SubCapturesAreNested = true;
18517
18518 // Retrieve the capture type for this variable.
18519 CaptureType = CSI->getCapture(Var).getCaptureType();
18520
18521 // Compute the type of an expression that refers to this variable.
18522 DeclRefType = CaptureType.getNonReferenceType();
18523
18524 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18525 // are mutable in the sense that user can change their value - they are
18526 // private instances of the captured declarations.
18527 const Capture &Cap = CSI->getCapture(Var);
18528 // C++ [expr.prim.lambda]p10:
18529 // The type of such a data member is [...] an lvalue reference to the
18530 // referenced function type if the entity is a reference to a function.
18531 // [...]
18532 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
18533 !(isa<LambdaScopeInfo>(CSI) &&
18534 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
18535 !(isa<CapturedRegionScopeInfo>(CSI) &&
18536 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18537 DeclRefType.addConst();
18538 return true;
18539 }
18540 return false;
18541}
18542
18543// Only block literals, captured statements, and lambda expressions can
18544// capture; other scopes don't work.
18546 ValueDecl *Var,
18548 const bool Diagnose,
18549 Sema &S) {
18550 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18552
18553 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18554 if (Underlying) {
18555 if (Underlying->hasLocalStorage() && Diagnose)
18557 }
18558 return nullptr;
18559}
18560
18561// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18562// certain types of variables (unnamed, variably modified types etc.)
18563// so check for eligibility.
18565 SourceLocation Loc, const bool Diagnose,
18566 Sema &S) {
18567
18568 assert((isa<VarDecl, BindingDecl>(Var)) &&
18569 "Only variables and structured bindings can be captured");
18570
18571 bool IsBlock = isa<BlockScopeInfo>(CSI);
18572 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18573
18574 // Lambdas are not allowed to capture unnamed variables
18575 // (e.g. anonymous unions).
18576 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18577 // assuming that's the intent.
18578 if (IsLambda && !Var->getDeclName()) {
18579 if (Diagnose) {
18580 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18581 S.Diag(Var->getLocation(), diag::note_declared_at);
18582 }
18583 return false;
18584 }
18585
18586 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18587 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18588 if (Diagnose) {
18589 S.Diag(Loc, diag::err_ref_vm_type);
18590 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18591 }
18592 return false;
18593 }
18594 // Prohibit structs with flexible array members too.
18595 // We cannot capture what is in the tail end of the struct.
18596 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18597 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18598 if (Diagnose) {
18599 if (IsBlock)
18600 S.Diag(Loc, diag::err_ref_flexarray_type);
18601 else
18602 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18603 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18604 }
18605 return false;
18606 }
18607 }
18608 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18609 // Lambdas and captured statements are not allowed to capture __block
18610 // variables; they don't support the expected semantics.
18611 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18612 if (Diagnose) {
18613 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18614 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18615 }
18616 return false;
18617 }
18618 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18619 if (S.getLangOpts().OpenCL && IsBlock &&
18620 Var->getType()->isBlockPointerType()) {
18621 if (Diagnose)
18622 S.Diag(Loc, diag::err_opencl_block_ref_block);
18623 return false;
18624 }
18625
18626 if (isa<BindingDecl>(Var)) {
18627 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18628 if (Diagnose)
18630 return false;
18631 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18632 S.Diag(Loc, S.LangOpts.CPlusPlus20
18633 ? diag::warn_cxx17_compat_capture_binding
18634 : diag::ext_capture_binding)
18635 << Var;
18636 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18637 }
18638 }
18639
18640 return true;
18641}
18642
18643// Returns true if the capture by block was successful.
18645 SourceLocation Loc, const bool BuildAndDiagnose,
18646 QualType &CaptureType, QualType &DeclRefType,
18647 const bool Nested, Sema &S, bool Invalid) {
18648 bool ByRef = false;
18649
18650 // Blocks are not allowed to capture arrays, excepting OpenCL.
18651 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18652 // (decayed to pointers).
18653 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18654 if (BuildAndDiagnose) {
18655 S.Diag(Loc, diag::err_ref_array_type);
18656 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18657 Invalid = true;
18658 } else {
18659 return false;
18660 }
18661 }
18662
18663 // Forbid the block-capture of autoreleasing variables.
18664 if (!Invalid &&
18666 if (BuildAndDiagnose) {
18667 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18668 << /*block*/ 0;
18669 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18670 Invalid = true;
18671 } else {
18672 return false;
18673 }
18674 }
18675
18676 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18677 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18678 QualType PointeeTy = PT->getPointeeType();
18679
18680 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18682 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18683 if (BuildAndDiagnose) {
18684 SourceLocation VarLoc = Var->getLocation();
18685 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18686 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18687 }
18688 }
18689 }
18690
18691 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18692 if (HasBlocksAttr || CaptureType->isReferenceType() ||
18693 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
18694 // Block capture by reference does not change the capture or
18695 // declaration reference types.
18696 ByRef = true;
18697 } else {
18698 // Block capture by copy introduces 'const'.
18699 CaptureType = CaptureType.getNonReferenceType().withConst();
18700 DeclRefType = CaptureType;
18701 }
18702
18703 // Actually capture the variable.
18704 if (BuildAndDiagnose)
18705 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18706 CaptureType, Invalid);
18707
18708 return !Invalid;
18709}
18710
18711/// Capture the given variable in the captured region.
18714 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18715 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18716 bool IsTopScope, Sema &S, bool Invalid) {
18717 // By default, capture variables by reference.
18718 bool ByRef = true;
18719 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18720 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18721 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18722 // Using an LValue reference type is consistent with Lambdas (see below).
18723 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
18724 bool HasConst = DeclRefType.isConstQualified();
18725 DeclRefType = DeclRefType.getUnqualifiedType();
18726 // Don't lose diagnostics about assignments to const.
18727 if (HasConst)
18728 DeclRefType.addConst();
18729 }
18730 // Do not capture firstprivates in tasks.
18731 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
18732 RSI->OpenMPCaptureLevel) != OMPC_unknown)
18733 return true;
18734 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18735 RSI->OpenMPCaptureLevel);
18736 }
18737
18738 if (ByRef)
18739 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18740 else
18741 CaptureType = DeclRefType;
18742
18743 // Actually capture the variable.
18744 if (BuildAndDiagnose)
18745 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18746 Loc, SourceLocation(), CaptureType, Invalid);
18747
18748 return !Invalid;
18749}
18750
18751/// Capture the given variable in the lambda.
18753 SourceLocation Loc, const bool BuildAndDiagnose,
18754 QualType &CaptureType, QualType &DeclRefType,
18755 const bool RefersToCapturedVariable,
18756 const Sema::TryCaptureKind Kind,
18757 SourceLocation EllipsisLoc, const bool IsTopScope,
18758 Sema &S, bool Invalid) {
18759 // Determine whether we are capturing by reference or by value.
18760 bool ByRef = false;
18761 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18762 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18763 } else {
18764 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18765 }
18766
18767 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
18769 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
18770 Invalid = true;
18771 }
18772
18773 // Compute the type of the field that will capture this variable.
18774 if (ByRef) {
18775 // C++11 [expr.prim.lambda]p15:
18776 // An entity is captured by reference if it is implicitly or
18777 // explicitly captured but not captured by copy. It is
18778 // unspecified whether additional unnamed non-static data
18779 // members are declared in the closure type for entities
18780 // captured by reference.
18781 //
18782 // FIXME: It is not clear whether we want to build an lvalue reference
18783 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18784 // to do the former, while EDG does the latter. Core issue 1249 will
18785 // clarify, but for now we follow GCC because it's a more permissive and
18786 // easily defensible position.
18787 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18788 } else {
18789 // C++11 [expr.prim.lambda]p14:
18790 // For each entity captured by copy, an unnamed non-static
18791 // data member is declared in the closure type. The
18792 // declaration order of these members is unspecified. The type
18793 // of such a data member is the type of the corresponding
18794 // captured entity if the entity is not a reference to an
18795 // object, or the referenced type otherwise. [Note: If the
18796 // captured entity is a reference to a function, the
18797 // corresponding data member is also a reference to a
18798 // function. - end note ]
18799 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18800 if (!RefType->getPointeeType()->isFunctionType())
18801 CaptureType = RefType->getPointeeType();
18802 }
18803
18804 // Forbid the lambda copy-capture of autoreleasing variables.
18805 if (!Invalid &&
18807 if (BuildAndDiagnose) {
18808 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18809 S.Diag(Var->getLocation(), diag::note_previous_decl)
18810 << Var->getDeclName();
18811 Invalid = true;
18812 } else {
18813 return false;
18814 }
18815 }
18816
18817 // Make sure that by-copy captures are of a complete and non-abstract type.
18818 if (!Invalid && BuildAndDiagnose) {
18819 if (!CaptureType->isDependentType() &&
18821 Loc, CaptureType,
18822 diag::err_capture_of_incomplete_or_sizeless_type,
18823 Var->getDeclName()))
18824 Invalid = true;
18825 else if (S.RequireNonAbstractType(Loc, CaptureType,
18826 diag::err_capture_of_abstract_type))
18827 Invalid = true;
18828 }
18829 }
18830
18831 // Compute the type of a reference to this captured variable.
18832 if (ByRef)
18833 DeclRefType = CaptureType.getNonReferenceType();
18834 else {
18835 // C++ [expr.prim.lambda]p5:
18836 // The closure type for a lambda-expression has a public inline
18837 // function call operator [...]. This function call operator is
18838 // declared const (9.3.1) if and only if the lambda-expression's
18839 // parameter-declaration-clause is not followed by mutable.
18840 DeclRefType = CaptureType.getNonReferenceType();
18841 bool Const = LSI->lambdaCaptureShouldBeConst();
18842 // C++ [expr.prim.lambda]p10:
18843 // The type of such a data member is [...] an lvalue reference to the
18844 // referenced function type if the entity is a reference to a function.
18845 // [...]
18846 if (Const && !CaptureType->isReferenceType() &&
18847 !DeclRefType->isFunctionType())
18848 DeclRefType.addConst();
18849 }
18850
18851 // Add the capture.
18852 if (BuildAndDiagnose)
18853 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18854 Loc, EllipsisLoc, CaptureType, Invalid);
18855
18856 return !Invalid;
18857}
18858
18860 const ASTContext &Context) {
18861 // Offer a Copy fix even if the type is dependent.
18862 if (Var->getType()->isDependentType())
18863 return true;
18865 if (T.isTriviallyCopyableType(Context))
18866 return true;
18867 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18868
18869 if (!(RD = RD->getDefinition()))
18870 return false;
18871 if (RD->hasSimpleCopyConstructor())
18872 return true;
18873 if (RD->hasUserDeclaredCopyConstructor())
18874 for (CXXConstructorDecl *Ctor : RD->ctors())
18875 if (Ctor->isCopyConstructor())
18876 return !Ctor->isDeleted();
18877 }
18878 return false;
18879}
18880
18881/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18882/// default capture. Fixes may be omitted if they aren't allowed by the
18883/// standard, for example we can't emit a default copy capture fix-it if we
18884/// already explicitly copy capture capture another variable.
18886 ValueDecl *Var) {
18888 // Don't offer Capture by copy of default capture by copy fixes if Var is
18889 // known not to be copy constructible.
18890 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18891
18892 SmallString<32> FixBuffer;
18893 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18894 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18895 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18896 if (ShouldOfferCopyFix) {
18897 // Offer fixes to insert an explicit capture for the variable.
18898 // [] -> [VarName]
18899 // [OtherCapture] -> [OtherCapture, VarName]
18900 FixBuffer.assign({Separator, Var->getName()});
18901 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18902 << Var << /*value*/ 0
18903 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18904 }
18905 // As above but capture by reference.
18906 FixBuffer.assign({Separator, "&", Var->getName()});
18907 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18908 << Var << /*reference*/ 1
18909 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18910 }
18911
18912 // Only try to offer default capture if there are no captures excluding this
18913 // and init captures.
18914 // [this]: OK.
18915 // [X = Y]: OK.
18916 // [&A, &B]: Don't offer.
18917 // [A, B]: Don't offer.
18918 if (llvm::any_of(LSI->Captures, [](Capture &C) {
18919 return !C.isThisCapture() && !C.isInitCapture();
18920 }))
18921 return;
18922
18923 // The default capture specifiers, '=' or '&', must appear first in the
18924 // capture body.
18925 SourceLocation DefaultInsertLoc =
18927
18928 if (ShouldOfferCopyFix) {
18929 bool CanDefaultCopyCapture = true;
18930 // [=, *this] OK since c++17
18931 // [=, this] OK since c++20
18932 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18933 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18935 : false;
18936 // We can't use default capture by copy if any captures already specified
18937 // capture by copy.
18938 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18939 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18940 })) {
18941 FixBuffer.assign({"=", Separator});
18942 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18943 << /*value*/ 0
18944 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18945 }
18946 }
18947
18948 // We can't use default capture by reference if any captures already specified
18949 // capture by reference.
18950 if (llvm::none_of(LSI->Captures, [](Capture &C) {
18951 return !C.isInitCapture() && C.isReferenceCapture() &&
18952 !C.isThisCapture();
18953 })) {
18954 FixBuffer.assign({"&", Separator});
18955 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18956 << /*reference*/ 1
18957 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18958 }
18959}
18960
18962 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18963 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18964 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18965 // An init-capture is notionally from the context surrounding its
18966 // declaration, but its parent DC is the lambda class.
18967 DeclContext *VarDC = Var->getDeclContext();
18968 DeclContext *DC = CurContext;
18969
18970 // Skip past RequiresExprBodys because they don't constitute function scopes.
18971 while (DC->isRequiresExprBody())
18972 DC = DC->getParent();
18973
18974 // tryCaptureVariable is called every time a DeclRef is formed,
18975 // it can therefore have non-negigible impact on performances.
18976 // For local variables and when there is no capturing scope,
18977 // we can bailout early.
18978 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
18979 return true;
18980
18981 // Exception: Function parameters are not tied to the function's DeclContext
18982 // until we enter the function definition. Capturing them anyway would result
18983 // in an out-of-bounds error while traversing DC and its parents.
18984 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
18985 return true;
18986
18987 const auto *VD = dyn_cast<VarDecl>(Var);
18988 if (VD) {
18989 if (VD->isInitCapture())
18990 VarDC = VarDC->getParent();
18991 } else {
18993 }
18994 assert(VD && "Cannot capture a null variable");
18995
18996 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18997 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18998 // We need to sync up the Declaration Context with the
18999 // FunctionScopeIndexToStopAt
19000 if (FunctionScopeIndexToStopAt) {
19001 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
19002 unsigned FSIndex = FunctionScopes.size() - 1;
19003 // When we're parsing the lambda parameter list, the current DeclContext is
19004 // NOT the lambda but its parent. So move away the current LSI before
19005 // aligning DC and FunctionScopeIndexToStopAt.
19006 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
19007 FSIndex && LSI && !LSI->AfterParameterList)
19008 --FSIndex;
19009 assert(MaxFunctionScopesIndex <= FSIndex &&
19010 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
19011 "FunctionScopes.");
19012 while (FSIndex != MaxFunctionScopesIndex) {
19014 --FSIndex;
19015 }
19016 }
19017
19018 // Capture global variables if it is required to use private copy of this
19019 // variable.
19020 bool IsGlobal = !VD->hasLocalStorage();
19021 if (IsGlobal && !(LangOpts.OpenMP &&
19022 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19023 MaxFunctionScopesIndex)))
19024 return true;
19025
19026 if (isa<VarDecl>(Var))
19027 Var = cast<VarDecl>(Var->getCanonicalDecl());
19028
19029 // Walk up the stack to determine whether we can capture the variable,
19030 // performing the "simple" checks that don't depend on type. We stop when
19031 // we've either hit the declared scope of the variable or find an existing
19032 // capture of that variable. We start from the innermost capturing-entity
19033 // (the DC) and ensure that all intervening capturing-entities
19034 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19035 // declcontext can either capture the variable or have already captured
19036 // the variable.
19037 CaptureType = Var->getType();
19038 DeclRefType = CaptureType.getNonReferenceType();
19039 bool Nested = false;
19040 bool Explicit = (Kind != TryCapture_Implicit);
19041 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19042 do {
19043
19044 LambdaScopeInfo *LSI = nullptr;
19045 if (!FunctionScopes.empty())
19046 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19047 FunctionScopes[FunctionScopesIndex]);
19048
19049 bool IsInScopeDeclarationContext =
19050 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19051
19052 if (LSI && !LSI->AfterParameterList) {
19053 // This allows capturing parameters from a default value which does not
19054 // seems correct
19055 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19056 return true;
19057 }
19058 // If the variable is declared in the current context, there is no need to
19059 // capture it.
19060 if (IsInScopeDeclarationContext &&
19061 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19062 return true;
19063
19064 // Only block literals, captured statements, and lambda expressions can
19065 // capture; other scopes don't work.
19066 DeclContext *ParentDC =
19067 !IsInScopeDeclarationContext
19068 ? DC->getParent()
19069 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19070 BuildAndDiagnose, *this);
19071 // We need to check for the parent *first* because, if we *have*
19072 // private-captured a global variable, we need to recursively capture it in
19073 // intermediate blocks, lambdas, etc.
19074 if (!ParentDC) {
19075 if (IsGlobal) {
19076 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19077 break;
19078 }
19079 return true;
19080 }
19081
19082 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19083 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
19084
19085 // Check whether we've already captured it.
19086 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19087 DeclRefType)) {
19088 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19089 break;
19090 }
19091
19092 // When evaluating some attributes (like enable_if) we might refer to a
19093 // function parameter appertaining to the same declaration as that
19094 // attribute.
19095 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19096 Parm && Parm->getDeclContext() == DC)
19097 return true;
19098
19099 // If we are instantiating a generic lambda call operator body,
19100 // we do not want to capture new variables. What was captured
19101 // during either a lambdas transformation or initial parsing
19102 // should be used.
19104 if (BuildAndDiagnose) {
19105 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19107 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19108 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19109 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19110 buildLambdaCaptureFixit(*this, LSI, Var);
19111 } else
19113 }
19114 return true;
19115 }
19116
19117 // Try to capture variable-length arrays types.
19118 if (Var->getType()->isVariablyModifiedType()) {
19119 // We're going to walk down into the type and look for VLA
19120 // expressions.
19121 QualType QTy = Var->getType();
19122 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19123 QTy = PVD->getOriginalType();
19125 }
19126
19127 if (getLangOpts().OpenMP) {
19128 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19129 // OpenMP private variables should not be captured in outer scope, so
19130 // just break here. Similarly, global variables that are captured in a
19131 // target region should not be captured outside the scope of the region.
19132 if (RSI->CapRegionKind == CR_OpenMP) {
19133 // FIXME: We should support capturing structured bindings in OpenMP.
19134 if (isa<BindingDecl>(Var)) {
19135 if (BuildAndDiagnose) {
19136 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19137 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19138 }
19139 return true;
19140 }
19141 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19142 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19143 // If the variable is private (i.e. not captured) and has variably
19144 // modified type, we still need to capture the type for correct
19145 // codegen in all regions, associated with the construct. Currently,
19146 // it is captured in the innermost captured region only.
19147 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19148 Var->getType()->isVariablyModifiedType()) {
19149 QualType QTy = Var->getType();
19150 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19151 QTy = PVD->getOriginalType();
19152 for (int I = 1,
19153 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
19154 I < E; ++I) {
19155 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19156 FunctionScopes[FunctionScopesIndex - I]);
19157 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19158 "Wrong number of captured regions associated with the "
19159 "OpenMP construct.");
19160 captureVariablyModifiedType(Context, QTy, OuterRSI);
19161 }
19162 }
19163 bool IsTargetCap =
19164 IsOpenMPPrivateDecl != OMPC_private &&
19165 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19166 RSI->OpenMPCaptureLevel);
19167 // Do not capture global if it is not privatized in outer regions.
19168 bool IsGlobalCap =
19169 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19170 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19171
19172 // When we detect target captures we are looking from inside the
19173 // target region, therefore we need to propagate the capture from the
19174 // enclosing region. Therefore, the capture is not initially nested.
19175 if (IsTargetCap)
19176 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19177 RSI->OpenMPLevel);
19178
19179 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19180 (IsGlobal && !IsGlobalCap)) {
19181 Nested = !IsTargetCap;
19182 bool HasConst = DeclRefType.isConstQualified();
19183 DeclRefType = DeclRefType.getUnqualifiedType();
19184 // Don't lose diagnostics about assignments to const.
19185 if (HasConst)
19186 DeclRefType.addConst();
19187 CaptureType = Context.getLValueReferenceType(DeclRefType);
19188 break;
19189 }
19190 }
19191 }
19192 }
19194 // No capture-default, and this is not an explicit capture
19195 // so cannot capture this variable.
19196 if (BuildAndDiagnose) {
19197 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19198 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19199 auto *LSI = cast<LambdaScopeInfo>(CSI);
19200 if (LSI->Lambda) {
19201 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19202 buildLambdaCaptureFixit(*this, LSI, Var);
19203 }
19204 // FIXME: If we error out because an outer lambda can not implicitly
19205 // capture a variable that an inner lambda explicitly captures, we
19206 // should have the inner lambda do the explicit capture - because
19207 // it makes for cleaner diagnostics later. This would purely be done
19208 // so that the diagnostic does not misleadingly claim that a variable
19209 // can not be captured by a lambda implicitly even though it is captured
19210 // explicitly. Suggestion:
19211 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19212 // at the function head
19213 // - cache the StartingDeclContext - this must be a lambda
19214 // - captureInLambda in the innermost lambda the variable.
19215 }
19216 return true;
19217 }
19218 Explicit = false;
19219 FunctionScopesIndex--;
19220 if (IsInScopeDeclarationContext)
19221 DC = ParentDC;
19222 } while (!VarDC->Equals(DC));
19223
19224 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19225 // computing the type of the capture at each step, checking type-specific
19226 // requirements, and adding captures if requested.
19227 // If the variable had already been captured previously, we start capturing
19228 // at the lambda nested within that one.
19229 bool Invalid = false;
19230 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19231 ++I) {
19232 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19233
19234 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19235 // certain types of variables (unnamed, variably modified types etc.)
19236 // so check for eligibility.
19237 if (!Invalid)
19238 Invalid =
19239 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19240
19241 // After encountering an error, if we're actually supposed to capture, keep
19242 // capturing in nested contexts to suppress any follow-on diagnostics.
19243 if (Invalid && !BuildAndDiagnose)
19244 return true;
19245
19246 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19247 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19248 DeclRefType, Nested, *this, Invalid);
19249 Nested = true;
19250 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19252 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19253 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19254 Nested = true;
19255 } else {
19256 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19257 Invalid =
19258 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19259 DeclRefType, Nested, Kind, EllipsisLoc,
19260 /*IsTopScope*/ I == N - 1, *this, Invalid);
19261 Nested = true;
19262 }
19263
19264 if (Invalid && !BuildAndDiagnose)
19265 return true;
19266 }
19267 return Invalid;
19268}
19269
19271 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19272 QualType CaptureType;
19273 QualType DeclRefType;
19274 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19275 /*BuildAndDiagnose=*/true, CaptureType,
19276 DeclRefType, nullptr);
19277}
19278
19280 QualType CaptureType;
19281 QualType DeclRefType;
19283 /*BuildAndDiagnose=*/false, CaptureType,
19284 DeclRefType, nullptr);
19285}
19286
19288 assert(Var && "Null value cannot be captured");
19289
19290 QualType CaptureType;
19291 QualType DeclRefType;
19292
19293 // Determine whether we can capture this variable.
19295 /*BuildAndDiagnose=*/false, CaptureType,
19296 DeclRefType, nullptr))
19297 return QualType();
19298
19299 return DeclRefType;
19300}
19301
19302namespace {
19303// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19304// The produced TemplateArgumentListInfo* points to data stored within this
19305// object, so should only be used in contexts where the pointer will not be
19306// used after the CopiedTemplateArgs object is destroyed.
19307class CopiedTemplateArgs {
19308 bool HasArgs;
19309 TemplateArgumentListInfo TemplateArgStorage;
19310public:
19311 template<typename RefExpr>
19312 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19313 if (HasArgs)
19314 E->copyTemplateArgumentsInto(TemplateArgStorage);
19315 }
19316 operator TemplateArgumentListInfo*()
19317#ifdef __has_cpp_attribute
19318#if __has_cpp_attribute(clang::lifetimebound)
19319 [[clang::lifetimebound]]
19320#endif
19321#endif
19322 {
19323 return HasArgs ? &TemplateArgStorage : nullptr;
19324 }
19325};
19326}
19327
19328/// Walk the set of potential results of an expression and mark them all as
19329/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19330///
19331/// \return A new expression if we found any potential results, ExprEmpty() if
19332/// not, and ExprError() if we diagnosed an error.
19334 NonOdrUseReason NOUR) {
19335 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19336 // an object that satisfies the requirements for appearing in a
19337 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19338 // is immediately applied." This function handles the lvalue-to-rvalue
19339 // conversion part.
19340 //
19341 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19342 // transform it into the relevant kind of non-odr-use node and rebuild the
19343 // tree of nodes leading to it.
19344 //
19345 // This is a mini-TreeTransform that only transforms a restricted subset of
19346 // nodes (and only certain operands of them).
19347
19348 // Rebuild a subexpression.
19349 auto Rebuild = [&](Expr *Sub) {
19350 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19351 };
19352
19353 // Check whether a potential result satisfies the requirements of NOUR.
19354 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19355 // Any entity other than a VarDecl is always odr-used whenever it's named
19356 // in a potentially-evaluated expression.
19357 auto *VD = dyn_cast<VarDecl>(D);
19358 if (!VD)
19359 return true;
19360
19361 // C++2a [basic.def.odr]p4:
19362 // A variable x whose name appears as a potentially-evalauted expression
19363 // e is odr-used by e unless
19364 // -- x is a reference that is usable in constant expressions, or
19365 // -- x is a variable of non-reference type that is usable in constant
19366 // expressions and has no mutable subobjects, and e is an element of
19367 // the set of potential results of an expression of
19368 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19369 // conversion is applied, or
19370 // -- x is a variable of non-reference type, and e is an element of the
19371 // set of potential results of a discarded-value expression to which
19372 // the lvalue-to-rvalue conversion is not applied
19373 //
19374 // We check the first bullet and the "potentially-evaluated" condition in
19375 // BuildDeclRefExpr. We check the type requirements in the second bullet
19376 // in CheckLValueToRValueConversionOperand below.
19377 switch (NOUR) {
19378 case NOUR_None:
19379 case NOUR_Unevaluated:
19380 llvm_unreachable("unexpected non-odr-use-reason");
19381
19382 case NOUR_Constant:
19383 // Constant references were handled when they were built.
19384 if (VD->getType()->isReferenceType())
19385 return true;
19386 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19387 if (RD->hasDefinition() && RD->hasMutableFields())
19388 return true;
19389 if (!VD->isUsableInConstantExpressions(S.Context))
19390 return true;
19391 break;
19392
19393 case NOUR_Discarded:
19394 if (VD->getType()->isReferenceType())
19395 return true;
19396 break;
19397 }
19398 return false;
19399 };
19400
19401 // Mark that this expression does not constitute an odr-use.
19402 auto MarkNotOdrUsed = [&] {
19403 S.MaybeODRUseExprs.remove(E);
19404 if (LambdaScopeInfo *LSI = S.getCurLambda())
19405 LSI->markVariableExprAsNonODRUsed(E);
19406 };
19407
19408 // C++2a [basic.def.odr]p2:
19409 // The set of potential results of an expression e is defined as follows:
19410 switch (E->getStmtClass()) {
19411 // -- If e is an id-expression, ...
19412 case Expr::DeclRefExprClass: {
19413 auto *DRE = cast<DeclRefExpr>(E);
19414 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19415 break;
19416
19417 // Rebuild as a non-odr-use DeclRefExpr.
19418 MarkNotOdrUsed();
19419 return DeclRefExpr::Create(
19420 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19421 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19422 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19423 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19424 }
19425
19426 case Expr::FunctionParmPackExprClass: {
19427 auto *FPPE = cast<FunctionParmPackExpr>(E);
19428 // If any of the declarations in the pack is odr-used, then the expression
19429 // as a whole constitutes an odr-use.
19430 for (VarDecl *D : *FPPE)
19431 if (IsPotentialResultOdrUsed(D))
19432 return ExprEmpty();
19433
19434 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19435 // nothing cares about whether we marked this as an odr-use, but it might
19436 // be useful for non-compiler tools.
19437 MarkNotOdrUsed();
19438 break;
19439 }
19440
19441 // -- If e is a subscripting operation with an array operand...
19442 case Expr::ArraySubscriptExprClass: {
19443 auto *ASE = cast<ArraySubscriptExpr>(E);
19444 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19445 if (!OldBase->getType()->isArrayType())
19446 break;
19447 ExprResult Base = Rebuild(OldBase);
19448 if (!Base.isUsable())
19449 return Base;
19450 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19451 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19452 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19453 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19454 ASE->getRBracketLoc());
19455 }
19456
19457 case Expr::MemberExprClass: {
19458 auto *ME = cast<MemberExpr>(E);
19459 // -- If e is a class member access expression [...] naming a non-static
19460 // data member...
19461 if (isa<FieldDecl>(ME->getMemberDecl())) {
19462 ExprResult Base = Rebuild(ME->getBase());
19463 if (!Base.isUsable())
19464 return Base;
19465 return MemberExpr::Create(
19466 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19467 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19468 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19469 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19470 ME->getObjectKind(), ME->isNonOdrUse());
19471 }
19472
19473 if (ME->getMemberDecl()->isCXXInstanceMember())
19474 break;
19475
19476 // -- If e is a class member access expression naming a static data member,
19477 // ...
19478 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19479 break;
19480
19481 // Rebuild as a non-odr-use MemberExpr.
19482 MarkNotOdrUsed();
19483 return MemberExpr::Create(
19484 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19485 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19486 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19487 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19488 }
19489
19490 case Expr::BinaryOperatorClass: {
19491 auto *BO = cast<BinaryOperator>(E);
19492 Expr *LHS = BO->getLHS();
19493 Expr *RHS = BO->getRHS();
19494 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19495 if (BO->getOpcode() == BO_PtrMemD) {
19496 ExprResult Sub = Rebuild(LHS);
19497 if (!Sub.isUsable())
19498 return Sub;
19499 BO->setLHS(Sub.get());
19500 // -- If e is a comma expression, ...
19501 } else if (BO->getOpcode() == BO_Comma) {
19502 ExprResult Sub = Rebuild(RHS);
19503 if (!Sub.isUsable())
19504 return Sub;
19505 BO->setRHS(Sub.get());
19506 } else {
19507 break;
19508 }
19509 return ExprResult(BO);
19510 }
19511
19512 // -- If e has the form (e1)...
19513 case Expr::ParenExprClass: {
19514 auto *PE = cast<ParenExpr>(E);
19515 ExprResult Sub = Rebuild(PE->getSubExpr());
19516 if (!Sub.isUsable())
19517 return Sub;
19518 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19519 }
19520
19521 // -- If e is a glvalue conditional expression, ...
19522 // We don't apply this to a binary conditional operator. FIXME: Should we?
19523 case Expr::ConditionalOperatorClass: {
19524 auto *CO = cast<ConditionalOperator>(E);
19525 ExprResult LHS = Rebuild(CO->getLHS());
19526 if (LHS.isInvalid())
19527 return ExprError();
19528 ExprResult RHS = Rebuild(CO->getRHS());
19529 if (RHS.isInvalid())
19530 return ExprError();
19531 if (!LHS.isUsable() && !RHS.isUsable())
19532 return ExprEmpty();
19533 if (!LHS.isUsable())
19534 LHS = CO->getLHS();
19535 if (!RHS.isUsable())
19536 RHS = CO->getRHS();
19537 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19538 CO->getCond(), LHS.get(), RHS.get());
19539 }
19540
19541 // [Clang extension]
19542 // -- If e has the form __extension__ e1...
19543 case Expr::UnaryOperatorClass: {
19544 auto *UO = cast<UnaryOperator>(E);
19545 if (UO->getOpcode() != UO_Extension)
19546 break;
19547 ExprResult Sub = Rebuild(UO->getSubExpr());
19548 if (!Sub.isUsable())
19549 return Sub;
19550 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19551 Sub.get());
19552 }
19553
19554 // [Clang extension]
19555 // -- If e has the form _Generic(...), the set of potential results is the
19556 // union of the sets of potential results of the associated expressions.
19557 case Expr::GenericSelectionExprClass: {
19558 auto *GSE = cast<GenericSelectionExpr>(E);
19559
19560 SmallVector<Expr *, 4> AssocExprs;
19561 bool AnyChanged = false;
19562 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19563 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19564 if (AssocExpr.isInvalid())
19565 return ExprError();
19566 if (AssocExpr.isUsable()) {
19567 AssocExprs.push_back(AssocExpr.get());
19568 AnyChanged = true;
19569 } else {
19570 AssocExprs.push_back(OrigAssocExpr);
19571 }
19572 }
19573
19574 void *ExOrTy = nullptr;
19575 bool IsExpr = GSE->isExprPredicate();
19576 if (IsExpr)
19577 ExOrTy = GSE->getControllingExpr();
19578 else
19579 ExOrTy = GSE->getControllingType();
19580 return AnyChanged ? S.CreateGenericSelectionExpr(
19581 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19582 GSE->getRParenLoc(), IsExpr, ExOrTy,
19583 GSE->getAssocTypeSourceInfos(), AssocExprs)
19584 : ExprEmpty();
19585 }
19586
19587 // [Clang extension]
19588 // -- If e has the form __builtin_choose_expr(...), the set of potential
19589 // results is the union of the sets of potential results of the
19590 // second and third subexpressions.
19591 case Expr::ChooseExprClass: {
19592 auto *CE = cast<ChooseExpr>(E);
19593
19594 ExprResult LHS = Rebuild(CE->getLHS());
19595 if (LHS.isInvalid())
19596 return ExprError();
19597
19598 ExprResult RHS = Rebuild(CE->getLHS());
19599 if (RHS.isInvalid())
19600 return ExprError();
19601
19602 if (!LHS.get() && !RHS.get())
19603 return ExprEmpty();
19604 if (!LHS.isUsable())
19605 LHS = CE->getLHS();
19606 if (!RHS.isUsable())
19607 RHS = CE->getRHS();
19608
19609 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19610 RHS.get(), CE->getRParenLoc());
19611 }
19612
19613 // Step through non-syntactic nodes.
19614 case Expr::ConstantExprClass: {
19615 auto *CE = cast<ConstantExpr>(E);
19616 ExprResult Sub = Rebuild(CE->getSubExpr());
19617 if (!Sub.isUsable())
19618 return Sub;
19619 return ConstantExpr::Create(S.Context, Sub.get());
19620 }
19621
19622 // We could mostly rely on the recursive rebuilding to rebuild implicit
19623 // casts, but not at the top level, so rebuild them here.
19624 case Expr::ImplicitCastExprClass: {
19625 auto *ICE = cast<ImplicitCastExpr>(E);
19626 // Only step through the narrow set of cast kinds we expect to encounter.
19627 // Anything else suggests we've left the region in which potential results
19628 // can be found.
19629 switch (ICE->getCastKind()) {
19630 case CK_NoOp:
19631 case CK_DerivedToBase:
19632 case CK_UncheckedDerivedToBase: {
19633 ExprResult Sub = Rebuild(ICE->getSubExpr());
19634 if (!Sub.isUsable())
19635 return Sub;
19636 CXXCastPath Path(ICE->path());
19637 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19638 ICE->getValueKind(), &Path);
19639 }
19640
19641 default:
19642 break;
19643 }
19644 break;
19645 }
19646
19647 default:
19648 break;
19649 }
19650
19651 // Can't traverse through this node. Nothing to do.
19652 return ExprEmpty();
19653}
19654
19656 // Check whether the operand is or contains an object of non-trivial C union
19657 // type.
19658 if (E->getType().isVolatileQualified() &&
19664
19665 // C++2a [basic.def.odr]p4:
19666 // [...] an expression of non-volatile-qualified non-class type to which
19667 // the lvalue-to-rvalue conversion is applied [...]
19669 return E;
19670
19673 if (Result.isInvalid())
19674 return ExprError();
19675 return Result.get() ? Result : E;
19676}
19677
19679 Res = CorrectDelayedTyposInExpr(Res);
19680
19681 if (!Res.isUsable())
19682 return Res;
19683
19684 // If a constant-expression is a reference to a variable where we delay
19685 // deciding whether it is an odr-use, just assume we will apply the
19686 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19687 // (a non-type template argument), we have special handling anyway.
19689}
19690
19692 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19693 // call.
19694 MaybeODRUseExprSet LocalMaybeODRUseExprs;
19695 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19696
19697 for (Expr *E : LocalMaybeODRUseExprs) {
19698 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19699 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19700 DRE->getLocation(), *this);
19701 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19702 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19703 *this);
19704 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19705 for (VarDecl *VD : *FP)
19706 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19707 } else {
19708 llvm_unreachable("Unexpected expression");
19709 }
19710 }
19711
19712 assert(MaybeODRUseExprs.empty() &&
19713 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19714}
19715
19717 ValueDecl *Var, Expr *E) {
19719 if (!VD)
19720 return;
19721
19722 const bool RefersToEnclosingScope =
19723 (SemaRef.CurContext != VD->getDeclContext() &&
19725 if (RefersToEnclosingScope) {
19726 LambdaScopeInfo *const LSI =
19727 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19728 if (LSI && (!LSI->CallOperator ||
19729 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19730 // If a variable could potentially be odr-used, defer marking it so
19731 // until we finish analyzing the full expression for any
19732 // lvalue-to-rvalue
19733 // or discarded value conversions that would obviate odr-use.
19734 // Add it to the list of potential captures that will be analyzed
19735 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19736 // unless the variable is a reference that was initialized by a constant
19737 // expression (this will never need to be captured or odr-used).
19738 //
19739 // FIXME: We can simplify this a lot after implementing P0588R1.
19740 assert(E && "Capture variable should be used in an expression.");
19741 if (!Var->getType()->isReferenceType() ||
19744 }
19745 }
19746}
19747
19750 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19751 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19752 isa<FunctionParmPackExpr>(E)) &&
19753 "Invalid Expr argument to DoMarkVarDeclReferenced");
19754 Var->setReferenced();
19755
19756 if (Var->isInvalidDecl())
19757 return;
19758
19759 auto *MSI = Var->getMemberSpecializationInfo();
19762
19763 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19764 bool UsableInConstantExpr =
19766
19767 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19768 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19769 }
19770
19771 // C++20 [expr.const]p12:
19772 // A variable [...] is needed for constant evaluation if it is [...] a
19773 // variable whose name appears as a potentially constant evaluated
19774 // expression that is either a contexpr variable or is of non-volatile
19775 // const-qualified integral type or of reference type
19776 bool NeededForConstantEvaluation =
19777 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19778
19779 bool NeedDefinition =
19780 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19781
19782 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19783 "Can't instantiate a partial template specialization.");
19784
19785 // If this might be a member specialization of a static data member, check
19786 // the specialization is visible. We already did the checks for variable
19787 // template specializations when we created them.
19788 if (NeedDefinition && TSK != TSK_Undeclared &&
19789 !isa<VarTemplateSpecializationDecl>(Var))
19791
19792 // Perform implicit instantiation of static data members, static data member
19793 // templates of class templates, and variable template specializations. Delay
19794 // instantiations of variable templates, except for those that could be used
19795 // in a constant expression.
19796 if (NeedDefinition && isTemplateInstantiation(TSK)) {
19797 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19798 // instantiation declaration if a variable is usable in a constant
19799 // expression (among other cases).
19800 bool TryInstantiating =
19802 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19803
19804 if (TryInstantiating) {
19805 SourceLocation PointOfInstantiation =
19806 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19807 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19808 if (FirstInstantiation) {
19809 PointOfInstantiation = Loc;
19810 if (MSI)
19811 MSI->setPointOfInstantiation(PointOfInstantiation);
19812 // FIXME: Notify listener.
19813 else
19814 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19815 }
19816
19817 if (UsableInConstantExpr) {
19818 // Do not defer instantiations of variables that could be used in a
19819 // constant expression.
19820 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19821 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19822 });
19823
19824 // Re-set the member to trigger a recomputation of the dependence bits
19825 // for the expression.
19826 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19827 DRE->setDecl(DRE->getDecl());
19828 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19829 ME->setMemberDecl(ME->getMemberDecl());
19830 } else if (FirstInstantiation) {
19832 .push_back(std::make_pair(Var, PointOfInstantiation));
19833 } else {
19834 bool Inserted = false;
19835 for (auto &I : SemaRef.SavedPendingInstantiations) {
19836 auto Iter = llvm::find_if(
19837 I, [Var](const Sema::PendingImplicitInstantiation &P) {
19838 return P.first == Var;
19839 });
19840 if (Iter != I.end()) {
19842 I.erase(Iter);
19843 Inserted = true;
19844 break;
19845 }
19846 }
19847
19848 // FIXME: For a specialization of a variable template, we don't
19849 // distinguish between "declaration and type implicitly instantiated"
19850 // and "implicit instantiation of definition requested", so we have
19851 // no direct way to avoid enqueueing the pending instantiation
19852 // multiple times.
19853 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
19855 .push_back(std::make_pair(Var, PointOfInstantiation));
19856 }
19857 }
19858 }
19859
19860 // C++2a [basic.def.odr]p4:
19861 // A variable x whose name appears as a potentially-evaluated expression e
19862 // is odr-used by e unless
19863 // -- x is a reference that is usable in constant expressions
19864 // -- x is a variable of non-reference type that is usable in constant
19865 // expressions and has no mutable subobjects [FIXME], and e is an
19866 // element of the set of potential results of an expression of
19867 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19868 // conversion is applied
19869 // -- x is a variable of non-reference type, and e is an element of the set
19870 // of potential results of a discarded-value expression to which the
19871 // lvalue-to-rvalue conversion is not applied [FIXME]
19872 //
19873 // We check the first part of the second bullet here, and
19874 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19875 // FIXME: To get the third bullet right, we need to delay this even for
19876 // variables that are not usable in constant expressions.
19877
19878 // If we already know this isn't an odr-use, there's nothing more to do.
19879 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19880 if (DRE->isNonOdrUse())
19881 return;
19882 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19883 if (ME->isNonOdrUse())
19884 return;
19885
19886 switch (OdrUse) {
19887 case OdrUseContext::None:
19888 // In some cases, a variable may not have been marked unevaluated, if it
19889 // appears in a defaukt initializer.
19890 assert((!E || isa<FunctionParmPackExpr>(E) ||
19892 "missing non-odr-use marking for unevaluated decl ref");
19893 break;
19894
19895 case OdrUseContext::FormallyOdrUsed:
19896 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19897 // behavior.
19898 break;
19899
19900 case OdrUseContext::Used:
19901 // If we might later find that this expression isn't actually an odr-use,
19902 // delay the marking.
19904 SemaRef.MaybeODRUseExprs.insert(E);
19905 else
19907 break;
19908
19909 case OdrUseContext::Dependent:
19910 // If this is a dependent context, we don't need to mark variables as
19911 // odr-used, but we may still need to track them for lambda capture.
19912 // FIXME: Do we also need to do this inside dependent typeid expressions
19913 // (which are modeled as unevaluated at this point)?
19915 break;
19916 }
19917}
19918
19920 BindingDecl *BD, Expr *E) {
19921 BD->setReferenced();
19922
19923 if (BD->isInvalidDecl())
19924 return;
19925
19926 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19927 if (OdrUse == OdrUseContext::Used) {
19928 QualType CaptureType, DeclRefType;
19930 /*EllipsisLoc*/ SourceLocation(),
19931 /*BuildAndDiagnose*/ true, CaptureType,
19932 DeclRefType,
19933 /*FunctionScopeIndexToStopAt*/ nullptr);
19934 } else if (OdrUse == OdrUseContext::Dependent) {
19936 }
19937}
19938
19940 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19941}
19942
19943// C++ [temp.dep.expr]p3:
19944// An id-expression is type-dependent if it contains:
19945// - an identifier associated by name lookup with an entity captured by copy
19946// in a lambda-expression that has an explicit object parameter whose type
19947// is dependent ([dcl.fct]),
19949 Sema &SemaRef, ValueDecl *D, Expr *E) {
19950 auto *ID = dyn_cast<DeclRefExpr>(E);
19951 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
19952 return;
19953
19954 // If any enclosing lambda with a dependent explicit object parameter either
19955 // explicitly captures the variable by value, or has a capture default of '='
19956 // and does not capture the variable by reference, then the type of the DRE
19957 // is dependent on the type of that lambda's explicit object parameter.
19958 auto IsDependent = [&]() {
19959 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
19960 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
19961 if (!LSI)
19962 continue;
19963
19964 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
19965 LSI->AfterParameterList)
19966 return false;
19967
19968 const auto *MD = LSI->CallOperator;
19969 if (MD->getType().isNull())
19970 continue;
19971
19972 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
19973 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
19974 !Ty->getParamType(0)->isDependentType())
19975 continue;
19976
19977 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
19978 if (C->isCopyCapture())
19979 return true;
19980 continue;
19981 }
19982
19983 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
19984 return true;
19985 }
19986 return false;
19987 }();
19988
19989 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
19990 IsDependent, SemaRef.getASTContext());
19991}
19992
19993static void
19995 bool MightBeOdrUse,
19996 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19999
20000 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20002 if (SemaRef.getLangOpts().CPlusPlus)
20004 Var, E);
20005 return;
20006 }
20007
20008 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20010 if (SemaRef.getLangOpts().CPlusPlus)
20012 Decl, E);
20013 return;
20014 }
20015 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20016
20017 // If this is a call to a method via a cast, also mark the method in the
20018 // derived class used in case codegen can devirtualize the call.
20019 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20020 if (!ME)
20021 return;
20022 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20023 if (!MD)
20024 return;
20025 // Only attempt to devirtualize if this is truly a virtual call.
20026 bool IsVirtualCall = MD->isVirtual() &&
20028 if (!IsVirtualCall)
20029 return;
20030
20031 // If it's possible to devirtualize the call, mark the called function
20032 // referenced.
20034 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20035 if (DM)
20036 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20037}
20038
20040 // TODO: update this with DR# once a defect report is filed.
20041 // C++11 defect. The address of a pure member should not be an ODR use, even
20042 // if it's a qualified reference.
20043 bool OdrUse = true;
20044 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20045 if (Method->isVirtual() &&
20046 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20047 OdrUse = false;
20048
20049 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20053 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20054 !FD->isDependentContext())
20055 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20056 }
20057 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20059}
20060
20062 // C++11 [basic.def.odr]p2:
20063 // A non-overloaded function whose name appears as a potentially-evaluated
20064 // expression or a member of a set of candidate functions, if selected by
20065 // overload resolution when referred to from a potentially-evaluated
20066 // expression, is odr-used, unless it is a pure virtual function and its
20067 // name is not explicitly qualified.
20068 bool MightBeOdrUse = true;
20069 if (E->performsVirtualDispatch(getLangOpts())) {
20070 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20071 if (Method->isPureVirtual())
20072 MightBeOdrUse = false;
20073 }
20075 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20076 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20078}
20079
20081 for (VarDecl *VD : *E)
20082 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20084}
20085
20086/// Perform marking for a reference to an arbitrary declaration. It
20087/// marks the declaration referenced, and performs odr-use checking for
20088/// functions and variables. This method should not be used when building a
20089/// normal expression which refers to a variable.
20091 bool MightBeOdrUse) {
20092 if (MightBeOdrUse) {
20093 if (auto *VD = dyn_cast<VarDecl>(D)) {
20095 return;
20096 }
20097 }
20098 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20099 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20100 return;
20101 }
20102 D->setReferenced();
20103}
20104
20105namespace {
20106 // Mark all of the declarations used by a type as referenced.
20107 // FIXME: Not fully implemented yet! We need to have a better understanding
20108 // of when we're entering a context we should not recurse into.
20109 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20110 // TreeTransforms rebuilding the type in a new context. Rather than
20111 // duplicating the TreeTransform logic, we should consider reusing it here.
20112 // Currently that causes problems when rebuilding LambdaExprs.
20113class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20114 Sema &S;
20116
20117public:
20118 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20119
20120 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20121};
20122}
20123
20124bool MarkReferencedDecls::TraverseTemplateArgument(
20125 const TemplateArgument &Arg) {
20126 {
20127 // A non-type template argument is a constant-evaluated context.
20131 if (Decl *D = Arg.getAsDecl())
20132 S.MarkAnyDeclReferenced(Loc, D, true);
20133 } else if (Arg.getKind() == TemplateArgument::Expression) {
20135 }
20136 }
20137
20139}
20140
20142 MarkReferencedDecls Marker(*this, Loc);
20143 Marker.TraverseType(T);
20144}
20145
20146namespace {
20147/// Helper class that marks all of the declarations referenced by
20148/// potentially-evaluated subexpressions as "referenced".
20149class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20150public:
20151 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20152 bool SkipLocalVariables;
20154
20155 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20157 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20158
20159 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20160 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20161 }
20162
20163 void Visit(Expr *E) {
20164 if (llvm::is_contained(StopAt, E))
20165 return;
20166 Inherited::Visit(E);
20167 }
20168
20169 void VisitConstantExpr(ConstantExpr *E) {
20170 // Don't mark declarations within a ConstantExpression, as this expression
20171 // will be evaluated and folded to a value.
20172 }
20173
20174 void VisitDeclRefExpr(DeclRefExpr *E) {
20175 // If we were asked not to visit local variables, don't.
20176 if (SkipLocalVariables) {
20177 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20178 if (VD->hasLocalStorage())
20179 return;
20180 }
20181
20182 // FIXME: This can trigger the instantiation of the initializer of a
20183 // variable, which can cause the expression to become value-dependent
20184 // or error-dependent. Do we need to propagate the new dependence bits?
20186 }
20187
20188 void VisitMemberExpr(MemberExpr *E) {
20190 Visit(E->getBase());
20191 }
20192};
20193} // namespace
20194
20196 bool SkipLocalVariables,
20197 ArrayRef<const Expr*> StopAt) {
20198 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20199}
20200
20201/// Emit a diagnostic when statements are reachable.
20202/// FIXME: check for reachability even in expressions for which we don't build a
20203/// CFG (eg, in the initializer of a global or in a constant expression).
20204/// For example,
20205/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20207 const PartialDiagnostic &PD) {
20208 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20209 if (!FunctionScopes.empty())
20210 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20212 return true;
20213 }
20214
20215 // The initializer of a constexpr variable or of the first declaration of a
20216 // static data member is not syntactically a constant evaluated constant,
20217 // but nonetheless is always required to be a constant expression, so we
20218 // can skip diagnosing.
20219 // FIXME: Using the mangling context here is a hack.
20220 if (auto *VD = dyn_cast_or_null<VarDecl>(
20221 ExprEvalContexts.back().ManglingContextDecl)) {
20222 if (VD->isConstexpr() ||
20223 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20224 return false;
20225 // FIXME: For any other kind of variable, we should build a CFG for its
20226 // initializer and check whether the context in question is reachable.
20227 }
20228
20229 Diag(Loc, PD);
20230 return true;
20231}
20232
20233/// Emit a diagnostic that describes an effect on the run-time behavior
20234/// of the program being compiled.
20235///
20236/// This routine emits the given diagnostic when the code currently being
20237/// type-checked is "potentially evaluated", meaning that there is a
20238/// possibility that the code will actually be executable. Code in sizeof()
20239/// expressions, code used only during overload resolution, etc., are not
20240/// potentially evaluated. This routine will suppress such diagnostics or,
20241/// in the absolutely nutty case of potentially potentially evaluated
20242/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20243/// later.
20244///
20245/// This routine should be used for all diagnostics that describe the run-time
20246/// behavior of a program, such as passing a non-POD value through an ellipsis.
20247/// Failure to do so will likely result in spurious diagnostics or failures
20248/// during overload resolution or within sizeof/alignof/typeof/typeid.
20250 const PartialDiagnostic &PD) {
20251
20252 if (ExprEvalContexts.back().isDiscardedStatementContext())
20253 return false;
20254
20255 switch (ExprEvalContexts.back().Context) {
20260 // The argument will never be evaluated, so don't complain.
20261 break;
20262
20265 // Relevant diagnostics should be produced by constant evaluation.
20266 break;
20267
20270 return DiagIfReachable(Loc, Stmts, PD);
20271 }
20272
20273 return false;
20274}
20275
20277 const PartialDiagnostic &PD) {
20278 return DiagRuntimeBehavior(
20279 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
20280 PD);
20281}
20282
20284 CallExpr *CE, FunctionDecl *FD) {
20285 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20286 return false;
20287
20288 // If we're inside a decltype's expression, don't check for a valid return
20289 // type or construct temporaries until we know whether this is the last call.
20290 if (ExprEvalContexts.back().ExprContext ==
20292 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20293 return false;
20294 }
20295
20296 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20297 FunctionDecl *FD;
20298 CallExpr *CE;
20299
20300 public:
20301 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20302 : FD(FD), CE(CE) { }
20303
20304 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20305 if (!FD) {
20306 S.Diag(Loc, diag::err_call_incomplete_return)
20307 << T << CE->getSourceRange();
20308 return;
20309 }
20310
20311 S.Diag(Loc, diag::err_call_function_incomplete_return)
20312 << CE->getSourceRange() << FD << T;
20313 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20314 << FD->getDeclName();
20315 }
20316 } Diagnoser(FD, CE);
20317
20318 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20319 return true;
20320
20321 return false;
20322}
20323
20324// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20325// will prevent this condition from triggering, which is what we want.
20328
20329 unsigned diagnostic = diag::warn_condition_is_assignment;
20330 bool IsOrAssign = false;
20331
20332 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20333 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20334 return;
20335
20336 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20337
20338 // Greylist some idioms by putting them into a warning subcategory.
20339 if (ObjCMessageExpr *ME
20340 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20341 Selector Sel = ME->getSelector();
20342
20343 // self = [<foo> init...]
20344 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20345 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20346
20347 // <foo> = [<bar> nextObject]
20348 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20349 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20350 }
20351
20352 Loc = Op->getOperatorLoc();
20353 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20354 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20355 return;
20356
20357 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20358 Loc = Op->getOperatorLoc();
20359 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20360 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20361 else {
20362 // Not an assignment.
20363 return;
20364 }
20365
20366 Diag(Loc, diagnostic) << E->getSourceRange();
20367
20370 Diag(Loc, diag::note_condition_assign_silence)
20372 << FixItHint::CreateInsertion(Close, ")");
20373
20374 if (IsOrAssign)
20375 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20377 else
20378 Diag(Loc, diag::note_condition_assign_to_comparison)
20380}
20381
20383 // Don't warn if the parens came from a macro.
20384 SourceLocation parenLoc = ParenE->getBeginLoc();
20385 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20386 return;
20387 // Don't warn for dependent expressions.
20388 if (ParenE->isTypeDependent())
20389 return;
20390
20391 Expr *E = ParenE->IgnoreParens();
20392 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
20393 return;
20394
20395 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20396 if (opE->getOpcode() == BO_EQ &&
20397 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20398 == Expr::MLV_Valid) {
20399 SourceLocation Loc = opE->getOperatorLoc();
20400
20401 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20402 SourceRange ParenERange = ParenE->getSourceRange();
20403 Diag(Loc, diag::note_equality_comparison_silence)
20404 << FixItHint::CreateRemoval(ParenERange.getBegin())
20405 << FixItHint::CreateRemoval(ParenERange.getEnd());
20406 Diag(Loc, diag::note_equality_comparison_to_assign)
20408 }
20409}
20410
20412 bool IsConstexpr) {
20414 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20416
20418 if (result.isInvalid()) return ExprError();
20419 E = result.get();
20420
20421 if (!E->isTypeDependent()) {
20422 if (getLangOpts().CPlusPlus)
20423 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20424
20426 if (ERes.isInvalid())
20427 return ExprError();
20428 E = ERes.get();
20429
20430 QualType T = E->getType();
20431 if (!T->isScalarType()) { // C99 6.8.4.1p1
20432 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20433 << T << E->getSourceRange();
20434 return ExprError();
20435 }
20436 CheckBoolLikeConversion(E, Loc);
20437 }
20438
20439 return E;
20440}
20441
20443 Expr *SubExpr, ConditionKind CK,
20444 bool MissingOK) {
20445 // MissingOK indicates whether having no condition expression is valid
20446 // (for loop) or invalid (e.g. while loop).
20447 if (!SubExpr)
20448 return MissingOK ? ConditionResult() : ConditionError();
20449
20450 ExprResult Cond;
20451 switch (CK) {
20453 Cond = CheckBooleanCondition(Loc, SubExpr);
20454 break;
20455
20457 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20458 break;
20459
20461 Cond = CheckSwitchCondition(Loc, SubExpr);
20462 break;
20463 }
20464 if (Cond.isInvalid()) {
20465 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20466 {SubExpr}, PreferredConditionType(CK));
20467 if (!Cond.get())
20468 return ConditionError();
20469 }
20470 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20472 if (!FullExpr.get())
20473 return ConditionError();
20474
20475 return ConditionResult(*this, nullptr, FullExpr,
20477}
20478
20479namespace {
20480 /// A visitor for rebuilding a call to an __unknown_any expression
20481 /// to have an appropriate type.
20482 struct RebuildUnknownAnyFunction
20483 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20484
20485 Sema &S;
20486
20487 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20488
20489 ExprResult VisitStmt(Stmt *S) {
20490 llvm_unreachable("unexpected statement!");
20491 }
20492
20493 ExprResult VisitExpr(Expr *E) {
20494 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20495 << E->getSourceRange();
20496 return ExprError();
20497 }
20498
20499 /// Rebuild an expression which simply semantically wraps another
20500 /// expression which it shares the type and value kind of.
20501 template <class T> ExprResult rebuildSugarExpr(T *E) {
20502 ExprResult SubResult = Visit(E->getSubExpr());
20503 if (SubResult.isInvalid()) return ExprError();
20504
20505 Expr *SubExpr = SubResult.get();
20506 E->setSubExpr(SubExpr);
20507 E->setType(SubExpr->getType());
20508 E->setValueKind(SubExpr->getValueKind());
20509 assert(E->getObjectKind() == OK_Ordinary);
20510 return E;
20511 }
20512
20513 ExprResult VisitParenExpr(ParenExpr *E) {
20514 return rebuildSugarExpr(E);
20515 }
20516
20517 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20518 return rebuildSugarExpr(E);
20519 }
20520
20521 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20522 ExprResult SubResult = Visit(E->getSubExpr());
20523 if (SubResult.isInvalid()) return ExprError();
20524
20525 Expr *SubExpr = SubResult.get();
20526 E->setSubExpr(SubExpr);
20527 E->setType(S.Context.getPointerType(SubExpr->getType()));
20528 assert(E->isPRValue());
20529 assert(E->getObjectKind() == OK_Ordinary);
20530 return E;
20531 }
20532
20533 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20534 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20535
20536 E->setType(VD->getType());
20537
20538 assert(E->isPRValue());
20539 if (S.getLangOpts().CPlusPlus &&
20540 !(isa<CXXMethodDecl>(VD) &&
20541 cast<CXXMethodDecl>(VD)->isInstance()))
20543
20544 return E;
20545 }
20546
20547 ExprResult VisitMemberExpr(MemberExpr *E) {
20548 return resolveDecl(E, E->getMemberDecl());
20549 }
20550
20551 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20552 return resolveDecl(E, E->getDecl());
20553 }
20554 };
20555}
20556
20557/// Given a function expression of unknown-any type, try to rebuild it
20558/// to have a function type.
20560 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20561 if (Result.isInvalid()) return ExprError();
20562 return S.DefaultFunctionArrayConversion(Result.get());
20563}
20564
20565namespace {
20566 /// A visitor for rebuilding an expression of type __unknown_anytype
20567 /// into one which resolves the type directly on the referring
20568 /// expression. Strict preservation of the original source
20569 /// structure is not a goal.
20570 struct RebuildUnknownAnyExpr
20571 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20572
20573 Sema &S;
20574
20575 /// The current destination type.
20576 QualType DestType;
20577
20578 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20579 : S(S), DestType(CastType) {}
20580
20581 ExprResult VisitStmt(Stmt *S) {
20582 llvm_unreachable("unexpected statement!");
20583 }
20584
20585 ExprResult VisitExpr(Expr *E) {
20586 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20587 << E->getSourceRange();
20588 return ExprError();
20589 }
20590
20591 ExprResult VisitCallExpr(CallExpr *E);
20592 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20593
20594 /// Rebuild an expression which simply semantically wraps another
20595 /// expression which it shares the type and value kind of.
20596 template <class T> ExprResult rebuildSugarExpr(T *E) {
20597 ExprResult SubResult = Visit(E->getSubExpr());
20598 if (SubResult.isInvalid()) return ExprError();
20599 Expr *SubExpr = SubResult.get();
20600 E->setSubExpr(SubExpr);
20601 E->setType(SubExpr->getType());
20602 E->setValueKind(SubExpr->getValueKind());
20603 assert(E->getObjectKind() == OK_Ordinary);
20604 return E;
20605 }
20606
20607 ExprResult VisitParenExpr(ParenExpr *E) {
20608 return rebuildSugarExpr(E);
20609 }
20610
20611 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20612 return rebuildSugarExpr(E);
20613 }
20614
20615 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20616 const PointerType *Ptr = DestType->getAs<PointerType>();
20617 if (!Ptr) {
20618 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20619 << E->getSourceRange();
20620 return ExprError();
20621 }
20622
20623 if (isa<CallExpr>(E->getSubExpr())) {
20624 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20625 << E->getSourceRange();
20626 return ExprError();
20627 }
20628
20629 assert(E->isPRValue());
20630 assert(E->getObjectKind() == OK_Ordinary);
20631 E->setType(DestType);
20632
20633 // Build the sub-expression as if it were an object of the pointee type.
20634 DestType = Ptr->getPointeeType();
20635 ExprResult SubResult = Visit(E->getSubExpr());
20636 if (SubResult.isInvalid()) return ExprError();
20637 E->setSubExpr(SubResult.get());
20638 return E;
20639 }
20640
20641 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20642
20643 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20644
20645 ExprResult VisitMemberExpr(MemberExpr *E) {
20646 return resolveDecl(E, E->getMemberDecl());
20647 }
20648
20649 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20650 return resolveDecl(E, E->getDecl());
20651 }
20652 };
20653}
20654
20655/// Rebuilds a call expression which yielded __unknown_anytype.
20656ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20657 Expr *CalleeExpr = E->getCallee();
20658
20659 enum FnKind {
20660 FK_MemberFunction,
20661 FK_FunctionPointer,
20662 FK_BlockPointer
20663 };
20664
20665 FnKind Kind;
20666 QualType CalleeType = CalleeExpr->getType();
20667 if (CalleeType == S.Context.BoundMemberTy) {
20668 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20669 Kind = FK_MemberFunction;
20670 CalleeType = Expr::findBoundMemberType(CalleeExpr);
20671 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20672 CalleeType = Ptr->getPointeeType();
20673 Kind = FK_FunctionPointer;
20674 } else {
20675 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20676 Kind = FK_BlockPointer;
20677 }
20678 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20679
20680 // Verify that this is a legal result type of a function.
20681 if (DestType->isArrayType() || DestType->isFunctionType()) {
20682 unsigned diagID = diag::err_func_returning_array_function;
20683 if (Kind == FK_BlockPointer)
20684 diagID = diag::err_block_returning_array_function;
20685
20686 S.Diag(E->getExprLoc(), diagID)
20687 << DestType->isFunctionType() << DestType;
20688 return ExprError();
20689 }
20690
20691 // Otherwise, go ahead and set DestType as the call's result.
20692 E->setType(DestType.getNonLValueExprType(S.Context));
20694 assert(E->getObjectKind() == OK_Ordinary);
20695
20696 // Rebuild the function type, replacing the result type with DestType.
20697 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20698 if (Proto) {
20699 // __unknown_anytype(...) is a special case used by the debugger when
20700 // it has no idea what a function's signature is.
20701 //
20702 // We want to build this call essentially under the K&R
20703 // unprototyped rules, but making a FunctionNoProtoType in C++
20704 // would foul up all sorts of assumptions. However, we cannot
20705 // simply pass all arguments as variadic arguments, nor can we
20706 // portably just call the function under a non-variadic type; see
20707 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20708 // However, it turns out that in practice it is generally safe to
20709 // call a function declared as "A foo(B,C,D);" under the prototype
20710 // "A foo(B,C,D,...);". The only known exception is with the
20711 // Windows ABI, where any variadic function is implicitly cdecl
20712 // regardless of its normal CC. Therefore we change the parameter
20713 // types to match the types of the arguments.
20714 //
20715 // This is a hack, but it is far superior to moving the
20716 // corresponding target-specific code from IR-gen to Sema/AST.
20717
20718 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20719 SmallVector<QualType, 8> ArgTypes;
20720 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20721 ArgTypes.reserve(E->getNumArgs());
20722 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20723 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20724 }
20725 ParamTypes = ArgTypes;
20726 }
20727 DestType = S.Context.getFunctionType(DestType, ParamTypes,
20728 Proto->getExtProtoInfo());
20729 } else {
20730 DestType = S.Context.getFunctionNoProtoType(DestType,
20731 FnType->getExtInfo());
20732 }
20733
20734 // Rebuild the appropriate pointer-to-function type.
20735 switch (Kind) {
20736 case FK_MemberFunction:
20737 // Nothing to do.
20738 break;
20739
20740 case FK_FunctionPointer:
20741 DestType = S.Context.getPointerType(DestType);
20742 break;
20743
20744 case FK_BlockPointer:
20745 DestType = S.Context.getBlockPointerType(DestType);
20746 break;
20747 }
20748
20749 // Finally, we can recurse.
20750 ExprResult CalleeResult = Visit(CalleeExpr);
20751 if (!CalleeResult.isUsable()) return ExprError();
20752 E->setCallee(CalleeResult.get());
20753
20754 // Bind a temporary if necessary.
20755 return S.MaybeBindToTemporary(E);
20756}
20757
20758ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20759 // Verify that this is a legal result type of a call.
20760 if (DestType->isArrayType() || DestType->isFunctionType()) {
20761 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20762 << DestType->isFunctionType() << DestType;
20763 return ExprError();
20764 }
20765
20766 // Rewrite the method result type if available.
20767 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20768 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20769 Method->setReturnType(DestType);
20770 }
20771
20772 // Change the type of the message.
20773 E->setType(DestType.getNonReferenceType());
20775
20776 return S.MaybeBindToTemporary(E);
20777}
20778
20779ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20780 // The only case we should ever see here is a function-to-pointer decay.
20781 if (E->getCastKind() == CK_FunctionToPointerDecay) {
20782 assert(E->isPRValue());
20783 assert(E->getObjectKind() == OK_Ordinary);
20784
20785 E->setType(DestType);
20786
20787 // Rebuild the sub-expression as the pointee (function) type.
20788 DestType = DestType->castAs<PointerType>()->getPointeeType();
20789
20790 ExprResult Result = Visit(E->getSubExpr());
20791 if (!Result.isUsable()) return ExprError();
20792
20793 E->setSubExpr(Result.get());
20794 return E;
20795 } else if (E->getCastKind() == CK_LValueToRValue) {
20796 assert(E->isPRValue());
20797 assert(E->getObjectKind() == OK_Ordinary);
20798
20799 assert(isa<BlockPointerType>(E->getType()));
20800
20801 E->setType(DestType);
20802
20803 // The sub-expression has to be a lvalue reference, so rebuild it as such.
20804 DestType = S.Context.getLValueReferenceType(DestType);
20805
20806 ExprResult Result = Visit(E->getSubExpr());
20807 if (!Result.isUsable()) return ExprError();
20808
20809 E->setSubExpr(Result.get());
20810 return E;
20811 } else {
20812 llvm_unreachable("Unhandled cast type!");
20813 }
20814}
20815
20816ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20817 ExprValueKind ValueKind = VK_LValue;
20818 QualType Type = DestType;
20819
20820 // We know how to make this work for certain kinds of decls:
20821
20822 // - functions
20823 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20824 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20825 DestType = Ptr->getPointeeType();
20826 ExprResult Result = resolveDecl(E, VD);
20827 if (Result.isInvalid()) return ExprError();
20828 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20829 VK_PRValue);
20830 }
20831
20832 if (!Type->isFunctionType()) {
20833 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20834 << VD << E->getSourceRange();
20835 return ExprError();
20836 }
20837 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20838 // We must match the FunctionDecl's type to the hack introduced in
20839 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20840 // type. See the lengthy commentary in that routine.
20841 QualType FDT = FD->getType();
20842 const FunctionType *FnType = FDT->castAs<FunctionType>();
20843 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20844 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20845 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20846 SourceLocation Loc = FD->getLocation();
20848 S.Context, FD->getDeclContext(), Loc, Loc,
20849 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20851 false /*isInlineSpecified*/, FD->hasPrototype(),
20852 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20853
20854 if (FD->getQualifier())
20855 NewFD->setQualifierInfo(FD->getQualifierLoc());
20856
20858 for (const auto &AI : FT->param_types()) {
20859 ParmVarDecl *Param =
20861 Param->setScopeInfo(0, Params.size());
20862 Params.push_back(Param);
20863 }
20864 NewFD->setParams(Params);
20865 DRE->setDecl(NewFD);
20866 VD = DRE->getDecl();
20867 }
20868 }
20869
20870 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20871 if (MD->isInstance()) {
20872 ValueKind = VK_PRValue;
20874 }
20875
20876 // Function references aren't l-values in C.
20877 if (!S.getLangOpts().CPlusPlus)
20878 ValueKind = VK_PRValue;
20879
20880 // - variables
20881 } else if (isa<VarDecl>(VD)) {
20882 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20883 Type = RefTy->getPointeeType();
20884 } else if (Type->isFunctionType()) {
20885 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20886 << VD << E->getSourceRange();
20887 return ExprError();
20888 }
20889
20890 // - nothing else
20891 } else {
20892 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20893 << VD << E->getSourceRange();
20894 return ExprError();
20895 }
20896
20897 // Modifying the declaration like this is friendly to IR-gen but
20898 // also really dangerous.
20899 VD->setType(DestType);
20900 E->setType(Type);
20901 E->setValueKind(ValueKind);
20902 return E;
20903}
20904
20908 // The type we're casting to must be either void or complete.
20909 if (!CastType->isVoidType() &&
20911 diag::err_typecheck_cast_to_incomplete))
20912 return ExprError();
20913
20914 // Rewrite the casted expression from scratch.
20915 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20916 if (!result.isUsable()) return ExprError();
20917
20918 CastExpr = result.get();
20919 VK = CastExpr->getValueKind();
20920 CastKind = CK_NoOp;
20921
20922 return CastExpr;
20923}
20924
20926 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20927}
20928
20930 Expr *arg, QualType &paramType) {
20931 // If the syntactic form of the argument is not an explicit cast of
20932 // any sort, just do default argument promotion.
20933 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20934 if (!castArg) {
20936 if (result.isInvalid()) return ExprError();
20937 paramType = result.get()->getType();
20938 return result;
20939 }
20940
20941 // Otherwise, use the type that was written in the explicit cast.
20942 assert(!arg->hasPlaceholderType());
20943 paramType = castArg->getTypeAsWritten();
20944
20945 // Copy-initialize a parameter of that type.
20946 InitializedEntity entity =
20948 /*consumed*/ false);
20949 return PerformCopyInitialization(entity, callLoc, arg);
20950}
20951
20953 Expr *orig = E;
20954 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20955 while (true) {
20956 E = E->IgnoreParenImpCasts();
20957 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20958 E = call->getCallee();
20959 diagID = diag::err_uncasted_call_of_unknown_any;
20960 } else {
20961 break;
20962 }
20963 }
20964
20965 SourceLocation loc;
20966 NamedDecl *d;
20967 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20968 loc = ref->getLocation();
20969 d = ref->getDecl();
20970 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20971 loc = mem->getMemberLoc();
20972 d = mem->getMemberDecl();
20973 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20974 diagID = diag::err_uncasted_call_of_unknown_any;
20975 loc = msg->getSelectorStartLoc();
20976 d = msg->getMethodDecl();
20977 if (!d) {
20978 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20979 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20980 << orig->getSourceRange();
20981 return ExprError();
20982 }
20983 } else {
20984 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20985 << E->getSourceRange();
20986 return ExprError();
20987 }
20988
20989 S.Diag(loc, diagID) << d << orig->getSourceRange();
20990
20991 // Never recoverable.
20992 return ExprError();
20993}
20994
20997 // C cannot handle TypoExpr nodes on either side of a binop because it
20998 // doesn't handle dependent types properly, so make sure any TypoExprs have
20999 // been dealt with before checking the operands.
21001 if (!Result.isUsable()) return ExprError();
21002 E = Result.get();
21003 }
21004
21005 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21006 if (!placeholderType) return E;
21007
21008 switch (placeholderType->getKind()) {
21009 case BuiltinType::UnresolvedTemplate: {
21010 auto *ULE = cast<UnresolvedLookupExpr>(E);
21011 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
21012 // There's only one FoundDecl for UnresolvedTemplate type. See
21013 // BuildTemplateIdExpr.
21014 NamedDecl *Temp = *ULE->decls_begin();
21015 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
21016
21017 if (NestedNameSpecifierLoc Loc = ULE->getQualifierLoc(); Loc.hasQualifier())
21018 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21019 << Loc.getNestedNameSpecifier() << NameInfo.getName().getAsString()
21020 << Loc.getSourceRange() << IsTypeAliasTemplateDecl;
21021 else
21022 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21023 << "" << NameInfo.getName().getAsString() << ULE->getSourceRange()
21024 << IsTypeAliasTemplateDecl;
21025 Diag(Temp->getLocation(), diag::note_referenced_type_template)
21026 << IsTypeAliasTemplateDecl;
21027
21028 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
21029 }
21030
21031 // Overloaded expressions.
21032 case BuiltinType::Overload: {
21033 // Try to resolve a single function template specialization.
21034 // This is obligatory.
21037 return Result;
21038
21039 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21040 // leaves Result unchanged on failure.
21041 Result = E;
21043 return Result;
21044
21045 // If that failed, try to recover with a call.
21046 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21047 /*complain*/ true);
21048 return Result;
21049 }
21050
21051 // Bound member functions.
21052 case BuiltinType::BoundMember: {
21053 ExprResult result = E;
21054 const Expr *BME = E->IgnoreParens();
21055 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21056 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21057 if (isa<CXXPseudoDestructorExpr>(BME)) {
21058 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21059 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21060 if (ME->getMemberNameInfo().getName().getNameKind() ==
21062 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21063 }
21064 tryToRecoverWithCall(result, PD,
21065 /*complain*/ true);
21066 return result;
21067 }
21068
21069 // ARC unbridged casts.
21070 case BuiltinType::ARCUnbridgedCast: {
21071 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
21072 ObjC().diagnoseARCUnbridgedCast(realCast);
21073 return realCast;
21074 }
21075
21076 // Expressions of unknown type.
21077 case BuiltinType::UnknownAny:
21078 return diagnoseUnknownAnyExpr(*this, E);
21079
21080 // Pseudo-objects.
21081 case BuiltinType::PseudoObject:
21082 return PseudoObject().checkRValue(E);
21083
21084 case BuiltinType::BuiltinFn: {
21085 // Accept __noop without parens by implicitly converting it to a call expr.
21086 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21087 if (DRE) {
21088 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21089 unsigned BuiltinID = FD->getBuiltinID();
21090 if (BuiltinID == Builtin::BI__noop) {
21091 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21092 CK_BuiltinFnToFnPtr)
21093 .get();
21094 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21097 }
21098
21099 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21100 // Any use of these other than a direct call is ill-formed as of C++20,
21101 // because they are not addressable functions. In earlier language
21102 // modes, warn and force an instantiation of the real body.
21103 Diag(E->getBeginLoc(),
21105 ? diag::err_use_of_unaddressable_function
21106 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21107 if (FD->isImplicitlyInstantiable()) {
21108 // Require a definition here because a normal attempt at
21109 // instantiation for a builtin will be ignored, and we won't try
21110 // again later. We assume that the definition of the template
21111 // precedes this use.
21113 /*Recursive=*/false,
21114 /*DefinitionRequired=*/true,
21115 /*AtEndOfTU=*/false);
21116 }
21117 // Produce a properly-typed reference to the function.
21118 CXXScopeSpec SS;
21119 SS.Adopt(DRE->getQualifierLoc());
21120 TemplateArgumentListInfo TemplateArgs;
21121 DRE->copyTemplateArgumentsInto(TemplateArgs);
21122 return BuildDeclRefExpr(
21123 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21124 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21125 DRE->getTemplateKeywordLoc(),
21126 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21127 }
21128 }
21129
21130 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21131 return ExprError();
21132 }
21133
21134 case BuiltinType::IncompleteMatrixIdx:
21135 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
21136 ->getRowIdx()
21137 ->getBeginLoc(),
21138 diag::err_matrix_incomplete_index);
21139 return ExprError();
21140
21141 // Expressions of unknown type.
21142 case BuiltinType::ArraySection:
21143 Diag(E->getBeginLoc(), diag::err_array_section_use)
21144 << cast<ArraySectionExpr>(E)->isOMPArraySection();
21145 return ExprError();
21146
21147 // Expressions of unknown type.
21148 case BuiltinType::OMPArrayShaping:
21149 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21150
21151 case BuiltinType::OMPIterator:
21152 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21153
21154 // Everything else should be impossible.
21155#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21156 case BuiltinType::Id:
21157#include "clang/Basic/OpenCLImageTypes.def"
21158#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21159 case BuiltinType::Id:
21160#include "clang/Basic/OpenCLExtensionTypes.def"
21161#define SVE_TYPE(Name, Id, SingletonId) \
21162 case BuiltinType::Id:
21163#include "clang/Basic/AArch64SVEACLETypes.def"
21164#define PPC_VECTOR_TYPE(Name, Id, Size) \
21165 case BuiltinType::Id:
21166#include "clang/Basic/PPCTypes.def"
21167#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21168#include "clang/Basic/RISCVVTypes.def"
21169#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21170#include "clang/Basic/WebAssemblyReferenceTypes.def"
21171#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
21172#include "clang/Basic/AMDGPUTypes.def"
21173#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21174#include "clang/Basic/HLSLIntangibleTypes.def"
21175#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21176#define PLACEHOLDER_TYPE(Id, SingletonId)
21177#include "clang/AST/BuiltinTypes.def"
21178 break;
21179 }
21180
21181 llvm_unreachable("invalid placeholder type!");
21182}
21183
21185 if (E->isTypeDependent())
21186 return true;
21189 return false;
21190}
21191
21193 ArrayRef<Expr *> SubExprs, QualType T) {
21194 if (!Context.getLangOpts().RecoveryAST)
21195 return ExprError();
21196
21197 if (isSFINAEContext())
21198 return ExprError();
21199
21200 if (T.isNull() || T->isUndeducedType() ||
21201 !Context.getLangOpts().RecoveryASTType)
21202 // We don't know the concrete type, fallback to dependent type.
21204
21205 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21206}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3460
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:1125
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:9139
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
Definition: SemaExpr.cpp:17761
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:1953
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:15333
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:10023
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:18712
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:10786
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:15082
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
Definition: SemaExpr.cpp:6146
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:10705
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:8710
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:3170
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
Definition: SemaExpr.cpp:8159
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:8365
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:11752
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:10750
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:11702
static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn)
Definition: SemaExpr.cpp:5809
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
Definition: SemaExpr.cpp:2238
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:14558
static void DetectPrecisionLossInComplexDivision(Sema &S, SourceLocation OpLoc, Expr *Operand)
Definition: SemaExpr.cpp:15264
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:18099
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
Definition: SemaExpr.cpp:13308
@ NCCK_Block
Definition: SemaExpr.cpp:13308
@ NCCK_None
Definition: SemaExpr.cpp:13308
@ NCCK_Lambda
Definition: SemaExpr.cpp:13308
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:9912
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:9188
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:6078
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:2648
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(Sema &SemaRef, ValueDecl *D, Expr *E)
Definition: SemaExpr.cpp:19948
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18564
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:16824
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:8614
static Decl * getPredefinedExprDecl(DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
Definition: SemaExpr.cpp:1937
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:16707
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
Definition: SemaExpr.cpp:13883
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
Definition: SemaExpr.cpp:4733
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12164
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
Definition: SemaExpr.cpp:14458
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
Definition: SemaExpr.cpp:4347
static bool ExprLooksBoolean(const Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
Definition: SemaExpr.cpp:8689
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
Definition: SemaExpr.cpp:17948
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:14614
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:10872
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
Definition: SemaExpr.cpp:8002
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19748
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
Definition: SemaExpr.cpp:3195
static bool checkCondition(Sema &S, const Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
Definition: SemaExpr.cpp:7968
static bool checkForArray(const Expr *E)
Definition: SemaExpr.cpp:11794
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
Definition: SemaExpr.cpp:6421
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
Definition: SemaExpr.cpp:13505
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19994
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:9961
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
Definition: SemaExpr.cpp:19716
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:14440
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
Definition: SemaExpr.cpp:17611
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:12039
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:8644
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:14712
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
Definition: SemaExpr.cpp:1324
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
Definition: SemaExpr.cpp:6311
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:9576
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:8283
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
Definition: SemaExpr.cpp:7989
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
Definition: SemaExpr.cpp:10717
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:14697
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
Definition: SemaExpr.cpp:4790
static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8915
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
Definition: SemaExpr.cpp:17653
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:15173
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:2373
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:13988
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:8228
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:8337
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10544
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
Definition: SemaExpr.cpp:11853
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:4224
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
Definition: SemaExpr.cpp:10592
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
Definition: SemaExpr.cpp:3487
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
Definition: SemaExpr.cpp:5768
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:11241
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4131
static Sema::AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
Definition: SemaExpr.cpp:9088
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:1281
static void MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
Definition: SemaExpr.cpp:18391
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:10902
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:13569
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:14090
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:17979
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:11603
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
Definition: SemaExpr.cpp:15230
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
Definition: SemaExpr.cpp:14150
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:1374
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
Definition: SemaExpr.cpp:4804
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:10070
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:18752
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the left hand of a '||' expr.
Definition: SemaExpr.cpp:15137
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:8744
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:18067
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:13380
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
Definition: SemaExpr.cpp:3618
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
Definition: SemaExpr.cpp:13358
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:18508
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
Definition: SemaExpr.cpp:10764
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4176
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:11436
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12082
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:20952
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:1945
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
Definition: SemaExpr.cpp:8403
OriginalExprKind
Definition: SemaExpr.cpp:13499
@ OEK_Variable
Definition: SemaExpr.cpp:13500
@ OEK_LValue
Definition: SemaExpr.cpp:13502
@ OEK_Member
Definition: SemaExpr.cpp:13501
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:18644
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:1231
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
Definition: SemaExpr.cpp:10692
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:11342
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
Definition: SemaExpr.cpp:18467
static FieldDecl * FindFieldDeclInstantiationPattern(const ASTContext &Ctx, FieldDecl *Field)
Definition: SemaExpr.cpp:5577
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
Definition: SemaExpr.cpp:1306
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
Definition: SemaExpr.cpp:10508
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:13295
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:11810
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:18885
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:6380
static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4161
static Sema::AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, SourceLocation Loc)
Definition: SemaExpr.cpp:8936
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4149
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
Definition: SemaExpr.cpp:15158
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
Definition: SemaExpr.cpp:4823
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
Definition: SemaExpr.cpp:10953
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:6338
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
Definition: SemaExpr.cpp:1420
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4206
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
Definition: SemaExpr.cpp:10734
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:8198
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:12000
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
Definition: SemaExpr.cpp:12864
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
Definition: SemaExpr.cpp:8317
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:8629
@ ConstMethod
Definition: SemaExpr.cpp:13371
@ ConstUnknown
Definition: SemaExpr.cpp:13373
@ ConstVariable
Definition: SemaExpr.cpp:13369
@ NestedConstMember
Definition: SemaExpr.cpp:13372
@ ConstMember
Definition: SemaExpr.cpp:13370
@ ConstFunction
Definition: SemaExpr.cpp:13368
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:1125
static std::pair< ExprResult, ExprResult > CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:14745
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:14656
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:20559
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:1200
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
Definition: SemaExpr.cpp:11655
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, QualType ShorterType, QualType LongerType, bool PromotePrecision)
Definition: SemaExpr.cpp:1153
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:6238
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
Definition: SemaExpr.cpp:19919
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind)
Definition: SemaExpr.cpp:1913
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:1467
static QualType handleComplexConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
Definition: SemaExpr.cpp:1176
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:13952
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
Definition: SemaExpr.cpp:18859
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:10682
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
Definition: SemaExpr.cpp:11592
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:14768
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:11642
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:13309
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:8133
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15202
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:15188
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:11632
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
Definition: SemaExpr.cpp:15125
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
Definition: SemaExpr.cpp:4413
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:9982
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18545
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:15512
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
Definition: SemaExpr.cpp:13697
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13104
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:19333
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
Definition: SemaExpr.cpp:18013
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:11235
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:10818
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:7513
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:489
bool hasValue() const
Definition: APValue.h:465
bool isInt() const
Definition: APValue.h:467
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:957
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:2922
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:2258
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:2272
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:2723
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2739
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:2296
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:2469
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2770
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:2489
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:2011
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:2508
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:1927
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:2139
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:2493
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:1593
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3578
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3592
QualType getElementType() const
Definition: Type.h:3590
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:6562
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:2195
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:2148
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:4902
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:2220
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:2157
static bool isBitwiseOp(Opcode Opc)
Definition: Expr.h:4000
A binding in a decomposition declaration.
Definition: DeclCXX.h:4169
A class which contains all the information about a particular captured value.
Definition: Decl.h:4502
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4496
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.cpp:5271
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition: Decl.h:4578
void setBlockMissingReturnType(bool val=true)
Definition: Decl.h:4635
void setIsVariadic(bool value)
Definition: Decl.h:4572
SourceLocation getCaretLocation() const
Definition: Decl.h:4569
void setBody(CompoundStmt *B)
Definition: Decl.h:4576
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:4582
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition: Decl.cpp:5282
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5465
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6414
Pointer to a block type.
Definition: Type.h:3409
This class is used for builtin types like 'int'.
Definition: Type.h:3035
bool isSVEBool() const
Definition: Type.h:3112
Kind getKind() const
Definition: Type.h:3083
bool hasPtrArgsOrResult(unsigned ID) const
Determines whether this builtin has a result or any arguments which are pointer types.
Definition: Builtins.h:210
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:285
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:197
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:183
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:189
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:2592
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2924
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition: DeclCXX.cpp:3063
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2357
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:2856
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2117
bool isVirtual() const
Definition: DeclCXX.h:2172
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2243
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:2432
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:612
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:2037
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:1498
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:3146
QualType getElementType() const
Definition: Type.h:3156
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:4924
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:3616
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3672
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3692
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:301
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition: Expr.cpp:377
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1127
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:349
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4233
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:4254
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:4251
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:1294
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:1375
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1442
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2107
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2236
bool isRequiresExprBody() const
Definition: DeclBase.h:2192
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1347
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1868
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:2012
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1782
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1651
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:2038
bool isFunctionOrMethod() const
Definition: DeclBase.h:2159
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1298
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1417
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:543
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:550
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:487
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:753
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:159
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:572
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:1042
DeclContext * getDeclContext()
Definition: DeclBase.h:451
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:911
bool hasAttr() const
Definition: DeclBase.h:580
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:971
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:790
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:804
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:768
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1904
DeclaratorContext getContext() const
Definition: DeclSpec.h:2076
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2087
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2334
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:943
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:715
Recursive AST visitor that supports extension via dynamic dispatch.
virtual bool VisitStmt(MaybeConst< Stmt > *S)
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:2355
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2369
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:6104
EnumDecl * getDecl() const
Definition: Type.h:6111
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:3123
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:3052
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:3101
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:3096
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3084
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition: Expr.cpp:3105
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:3092
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:3316
@ 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:3593
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:3076
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:3970
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition: Expr.cpp:265
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:276
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:4222
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:4127
Represents difference between two FPOptions values.
Definition: LangOptions.h:981
bool isFPConstrained() const
Definition: LangOptions.h:909
RoundingMode getRoundingMode() const
Definition: LangOptions.h:915
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:3136
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3208
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3264
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:1001
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1080
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:3734
bool isImmediateFunction() const
Definition: Decl.cpp:3296
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3894
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3649
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3752
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:3509
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:4000
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:3159
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition: Decl.cpp:3910
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:4652
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5108
QualType desugar() const
Definition: Type.h:5652
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:5574
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:5388
bool isParamConsumed(unsigned I) const
Definition: Type.h:5588
unsigned getNumParams() const
Definition: Type.h:5361
QualType getParamType(unsigned i) const
Definition: Type.h:5363
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5485
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5372
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5368
ArrayRef< QualType > param_types() const
Definition: Type.h:5517
Declaration of a template function.
Definition: DeclTemplate.h:958
unsigned getNumParams() const
Definition: TypeLoc.h:1532
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1538
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1484
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1541
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1476
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4433
bool getCmseNSCall() const
Definition: Type.h:4483
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4507
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition: Type.h:4361
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4322
ExtInfo getExtInfo() const
Definition: Type.h:4661
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4657
QualType getReturnType() const
Definition: Type.h:4649
bool getCmseNSCallAttr() const
Definition: Type.h:4659
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4673
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:4522
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:2088
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:3335
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:7639
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:979
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:464
FPEvalMethodKind
Possible float expression evaluation method choices.
Definition: LangOptions.h:302
@ FEM_Extended
Use extended type for fp arithmetic.
Definition: LangOptions.h:311
@ FEM_Double
Use the type double for fp arithmetic.
Definition: LangOptions.h:309
@ 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:316
@ FEM_Source
Use the declared type for fp arithmetic.
Definition: LangOptions.h:307
@ 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:502
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:537
bool isSubscriptPointerArithmetic() const
Definition: LangOptions.h:670
bool isSignedOverflowDefined() const
Definition: LangOptions.h:666
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:4389
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:4197
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:4211
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:1768
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:641
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:7530
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:7586
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:7705
Represents a class type in Objective C.
Definition: Type.h:7332
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:1671
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:1021
@ CSK_Normal
Normal lookup.
Definition: Overload.h:1025
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1198
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:4774
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:2927
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:2918
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3019
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3199
QualType getPointeeType() const
Definition: Type.h:3209
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition: Expr.cpp:637
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition: Expr.cpp:677
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:8021
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:8026
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:8084
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3519
@ DK_nontrivial_c_struct
Definition: Type.h:1524
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2865
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:7937
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:8063
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:8078
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7977
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:2647
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:8140
QualType getCanonicalType() const
Definition: Type.h:7989
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:8031
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2883
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:8147
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:8010
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:8058
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:7994
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:2639
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:8120
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7969
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:8072
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:4162
field_range fields() const
Definition: Decl.h:4376
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6078
RecordDecl * getDecl() const
Definition: Type.h:6088
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition: Expr.cpp:5227
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:3440
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:2709
void emitLogicalOperatorFixIt(Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Definition: SemaHLSL.cpp:891
QualType handleVectorBinOpConversion(ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Definition: SemaHLSL.cpp:824
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:8062
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:12155
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7233
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T)
Definition: SemaExpr.cpp:17165
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:17171
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:466
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:14579
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:6396
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition: Sema.h:7815
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:13177
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:734
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:15845
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:7865
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15522
bool isAlwaysConstantEvaluatedContext() const
Definition: Sema.h:7783
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:870
bool isAttrContext() const
Definition: Sema.h:6473
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Definition: SemaDecl.cpp:15174
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:7858
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9004
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition: Sema.h:9043
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:9012
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:19678
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13182
VariadicCallType
Definition: Sema.h:2317
@ VariadicDoesNotApply
Definition: Sema.h:2322
@ VariadicFunction
Definition: Sema.h:2318
@ VariadicMethod
Definition: Sema.h:2320
@ VariadicConstructor
Definition: Sema.h:2321
@ VariadicBlock
Definition: Sema.h:2319
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:2465
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:7054
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:3641
@ NTCUC_Assignment
Definition: Sema.h:3639
@ NTCUC_FunctionReturn
Definition: Sema.h:3631
@ NTCUC_LValueToRValueVolatile
Definition: Sema.h:3645
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:7558
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:2351
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition: Sema.h:1128
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:15864
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:17483
void ActOnStmtExprError()
Definition: SemaExpr.cpp:15870
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:20195
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:1570
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
Definition: SemaExpr.cpp:12191
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:16446
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition: Sema.h:858
SemaCUDA & CUDA()
Definition: Sema.h:1073
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17418
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:20411
ConditionKind
Definition: Sema.h:7355
@ 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:2689
bool needsRebuildOfDefaultArgOrInit() const
Definition: Sema.h:7803
SourceLocation LocationOfExcessPrecisionNotSatisfied
Definition: Sema.h:7945
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:851
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:2293
Preprocessor & getPreprocessor() const
Definition: Sema.h:533
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition: Sema.h:6451
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2162
QualType GetSignedSizelessVectorType(QualType V)
Definition: SemaExpr.cpp:12750
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:7934
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3551
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition: Sema.h:7846
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:18461
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:17176
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
Definition: SemaExpr.cpp:6696
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:10162
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:1667
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types? I.e.
Definition: SemaExpr.cpp:7532
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:15883
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:16526
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition: Sema.h:6463
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:1570
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:831
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
ExprResult CheckUnevaluatedOperand(Expr *E)
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
Definition: SemaExpr.cpp:1056
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:13903
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Definition: SemaExpr.cpp:5012
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
std::vector< Token > ExpandFunctionLocalPredefinedMacros(ArrayRef< Token > Toks)
Definition: SemaExpr.cpp:2012
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
Definition: SemaExpr.cpp:7642
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:14183
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15161
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:1120
ASTContext & Context
Definition: Sema.h:911
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:7770
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
Definition: SemaCast.cpp:2704
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12986
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:9852
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:20206
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:11528
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool HasMatchedPackOnParmToNonPackOnArg=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:531
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:7907
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:21184
SemaObjC & ObjC()
Definition: Sema.h:1113
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
Definition: SemaExpr.cpp:13021
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:2671
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:7247
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1499
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19691
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:752
bool isImmediateFunctionContext() const
Definition: Sema.h:7795
ASTContext & getASTContext() const
Definition: Sema.h:534
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:15801
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:18961
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:19939
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
Definition: SemaExpr.cpp:15319
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:17851
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9595
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:692
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition: SemaExpr.cpp:881
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
Definition: SemaExpr.cpp:3499
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
Definition: SemaExpr.cpp:6213
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3114
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:7068
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:15851
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:5609
@ None
This is not a defaultable comparison operator.
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:7923
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:13067
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:819
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1575
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2217
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:16139
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:1684
AssumedTemplateKind
Definition: Sema.h:11129
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
Definition: SemaExpr.cpp:1982
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:674
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:7830
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:529
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition: Sema.h:7928
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20442
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:82
@ UPPC_Block
Block expression.
Definition: Sema.h:14008
const LangOptions & getLangOpts() const
Definition: Sema.h:527
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:12218
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:7306
SemaOpenACC & OpenACC()
Definition: Sema.h:1118
ReuseLambdaContextDecl_t
Definition: Sema.h:6535
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:6612
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void MarkExpressionAsImmediateEscalating(Expr *E)
Definition: SemaExpr.cpp:17514
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
Definition: SemaExpr.cpp:2265
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:20080
Preprocessor & PP
Definition: Sema.h:910
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:10963
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5724
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:6489
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
Definition: SemaExpr.cpp:14155
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
Definition: SemaExpr.cpp:16807
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
Definition: SemaExpr.cpp:4725
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:1981
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
Definition: SemaExpr.cpp:7547
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:909
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
Definition: SemaExpr.cpp:15953
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2407
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:6746
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17535
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:7602
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:6040
SemaHLSL & HLSL()
Definition: Sema.h:1078
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:17499
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition: Sema.h:15204
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:20090
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:9876
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:6484
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:6066
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1582
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:9585
void checkEnumArithmeticConversions(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:1506
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:13578
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:950
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
Definition: SemaExpr.cpp:15764
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:784
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:3355
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:942
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:3651
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
Definition: SemaExpr.cpp:10430
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:9647
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:1736
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:6481
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:2145
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:3202
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition: Sema.h:7799
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
Definition: SemaExpr.cpp:7293
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:1652
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:16315
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7683
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2362
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1046
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:7585
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:20905
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:12179
@ VAK_Invalid
Definition: Sema.h:7549
@ VAK_Valid
Definition: Sema.h:7545
@ VAK_ValidInCXX11
Definition: Sema.h:7546
@ VAK_MSVCUndefined
Definition: Sema.h:7548
@ VAK_Undefined
Definition: Sema.h:7547
SemaOpenCL & OpenCL()
Definition: Sema.h:1123
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5826
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:13587
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:16689
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:7929
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:20141
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:7791
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1550
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:7594
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition: Sema.h:7638
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition: Sema.h:7604
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition: Sema.h:7662
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition: Sema.h:7667
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition: Sema.h:7654
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:7633
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:7612
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition: Sema.h:7671
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:7596
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition: Sema.h:7623
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:7675
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition: Sema.h:7608
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition: Sema.h:7617
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:7629
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition: Sema.h:7650
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition: Sema.h:7644
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition: Sema.h:7600
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition: Sema.h:7658
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:8470
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition: Sema.h:7403
@ ACK_Arithmetic
An arithmetic operation.
Definition: Sema.h:7405
@ ACK_CompAssign
A compound assignment expression.
Definition: Sema.h:7413
@ ACK_BitwiseOp
A bitwise operation.
Definition: Sema.h:7407
@ ACK_Conditional
A conditional (?:) operator.
Definition: Sema.h:7411
@ ACK_Comparison
A comparison.
Definition: Sema.h:7409
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20039
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:2909
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4122
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16774
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition: Sema.h:6293
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20995
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17398
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:13534
SourceManager & getSourceManager() const
Definition: Sema.h:532
TryCaptureKind
Definition: Sema.h:6597
@ TryCapture_Implicit
Definition: Sema.h:6598
@ TryCapture_ExplicitByRef
Definition: Sema.h:6600
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
Definition: SemaExpr.cpp:6724
bool CheckVecStepExpr(Expr *E)
Definition: SemaExpr.cpp:4403
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:8795
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:12762
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide)
Definition: SemaExpr.cpp:10605
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
Definition: SemaExpr.cpp:19655
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13742
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:3657
@ NTCUK_Copy
Definition: Sema.h:3658
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition: Sema.h:7944
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20276
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5501
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7577
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:7614
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition: Sema.cpp:2193
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:6291
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:8305
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:2061
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14989
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:15295
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:7716
@ CTK_ErrorRecovery
Definition: Sema.h:9398
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2347
bool isConstantEvaluatedContext() const
Definition: Sema.h:2153
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:3095
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12564
ASTConsumer & Consumer
Definition: Sema.h:912
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:4230
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:6488
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:947
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:13570
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5134
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3547
ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, StringLiteral *BinaryData)
Definition: SemaExpr.cpp:16815
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
Definition: SemaExpr.cpp:12707
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:8422
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition: Sema.h:6235
@ 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:6717
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
Definition: SemaExpr.cpp:4630
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5705
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:20283
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
Definition: SemaExpr.cpp:4240
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16519
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
Definition: SemaType.cpp:5818
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9122
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:874
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:20925
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:19287
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:7751
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:7781
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr)
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17928
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:19279
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7931
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1310
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
Definition: SemaExpr.cpp:7663
SourceManager & SourceMgr
Definition: Sema.h:914
@ TemplateNameIsRequired
Definition: Sema.h:11106
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
Definition: SemaExpr.cpp:4717
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
Definition: SemaExpr.cpp:7824
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
Definition: SemaExpr.cpp:781
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:2406
DiagnosticsEngine & Diags
Definition: Sema.h:913
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:528
FPOptions CurFPFeatures
Definition: Sema.h:907
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:693
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:7600
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9773
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
Definition: SemaExpr.cpp:3611
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5595
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
Definition: SemaExpr.cpp:20326
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:1317
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13118
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:6070
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:15878
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:1011
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
Definition: SemaExpr.cpp:6088
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12823
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8898
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:13110
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:16325
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:564
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
Definition: SemaExpr.cpp:20061
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:16843
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:18109
ExprResult ActOnStmtExprResult(ExprResult E)
Definition: SemaExpr.cpp:15922
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4770
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:5967
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
Definition: SemaLambda.cpp:284
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
Definition: SemaExpr.cpp:20382
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1964
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:21192
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15369
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3685
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
Definition: SemaExpr.cpp:2982
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7268
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:16177
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
Definition: SemaExpr.cpp:4843
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:14792
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9173
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:6451
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:4700
QualType PreferredConditionType(ConditionKind K) const
Definition: Sema.h:7501
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:9057
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition: Sema.h:9063
@ LOLR_Error
The lookup resulted in an error.
Definition: Sema.h:9055
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition: Sema.h:9060
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition: Sema.h:9071
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition: Sema.h:9067
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:16206
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:10644
@ 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:13566
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:2752
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:15820
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:13362
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:11086
static ConditionResult ConditionError()
Definition: Sema.h:7342
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ActOnConvertVectorExpr - create a new convert-vector expression from the provided arguments.
Definition: SemaExpr.cpp:6738
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:20929
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:5827
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:16120
SemaPseudoObject & PseudoObject()
Definition: Sema.h:1138
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2338
FullExprArg MakeFullExpr(Expr *Arg)
Definition: Sema.h:7298
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:2717
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:17936
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7200
bool isCheckingDefaultArgumentOrInitializer() const
Definition: Sema.h:7807
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:5346
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:8282
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:5020
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:186
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:358
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:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:346
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h: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:1193
StringRef getString() const
Definition: Expr.h:1855
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3681
bool isUnion() const
Definition: Decl.h:3784
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3802
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:1263
@ 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:1584
virtual bool supportsExtendIntArgs() const
Whether the option -fextend-arguments={32,64} is supported on the target.
Definition: TargetInfo.h:1677
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:1043
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1334
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:1494
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:398
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:3384
const Type * getTypeForDecl() const
Definition: Decl.h:3409
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3412
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:2716
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7908
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:7919
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:540
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:8581
bool isBlockPointerType() const
Definition: Type.h:8206
bool isVoidType() const
Definition: Type.h:8516
bool isBooleanType() const
Definition: Type.h:8648
bool isFunctionReferenceType() const
Definition: Type.h:8239
bool isObjCBuiltinType() const
Definition: Type.h:8385
bool isMFloat8Type() const
Definition: Type.h:8541
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:8698
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:773
bool isIncompleteArrayType() const
Definition: Type.h:8272
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:8492
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:8678
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:8264
bool isCharType() const
Definition: Type.cpp:2123
bool isFunctionPointerType() const
Definition: Type.h:8232
bool isArithmeticType() const
Definition: Type.cpp:2315
bool isConstantMatrixType() const
Definition: Type.h:8326
bool isPointerType() const
Definition: Type.h:8192
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8560
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:8810
bool isReferenceType() const
Definition: Type.h:8210
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:8601
bool isEnumeralType() const
Definition: Type.h:8296
bool isScalarType() const
Definition: Type.h:8619
bool isVariableArrayType() const
Definition: Type.h:8276
bool isSizelessBuiltinType() const
Definition: Type.cpp:2475
bool isClkEventT() const
Definition: Type.h:8407
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2552
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2092
bool isObjCQualifiedIdType() const
Definition: Type.h:8355
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:8635
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:8308
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:8312
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2591
bool isImageType() const
Definition: Type.h:8419
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:8510
bool isPipeType() const
Definition: Type.h:8426
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2715
bool isBitIntType() const
Definition: Type.h:8430
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:8485
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:8288
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2707
bool isAnyComplexType() const
Definition: Type.h:8300
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8573
bool isHalfType() const
Definition: Type.h:8520
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:8589
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:8498
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:8411
bool isMemberPointerType() const
Definition: Type.h:8246
bool isAtomicType() const
Definition: Type.h:8347
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:8661
bool isObjCIdType() const
Definition: Type.h:8367
bool isMatrixType() const
Definition: Type.h:8322
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2725
bool isComplexIntegerType() const
Definition: Type.cpp:716
bool isUnscopedEnumerationType() const
Definition: Type.cpp:2116
bool isObjCObjectType() const
Definition: Type.h:8338
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:4956
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8796
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:5046
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8654
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:8188
bool isObjCObjectPointerType() const
Definition: Type.h:8334
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:8250
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:8615
bool isVectorType() const
Definition: Type.h:8304
bool isObjCQualifiedClassType() const
Definition: Type.h:8361
bool isObjCClassType() const
Definition: Type.h:8373
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2300
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2539
ScalarTypeKind
Definition: Type.h:2680
@ STK_FloatingComplex
Definition: Type.h:2689
@ STK_Floating
Definition: Type.h:2687
@ STK_BlockPointer
Definition: Type.h:2682
@ STK_Bool
Definition: Type.h:2685
@ STK_ObjCObjectPointer
Definition: Type.h:2683
@ STK_FixedPoint
Definition: Type.h:2690
@ STK_IntegralComplex
Definition: Type.h:2688
@ STK_CPointer
Definition: Type.h:2681
@ STK_Integral
Definition: Type.h:2686
@ STK_MemberPointer
Definition: Type.h:2684
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:8200
bool isRealType() const
Definition: Type.cpp:2306
TypeClass getTypeClass() const
Definition: Type.h:2341
bool isSubscriptableVectorType() const
Definition: Type.h:8318
bool isSamplerT() const
Definition: Type.h:8399
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8741
bool isNullPtrType() const
Definition: Type.h:8553
bool isRecordType() const
Definition: Type.h:8292
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4761
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:1431
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:4959
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:4446
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:3459
QualType getType() const
Definition: Value.cpp:234
Represents a variable declaration or definition.
Definition: Decl.h:886
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:1526
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1238
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1181
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:2879
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1499
const Expr * getInit() const
Definition: Decl.h:1323
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1172
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1139
@ TLS_None
Not a TLS variable.
Definition: Decl.h:906
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1250
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:2772
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1217
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:2751
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2870
Declaration of a variable template.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3809
Expr * getSizeExpr() const
Definition: Type.h:3828
Represents a GCC generic vector type.
Definition: Type.h:4035
unsigned getNumElements() const
Definition: Type.h:4050
VectorKind getVectorKind() const
Definition: Type.h:4055
QualType getElementType() const
Definition: Type.h:4049
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
@ CPlusPlus26
Definition: LangStandard.h:61
@ 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:78
CUDAFunctionTarget
Definition: Cuda.h:147
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:102
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:82
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:28
@ 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:212
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:92
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:60
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition: Specifiers.h:173
@ NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition: Specifiers.h:183
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:177
@ NOUR_None
This is an odr-use.
Definition: Specifiers.h:175
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition: Specifiers.h:180
#define false
Definition: stdbool.h:26
ExprResult TransformSourceLocExpr(SourceLocExpr *E)
Definition: SemaExpr.cpp:5479
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
Definition: SemaExpr.cpp:5476
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
Definition: SemaExpr.cpp:5461
ExprResult TransformBlockExpr(BlockExpr *E)
Definition: SemaExpr.cpp:5471
ExprResult TransformLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5470
bool VisitSourceLocExpr(SourceLocExpr *E) override
Definition: SemaExpr.cpp:5435
bool VisitCXXConstructExpr(CXXConstructExpr *E) override
Definition: SemaExpr.cpp:5425
bool VisitCallExpr(CallExpr *E) override
Definition: SemaExpr.cpp:5419
const ASTContext & Context
Definition: SemaExpr.cpp:5412
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override
Definition: SemaExpr.cpp:5454
bool VisitLambdaExpr(LambdaExpr *E) override
Definition: SemaExpr.cpp:5446
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override
Definition: SemaExpr.cpp:5450
ImmediateCallVisitor(const ASTContext &Ctx)
Definition: SemaExpr.cpp:5413
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:5193
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5194
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:12709
Data structure used to record current or nested expression evaluation contexts.
Definition: Sema.h:6297
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition: Sema.h:6331
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition: Sema.h:6377
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition: Sema.h:6336
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:6344
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition: Sema.h:6340
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition: Sema.h:6350
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:6316
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:6354
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition: Sema.h:6302
unsigned NumTypos
The number of typos encountered during this expression evaluation context (i.e.
Definition: Sema.h:6310
ExpressionEvaluationContext Context
The expression evaluation context.
Definition: Sema.h:6299
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition: Sema.h:6306
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7872
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
uint64_t Width
Definition: ASTContext.h:159
Describes an entity that is being assigned.