clang 20.0.0git
SemaExpr.cpp
Go to the documentation of this file.
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for expressions.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
14#include "TreeTransform.h"
15#include "UsedDeclVisitor.h"
18#include "clang/AST/ASTLambda.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclObjC.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
28#include "clang/AST/ExprObjC.h"
31#include "clang/AST/Type.h"
32#include "clang/AST/TypeLoc.h"
43#include "clang/Sema/DeclSpec.h"
48#include "clang/Sema/Lookup.h"
49#include "clang/Sema/Overload.h"
51#include "clang/Sema/Scope.h"
53#include "clang/Sema/SemaCUDA.h"
55#include "clang/Sema/SemaHLSL.h"
57#include "clang/Sema/SemaObjC.h"
60#include "clang/Sema/Template.h"
61#include "llvm/ADT/STLExtras.h"
62#include "llvm/ADT/STLForwardCompat.h"
63#include "llvm/ADT/StringExtras.h"
64#include "llvm/Support/ConvertUTF.h"
65#include "llvm/Support/SaveAndRestore.h"
66#include "llvm/Support/TimeProfiler.h"
67#include "llvm/Support/TypeSize.h"
68#include <optional>
69
70using namespace clang;
71using namespace sema;
72
73bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
74 // See if this is an auto-typed variable whose initializer we are parsing.
75 if (ParsingInitForAutoVars.count(D))
76 return false;
77
78 // See if this is a deleted function.
79 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
80 if (FD->isDeleted())
81 return false;
82
83 // If the function has a deduced return type, and we can't deduce it,
84 // then we can't use it either.
85 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
86 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
87 return false;
88
89 // See if this is an aligned allocation/deallocation function that is
90 // unavailable.
91 if (TreatUnavailableAsInvalid &&
93 return false;
94 }
95
96 // See if this function is unavailable.
97 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
98 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
99 return false;
100
101 if (isa<UnresolvedUsingIfExistsDecl>(D))
102 return false;
103
104 return true;
105}
106
108 // Warn if this is used but marked unused.
109 if (const auto *A = D->getAttr<UnusedAttr>()) {
110 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
111 // should diagnose them.
112 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
113 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
114 const Decl *DC = cast_or_null<Decl>(S.ObjC().getCurObjCLexicalContext());
115 if (DC && !DC->hasAttr<UnusedAttr>())
116 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
117 }
118 }
119}
120
122 assert(Decl && Decl->isDeleted());
123
124 if (Decl->isDefaulted()) {
125 // If the method was explicitly defaulted, point at that declaration.
126 if (!Decl->isImplicit())
127 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
128
129 // Try to diagnose why this special member function was implicitly
130 // deleted. This might fail, if that reason no longer applies.
132 return;
133 }
134
135 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
136 if (Ctor && Ctor->isInheritingConstructor())
138
139 Diag(Decl->getLocation(), diag::note_availability_specified_here)
140 << Decl << 1;
141}
142
143/// Determine whether a FunctionDecl was ever declared with an
144/// explicit storage class.
146 for (auto *I : D->redecls()) {
147 if (I->getStorageClass() != SC_None)
148 return true;
149 }
150 return false;
151}
152
153/// Check whether we're in an extern inline function and referring to a
154/// variable or function with internal linkage (C11 6.7.4p3).
155///
156/// This is only a warning because we used to silently accept this code, but
157/// in many cases it will not behave correctly. This is not enabled in C++ mode
158/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
159/// and so while there may still be user mistakes, most of the time we can't
160/// prove that there are errors.
162 const NamedDecl *D,
164 // This is disabled under C++; there are too many ways for this to fire in
165 // contexts where the warning is a false positive, or where it is technically
166 // correct but benign.
167 if (S.getLangOpts().CPlusPlus)
168 return;
169
170 // Check if this is an inlined function or method.
171 FunctionDecl *Current = S.getCurFunctionDecl();
172 if (!Current)
173 return;
174 if (!Current->isInlined())
175 return;
176 if (!Current->isExternallyVisible())
177 return;
178
179 // Check if the decl has internal linkage.
180 if (D->getFormalLinkage() != Linkage::Internal)
181 return;
182
183 // Downgrade from ExtWarn to Extension if
184 // (1) the supposedly external inline function is in the main file,
185 // and probably won't be included anywhere else.
186 // (2) the thing we're referencing is a pure function.
187 // (3) the thing we're referencing is another inline function.
188 // This last can give us false negatives, but it's better than warning on
189 // wrappers for simple C library functions.
190 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
191 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
192 if (!DowngradeWarning && UsedFn)
193 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
194
195 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
196 : diag::ext_internal_in_extern_inline)
197 << /*IsVar=*/!UsedFn << D;
198
200
201 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
202 << D;
203}
204
206 const FunctionDecl *First = Cur->getFirstDecl();
207
208 // Suggest "static" on the function, if possible.
210 SourceLocation DeclBegin = First->getSourceRange().getBegin();
211 Diag(DeclBegin, diag::note_convert_inline_to_static)
212 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
213 }
214}
215
217 const ObjCInterfaceDecl *UnknownObjCClass,
218 bool ObjCPropertyAccess,
219 bool AvoidPartialAvailabilityChecks,
220 ObjCInterfaceDecl *ClassReceiver,
221 bool SkipTrailingRequiresClause) {
222 SourceLocation Loc = Locs.front();
223 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
224 // If there were any diagnostics suppressed by template argument deduction,
225 // emit them now.
226 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
227 if (Pos != SuppressedDiagnostics.end()) {
228 for (const PartialDiagnosticAt &Suppressed : Pos->second)
229 Diag(Suppressed.first, Suppressed.second);
230
231 // Clear out the list of suppressed diagnostics, so that we don't emit
232 // them again for this specialization. However, we don't obsolete this
233 // entry from the table, because we want to avoid ever emitting these
234 // diagnostics again.
235 Pos->second.clear();
236 }
237
238 // C++ [basic.start.main]p3:
239 // The function 'main' shall not be used within a program.
240 if (cast<FunctionDecl>(D)->isMain())
241 Diag(Loc, diag::ext_main_used);
242
243 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
244 }
245
246 // See if this is an auto-typed variable whose initializer we are parsing.
247 if (ParsingInitForAutoVars.count(D)) {
248 if (isa<BindingDecl>(D)) {
249 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
250 << D->getDeclName();
251 } else {
252 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
253 << D->getDeclName() << cast<VarDecl>(D)->getType();
254 }
255 return true;
256 }
257
258 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
259 // See if this is a deleted function.
260 if (FD->isDeleted()) {
261 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
262 if (Ctor && Ctor->isInheritingConstructor())
263 Diag(Loc, diag::err_deleted_inherited_ctor_use)
264 << Ctor->getParent()
265 << Ctor->getInheritedConstructor().getConstructor()->getParent();
266 else {
267 StringLiteral *Msg = FD->getDeletedMessage();
268 Diag(Loc, diag::err_deleted_function_use)
269 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
270 }
272 return true;
273 }
274
275 // [expr.prim.id]p4
276 // A program that refers explicitly or implicitly to a function with a
277 // trailing requires-clause whose constraint-expression is not satisfied,
278 // other than to declare it, is ill-formed. [...]
279 //
280 // See if this is a function with constraints that need to be satisfied.
281 // Check this before deducing the return type, as it might instantiate the
282 // definition.
283 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
284 ConstraintSatisfaction Satisfaction;
285 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
286 /*ForOverloadResolution*/ true))
287 // A diagnostic will have already been generated (non-constant
288 // constraint expression, for example)
289 return true;
290 if (!Satisfaction.IsSatisfied) {
291 Diag(Loc,
292 diag::err_reference_to_function_with_unsatisfied_constraints)
293 << D;
294 DiagnoseUnsatisfiedConstraint(Satisfaction);
295 return true;
296 }
297 }
298
299 // If the function has a deduced return type, and we can't deduce it,
300 // then we can't use it either.
301 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
303 return true;
304
305 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
306 return true;
307
308 }
309
310 if (auto *Concept = dyn_cast<ConceptDecl>(D);
312 return true;
313
314 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
315 // Lambdas are only default-constructible or assignable in C++2a onwards.
316 if (MD->getParent()->isLambda() &&
317 ((isa<CXXConstructorDecl>(MD) &&
318 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
319 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
320 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
321 << !isa<CXXConstructorDecl>(MD);
322 }
323 }
324
325 auto getReferencedObjCProp = [](const NamedDecl *D) ->
326 const ObjCPropertyDecl * {
327 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
328 return MD->findPropertyDecl();
329 return nullptr;
330 };
331 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
333 return true;
335 return true;
336 }
337
338 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
339 // Only the variables omp_in and omp_out are allowed in the combiner.
340 // Only the variables omp_priv and omp_orig are allowed in the
341 // initializer-clause.
342 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
343 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
344 isa<VarDecl>(D)) {
345 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
347 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
348 return true;
349 }
350
351 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
352 // List-items in map clauses on this construct may only refer to the declared
353 // variable var and entities that could be referenced by a procedure defined
354 // at the same location.
355 // [OpenMP 5.2] Also allow iterator declared variables.
356 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
357 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
358 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
360 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
361 return true;
362 }
363
364 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
365 Diag(Loc, diag::err_use_of_empty_using_if_exists);
366 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
367 return true;
368 }
369
370 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
371 AvoidPartialAvailabilityChecks, ClassReceiver);
372
373 DiagnoseUnusedOfDecl(*this, D, Loc);
374
376
377 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
378 if (getLangOpts().getFPEvalMethod() !=
381 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
382 Diag(D->getLocation(),
383 diag::err_type_available_only_in_default_eval_method)
384 << D->getName();
385 }
386
387 if (auto *VD = dyn_cast<ValueDecl>(D))
388 checkTypeSupport(VD->getType(), Loc, VD);
389
390 if (LangOpts.SYCLIsDevice ||
391 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
393 if (const auto *VD = dyn_cast<VarDecl>(D))
394 if (VD->getTLSKind() != VarDecl::TLS_None)
395 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
396 }
397
398 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
400 // C++ [expr.prim.req.nested] p3
401 // A local parameter shall only appear as an unevaluated operand
402 // (Clause 8) within the constraint-expression.
403 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
404 << D;
405 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
406 return true;
407 }
408
409 return false;
410}
411
413 ArrayRef<Expr *> Args) {
414 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
415 if (!Attr)
416 return;
417
418 // The number of formal parameters of the declaration.
419 unsigned NumFormalParams;
420
421 // The kind of declaration. This is also an index into a %select in
422 // the diagnostic.
423 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
424
425 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
426 NumFormalParams = MD->param_size();
427 CalleeKind = CK_Method;
428 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
429 NumFormalParams = FD->param_size();
430 CalleeKind = CK_Function;
431 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
432 QualType Ty = VD->getType();
433 const FunctionType *Fn = nullptr;
434 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
435 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
436 if (!Fn)
437 return;
438 CalleeKind = CK_Function;
439 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
440 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
441 CalleeKind = CK_Block;
442 } else {
443 return;
444 }
445
446 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
447 NumFormalParams = proto->getNumParams();
448 else
449 NumFormalParams = 0;
450 } else {
451 return;
452 }
453
454 // "NullPos" is the number of formal parameters at the end which
455 // effectively count as part of the variadic arguments. This is
456 // useful if you would prefer to not have *any* formal parameters,
457 // but the language forces you to have at least one.
458 unsigned NullPos = Attr->getNullPos();
459 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
460 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
461
462 // The number of arguments which should follow the sentinel.
463 unsigned NumArgsAfterSentinel = Attr->getSentinel();
464
465 // If there aren't enough arguments for all the formal parameters,
466 // the sentinel, and the args after the sentinel, complain.
467 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
468 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
469 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
470 return;
471 }
472
473 // Otherwise, find the sentinel expression.
474 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
475 if (!SentinelExpr)
476 return;
477 if (SentinelExpr->isValueDependent())
478 return;
479 if (Context.isSentinelNullExpr(SentinelExpr))
480 return;
481
482 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
483 // or 'NULL' if those are actually defined in the context. Only use
484 // 'nil' for ObjC methods, where it's much more likely that the
485 // variadic arguments form a list of object pointers.
486 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
487 std::string NullValue;
488 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
489 NullValue = "nil";
490 else if (getLangOpts().CPlusPlus11)
491 NullValue = "nullptr";
492 else if (PP.isMacroDefined("NULL"))
493 NullValue = "NULL";
494 else
495 NullValue = "(void*) 0";
496
497 if (MissingNilLoc.isInvalid())
498 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
499 else
500 Diag(MissingNilLoc, diag::warn_missing_sentinel)
501 << int(CalleeKind)
502 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
503 Diag(D->getLocation(), diag::note_sentinel_here)
504 << int(CalleeKind) << Attr->getRange();
505}
506
508 return E ? E->getSourceRange() : SourceRange();
509}
510
511//===----------------------------------------------------------------------===//
512// Standard Promotions and Conversions
513//===----------------------------------------------------------------------===//
514
515/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
517 // Handle any placeholder expressions which made it here.
518 if (E->hasPlaceholderType()) {
520 if (result.isInvalid()) return ExprError();
521 E = result.get();
522 }
523
524 QualType Ty = E->getType();
525 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
526
527 if (Ty->isFunctionType()) {
528 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
529 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
531 return ExprError();
532
534 CK_FunctionToPointerDecay).get();
535 } else if (Ty->isArrayType()) {
536 // In C90 mode, arrays only promote to pointers if the array expression is
537 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
538 // type 'array of type' is converted to an expression that has type 'pointer
539 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
540 // that has type 'array of type' ...". The relevant change is "an lvalue"
541 // (C90) to "an expression" (C99).
542 //
543 // C++ 4.2p1:
544 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
545 // T" can be converted to an rvalue of type "pointer to T".
546 //
547 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
549 CK_ArrayToPointerDecay);
550 if (Res.isInvalid())
551 return ExprError();
552 E = Res.get();
553 }
554 }
555 return E;
556}
557
559 // Check to see if we are dereferencing a null pointer. If so,
560 // and if not volatile-qualified, this is undefined behavior that the
561 // optimizer will delete, so warn about it. People sometimes try to use this
562 // to get a deterministic trap and are surprised by clang's behavior. This
563 // only handles the pattern "*null", which is a very syntactic check.
564 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
565 if (UO && UO->getOpcode() == UO_Deref &&
566 UO->getSubExpr()->getType()->isPointerType()) {
567 const LangAS AS =
568 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
569 if ((!isTargetAddressSpace(AS) ||
570 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
571 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
573 !UO->getType().isVolatileQualified()) {
574 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
575 S.PDiag(diag::warn_indirection_through_null)
576 << UO->getSubExpr()->getSourceRange());
577 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
578 S.PDiag(diag::note_indirection_through_null));
579 }
580 }
581}
582
583static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
584 SourceLocation AssignLoc,
585 const Expr* RHS) {
586 const ObjCIvarDecl *IV = OIRE->getDecl();
587 if (!IV)
588 return;
589
590 DeclarationName MemberName = IV->getDeclName();
592 if (!Member || !Member->isStr("isa"))
593 return;
594
595 const Expr *Base = OIRE->getBase();
596 QualType BaseType = Base->getType();
597 if (OIRE->isArrow())
598 BaseType = BaseType->getPointeeType();
599 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
600 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
601 ObjCInterfaceDecl *ClassDeclared = nullptr;
602 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
603 if (!ClassDeclared->getSuperClass()
604 && (*ClassDeclared->ivar_begin()) == IV) {
605 if (RHS) {
606 NamedDecl *ObjectSetClass =
608 &S.Context.Idents.get("object_setClass"),
610 if (ObjectSetClass) {
611 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
612 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
614 "object_setClass(")
616 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
617 << FixItHint::CreateInsertion(RHSLocEnd, ")");
618 }
619 else
620 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
621 } else {
622 NamedDecl *ObjectGetClass =
624 &S.Context.Idents.get("object_getClass"),
626 if (ObjectGetClass)
627 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
629 "object_getClass(")
631 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
632 else
633 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
634 }
635 S.Diag(IV->getLocation(), diag::note_ivar_decl);
636 }
637 }
638}
639
641 // Handle any placeholder expressions which made it here.
642 if (E->hasPlaceholderType()) {
644 if (result.isInvalid()) return ExprError();
645 E = result.get();
646 }
647
648 // C++ [conv.lval]p1:
649 // A glvalue of a non-function, non-array type T can be
650 // converted to a prvalue.
651 if (!E->isGLValue()) return E;
652
653 QualType T = E->getType();
654 assert(!T.isNull() && "r-value conversion on typeless expression?");
655
656 // lvalue-to-rvalue conversion cannot be applied to types that decay to
657 // pointers (i.e. function or array types).
659 return E;
660
661 // We don't want to throw lvalue-to-rvalue casts on top of
662 // expressions of certain types in C++.
663 if (getLangOpts().CPlusPlus) {
664 if (T == Context.OverloadTy || T->isRecordType() ||
665 (T->isDependentType() && !T->isAnyPointerType() &&
667 return E;
668 }
669
670 // The C standard is actually really unclear on this point, and
671 // DR106 tells us what the result should be but not why. It's
672 // generally best to say that void types just doesn't undergo
673 // lvalue-to-rvalue at all. Note that expressions of unqualified
674 // 'void' type are never l-values, but qualified void can be.
675 if (T->isVoidType())
676 return E;
677
678 // OpenCL usually rejects direct accesses to values of 'half' type.
679 if (getLangOpts().OpenCL &&
680 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
681 T->isHalfType()) {
682 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
683 << 0 << T;
684 return ExprError();
685 }
686
688 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
689 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
690 &Context.Idents.get("object_getClass"),
692 if (ObjectGetClass)
693 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
694 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
696 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
697 else
698 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
699 }
700 else if (const ObjCIvarRefExpr *OIRE =
701 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
702 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
703
704 // C++ [conv.lval]p1:
705 // [...] If T is a non-class type, the type of the prvalue is the
706 // cv-unqualified version of T. Otherwise, the type of the
707 // rvalue is T.
708 //
709 // C99 6.3.2.1p2:
710 // If the lvalue has qualified type, the value has the unqualified
711 // version of the type of the lvalue; otherwise, the value has the
712 // type of the lvalue.
713 if (T.hasQualifiers())
714 T = T.getUnqualifiedType();
715
716 // Under the MS ABI, lock down the inheritance model now.
717 if (T->isMemberPointerType() &&
719 (void)isCompleteType(E->getExprLoc(), T);
720
722 if (Res.isInvalid())
723 return Res;
724 E = Res.get();
725
726 // Loading a __weak object implicitly retains the value, so we need a cleanup to
727 // balance that.
730
733
734 // C++ [conv.lval]p3:
735 // If T is cv std::nullptr_t, the result is a null pointer constant.
736 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
737 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
739
740 // C11 6.3.2.1p2:
741 // ... if the lvalue has atomic type, the value has the non-atomic version
742 // of the type of the lvalue ...
743 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
744 T = Atomic->getValueType().getUnqualifiedType();
745 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
746 nullptr, VK_PRValue, FPOptionsOverride());
747 }
748
749 return Res;
750}
751
754 if (Res.isInvalid())
755 return ExprError();
756 Res = DefaultLvalueConversion(Res.get());
757 if (Res.isInvalid())
758 return ExprError();
759 return Res;
760}
761
763 QualType Ty = E->getType();
764 ExprResult Res = E;
765 // Only do implicit cast for a function type, but not for a pointer
766 // to function type.
767 if (Ty->isFunctionType()) {
769 CK_FunctionToPointerDecay);
770 if (Res.isInvalid())
771 return ExprError();
772 }
773 Res = DefaultLvalueConversion(Res.get());
774 if (Res.isInvalid())
775 return ExprError();
776 return Res.get();
777}
778
779/// UsualUnaryConversions - Performs various conversions that are common to most
780/// operators (C99 6.3). The conversions of array and function types are
781/// sometimes suppressed. For example, the array->pointer conversion doesn't
782/// apply if the array is an argument to the sizeof or address (&) operators.
783/// In these instances, this routine should *not* be called.
785 // First, convert to an r-value.
787 if (Res.isInvalid())
788 return ExprError();
789 E = Res.get();
790
791 QualType Ty = E->getType();
792 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
793
794 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
795 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
796 (getLangOpts().getFPEvalMethod() !=
799 switch (EvalMethod) {
800 default:
801 llvm_unreachable("Unrecognized float evaluation method");
802 break;
804 llvm_unreachable("Float evaluation method should be set by now");
805 break;
808 // Widen the expression to double.
809 return Ty->isComplexType()
812 CK_FloatingComplexCast)
813 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
814 break;
817 // Widen the expression to long double.
818 return Ty->isComplexType()
821 CK_FloatingComplexCast)
823 CK_FloatingCast);
824 break;
825 }
826 }
827
828 // Half FP have to be promoted to float unless it is natively supported
829 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
830 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
831
832 // Try to perform integral promotions if the object has a theoretically
833 // promotable type.
835 // C99 6.3.1.1p2:
836 //
837 // The following may be used in an expression wherever an int or
838 // unsigned int may be used:
839 // - an object or expression with an integer type whose integer
840 // conversion rank is less than or equal to the rank of int
841 // and unsigned int.
842 // - A bit-field of type _Bool, int, signed int, or unsigned int.
843 //
844 // If an int can represent all values of the original type, the
845 // value is converted to an int; otherwise, it is converted to an
846 // unsigned int. These are called the integer promotions. All
847 // other types are unchanged by the integer promotions.
848
850 if (!PTy.isNull()) {
851 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
852 return E;
853 }
856 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
857 return E;
858 }
859 }
860 return E;
861}
862
863/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
864/// do not have a prototype. Arguments that have type float or __fp16
865/// are promoted to double. All other argument types are converted by
866/// UsualUnaryConversions().
868 QualType Ty = E->getType();
869 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
870
872 if (Res.isInvalid())
873 return ExprError();
874 E = Res.get();
875
876 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
877 // promote to double.
878 // Note that default argument promotion applies only to float (and
879 // half/fp16); it does not apply to _Float16.
880 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
881 if (BTy && (BTy->getKind() == BuiltinType::Half ||
882 BTy->getKind() == BuiltinType::Float)) {
883 if (getLangOpts().OpenCL &&
884 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
885 if (BTy->getKind() == BuiltinType::Half) {
886 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
887 }
888 } else {
889 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
890 }
891 }
892 if (BTy &&
893 getLangOpts().getExtendIntArgs() ==
898 E = (Ty->isUnsignedIntegerType())
899 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
900 .get()
901 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
903 "Unexpected typesize for LongLongTy");
904 }
905
906 // C++ performs lvalue-to-rvalue conversion as a default argument
907 // promotion, even on class types, but note:
908 // C++11 [conv.lval]p2:
909 // When an lvalue-to-rvalue conversion occurs in an unevaluated
910 // operand or a subexpression thereof the value contained in the
911 // referenced object is not accessed. Otherwise, if the glvalue
912 // has a class type, the conversion copy-initializes a temporary
913 // of type T from the glvalue and the result of the conversion
914 // is a prvalue for the temporary.
915 // FIXME: add some way to gate this entire thing for correctness in
916 // potentially potentially evaluated contexts.
920 E->getExprLoc(), E);
921 if (Temp.isInvalid())
922 return ExprError();
923 E = Temp.get();
924 }
925
926 // C++ [expr.call]p7, per CWG722:
927 // An argument that has (possibly cv-qualified) type std::nullptr_t is
928 // converted to void* ([conv.ptr]).
929 // (This does not apply to C23 nullptr)
931 E = ImpCastExprToType(E, Context.VoidPtrTy, CK_NullToPointer).get();
932
933 return E;
934}
935
937 if (Ty->isIncompleteType()) {
938 // C++11 [expr.call]p7:
939 // After these conversions, if the argument does not have arithmetic,
940 // enumeration, pointer, pointer to member, or class type, the program
941 // is ill-formed.
942 //
943 // Since we've already performed null pointer conversion, array-to-pointer
944 // decay and function-to-pointer decay, the only such type in C++ is cv
945 // void. This also handles initializer lists as variadic arguments.
946 if (Ty->isVoidType())
947 return VAK_Invalid;
948
949 if (Ty->isObjCObjectType())
950 return VAK_Invalid;
951 return VAK_Valid;
952 }
953
955 return VAK_Invalid;
956
957 if (Context.getTargetInfo().getTriple().isWasm() &&
959 return VAK_Invalid;
960 }
961
962 if (Ty.isCXX98PODType(Context))
963 return VAK_Valid;
964
965 // C++11 [expr.call]p7:
966 // Passing a potentially-evaluated argument of class type (Clause 9)
967 // having a non-trivial copy constructor, a non-trivial move constructor,
968 // or a non-trivial destructor, with no corresponding parameter,
969 // is conditionally-supported with implementation-defined semantics.
972 if (!Record->hasNonTrivialCopyConstructor() &&
973 !Record->hasNonTrivialMoveConstructor() &&
974 !Record->hasNonTrivialDestructor())
975 return VAK_ValidInCXX11;
976
977 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
978 return VAK_Valid;
979
980 if (Ty->isObjCObjectType())
981 return VAK_Invalid;
982
984 return VAK_Valid;
985
986 if (getLangOpts().MSVCCompat)
987 return VAK_MSVCUndefined;
988
990 return VAK_Valid;
991
992 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
993 // permitted to reject them. We should consider doing so.
994 return VAK_Undefined;
995}
996
998 // Don't allow one to pass an Objective-C interface to a vararg.
999 const QualType &Ty = E->getType();
1000 VarArgKind VAK = isValidVarArgType(Ty);
1001
1002 // Complain about passing non-POD types through varargs.
1003 switch (VAK) {
1004 case VAK_ValidInCXX11:
1006 E->getBeginLoc(), nullptr,
1007 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1008 [[fallthrough]];
1009 case VAK_Valid:
1010 if (Ty->isRecordType()) {
1011 // This is unlikely to be what the user intended. If the class has a
1012 // 'c_str' member function, the user probably meant to call that.
1013 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1014 PDiag(diag::warn_pass_class_arg_to_vararg)
1015 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1016 }
1017 break;
1018
1019 case VAK_Undefined:
1020 case VAK_MSVCUndefined:
1021 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1022 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1023 << getLangOpts().CPlusPlus11 << Ty << CT);
1024 break;
1025
1026 case VAK_Invalid:
1028 Diag(E->getBeginLoc(),
1029 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1030 << Ty << CT;
1031 else if (Ty->isObjCObjectType())
1032 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1033 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1034 << Ty << CT);
1035 else
1036 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1037 << isa<InitListExpr>(E) << Ty << CT;
1038 break;
1039 }
1040}
1041
1043 FunctionDecl *FDecl) {
1044 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1045 // Strip the unbridged-cast placeholder expression off, if applicable.
1046 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1047 (CT == VariadicMethod ||
1048 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1050
1051 // Otherwise, do normal placeholder checking.
1052 } else {
1054 if (ExprRes.isInvalid())
1055 return ExprError();
1056 E = ExprRes.get();
1057 }
1058 }
1059
1061 if (ExprRes.isInvalid())
1062 return ExprError();
1063
1064 // Copy blocks to the heap.
1065 if (ExprRes.get()->getType()->isBlockPointerType())
1066 maybeExtendBlockObject(ExprRes);
1067
1068 E = ExprRes.get();
1069
1070 // Diagnostics regarding non-POD argument types are
1071 // emitted along with format string checking in Sema::CheckFunctionCall().
1073 // Turn this into a trap.
1074 CXXScopeSpec SS;
1075 SourceLocation TemplateKWLoc;
1076 UnqualifiedId Name;
1077 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1078 E->getBeginLoc());
1079 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1080 /*HasTrailingLParen=*/true,
1081 /*IsAddressOfOperand=*/false);
1082 if (TrapFn.isInvalid())
1083 return ExprError();
1084
1085 ExprResult Call = BuildCallExpr(TUScope, TrapFn.get(), E->getBeginLoc(), {},
1086 E->getEndLoc());
1087 if (Call.isInvalid())
1088 return ExprError();
1089
1090 ExprResult Comma =
1091 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1092 if (Comma.isInvalid())
1093 return ExprError();
1094 return Comma.get();
1095 }
1096
1097 if (!getLangOpts().CPlusPlus &&
1099 diag::err_call_incomplete_argument))
1100 return ExprError();
1101
1102 return E;
1103}
1104
1105/// Convert complex integers to complex floats and real integers to
1106/// real floats as required for complex arithmetic. Helper function of
1107/// UsualArithmeticConversions()
1108///
1109/// \return false if the integer expression is an integer type and is
1110/// successfully converted to the (complex) float type.
1112 ExprResult &ComplexExpr,
1113 QualType IntTy,
1114 QualType ComplexTy,
1115 bool SkipCast) {
1116 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1117 if (SkipCast) return false;
1118 if (IntTy->isIntegerType()) {
1119 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1120 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1121 } else {
1122 assert(IntTy->isComplexIntegerType());
1123 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1124 CK_IntegralComplexToFloatingComplex);
1125 }
1126 return false;
1127}
1128
1129// This handles complex/complex, complex/float, or float/complex.
1130// When both operands are complex, the shorter operand is converted to the
1131// type of the longer, and that is the type of the result. This corresponds
1132// to what is done when combining two real floating-point operands.
1133// The fun begins when size promotion occur across type domains.
1134// From H&S 6.3.4: When one operand is complex and the other is a real
1135// floating-point type, the less precise type is converted, within it's
1136// real or complex domain, to the precision of the other type. For example,
1137// when combining a "long double" with a "double _Complex", the
1138// "double _Complex" is promoted to "long double _Complex".
1140 QualType ShorterType,
1141 QualType LongerType,
1142 bool PromotePrecision) {
1143 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1145 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1146
1147 if (PromotePrecision) {
1148 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1149 Shorter =
1150 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1151 } else {
1152 if (LongerIsComplex)
1153 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1154 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1155 }
1156 }
1157 return Result;
1158}
1159
1160/// Handle arithmetic conversion with complex types. Helper function of
1161/// UsualArithmeticConversions()
1163 ExprResult &RHS, QualType LHSType,
1164 QualType RHSType, bool IsCompAssign) {
1165 // Handle (complex) integer types.
1166 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1167 /*SkipCast=*/false))
1168 return LHSType;
1169 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1170 /*SkipCast=*/IsCompAssign))
1171 return RHSType;
1172
1173 // Compute the rank of the two types, regardless of whether they are complex.
1174 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1175 if (Order < 0)
1176 // Promote the precision of the LHS if not an assignment.
1177 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1178 /*PromotePrecision=*/!IsCompAssign);
1179 // Promote the precision of the RHS unless it is already the same as the LHS.
1180 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1181 /*PromotePrecision=*/Order > 0);
1182}
1183
1184/// Handle arithmetic conversion from integer to float. Helper function
1185/// of UsualArithmeticConversions()
1187 ExprResult &IntExpr,
1188 QualType FloatTy, QualType IntTy,
1189 bool ConvertFloat, bool ConvertInt) {
1190 if (IntTy->isIntegerType()) {
1191 if (ConvertInt)
1192 // Convert intExpr to the lhs floating point type.
1193 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1194 CK_IntegralToFloating);
1195 return FloatTy;
1196 }
1197
1198 // Convert both sides to the appropriate complex float.
1199 assert(IntTy->isComplexIntegerType());
1200 QualType result = S.Context.getComplexType(FloatTy);
1201
1202 // _Complex int -> _Complex float
1203 if (ConvertInt)
1204 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1205 CK_IntegralComplexToFloatingComplex);
1206
1207 // float -> _Complex float
1208 if (ConvertFloat)
1209 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1210 CK_FloatingRealToComplex);
1211
1212 return result;
1213}
1214
1215/// Handle arithmethic conversion with floating point types. Helper
1216/// function of UsualArithmeticConversions()
1218 ExprResult &RHS, QualType LHSType,
1219 QualType RHSType, bool IsCompAssign) {
1220 bool LHSFloat = LHSType->isRealFloatingType();
1221 bool RHSFloat = RHSType->isRealFloatingType();
1222
1223 // N1169 4.1.4: If one of the operands has a floating type and the other
1224 // operand has a fixed-point type, the fixed-point operand
1225 // is converted to the floating type [...]
1226 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1227 if (LHSFloat)
1228 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1229 else if (!IsCompAssign)
1230 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1231 return LHSFloat ? LHSType : RHSType;
1232 }
1233
1234 // If we have two real floating types, convert the smaller operand
1235 // to the bigger result.
1236 if (LHSFloat && RHSFloat) {
1237 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1238 if (order > 0) {
1239 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1240 return LHSType;
1241 }
1242
1243 assert(order < 0 && "illegal float comparison");
1244 if (!IsCompAssign)
1245 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1246 return RHSType;
1247 }
1248
1249 if (LHSFloat) {
1250 // Half FP has to be promoted to float unless it is natively supported
1251 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1252 LHSType = S.Context.FloatTy;
1253
1254 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1255 /*ConvertFloat=*/!IsCompAssign,
1256 /*ConvertInt=*/ true);
1257 }
1258 assert(RHSFloat);
1259 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1260 /*ConvertFloat=*/ true,
1261 /*ConvertInt=*/!IsCompAssign);
1262}
1263
1264/// Diagnose attempts to convert between __float128, __ibm128 and
1265/// long double if there is no support for such conversion.
1266/// Helper function of UsualArithmeticConversions().
1267static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1268 QualType RHSType) {
1269 // No issue if either is not a floating point type.
1270 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1271 return false;
1272
1273 // No issue if both have the same 128-bit float semantics.
1274 auto *LHSComplex = LHSType->getAs<ComplexType>();
1275 auto *RHSComplex = RHSType->getAs<ComplexType>();
1276
1277 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1278 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1279
1280 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1281 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1282
1283 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1284 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1285 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1286 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1287 return false;
1288
1289 return true;
1290}
1291
1292typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1293
1294namespace {
1295/// These helper callbacks are placed in an anonymous namespace to
1296/// permit their use as function template parameters.
1297ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1298 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1299}
1300
1301ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1302 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1303 CK_IntegralComplexCast);
1304}
1305}
1306
1307/// Handle integer arithmetic conversions. Helper function of
1308/// UsualArithmeticConversions()
1309template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1311 ExprResult &RHS, QualType LHSType,
1312 QualType RHSType, bool IsCompAssign) {
1313 // The rules for this case are in C99 6.3.1.8
1314 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1315 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1316 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1317 if (LHSSigned == RHSSigned) {
1318 // Same signedness; use the higher-ranked type
1319 if (order >= 0) {
1320 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1321 return LHSType;
1322 } else if (!IsCompAssign)
1323 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1324 return RHSType;
1325 } else if (order != (LHSSigned ? 1 : -1)) {
1326 // The unsigned type has greater than or equal rank to the
1327 // signed type, so use the unsigned type
1328 if (RHSSigned) {
1329 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1330 return LHSType;
1331 } else if (!IsCompAssign)
1332 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1333 return RHSType;
1334 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1335 // The two types are different widths; if we are here, that
1336 // means the signed type is larger than the unsigned type, so
1337 // use the signed type.
1338 if (LHSSigned) {
1339 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1340 return LHSType;
1341 } else if (!IsCompAssign)
1342 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1343 return RHSType;
1344 } else {
1345 // The signed type is higher-ranked than the unsigned type,
1346 // but isn't actually any bigger (like unsigned int and long
1347 // on most 32-bit systems). Use the unsigned type corresponding
1348 // to the signed type.
1349 QualType result =
1350 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1351 RHS = (*doRHSCast)(S, RHS.get(), result);
1352 if (!IsCompAssign)
1353 LHS = (*doLHSCast)(S, LHS.get(), result);
1354 return result;
1355 }
1356}
1357
1358/// Handle conversions with GCC complex int extension. Helper function
1359/// of UsualArithmeticConversions()
1361 ExprResult &RHS, QualType LHSType,
1362 QualType RHSType,
1363 bool IsCompAssign) {
1364 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1365 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1366
1367 if (LHSComplexInt && RHSComplexInt) {
1368 QualType LHSEltType = LHSComplexInt->getElementType();
1369 QualType RHSEltType = RHSComplexInt->getElementType();
1370 QualType ScalarType =
1371 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1372 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1373
1374 return S.Context.getComplexType(ScalarType);
1375 }
1376
1377 if (LHSComplexInt) {
1378 QualType LHSEltType = LHSComplexInt->getElementType();
1379 QualType ScalarType =
1380 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1381 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1383 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1384 CK_IntegralRealToComplex);
1385
1386 return ComplexType;
1387 }
1388
1389 assert(RHSComplexInt);
1390
1391 QualType RHSEltType = RHSComplexInt->getElementType();
1392 QualType ScalarType =
1393 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1394 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1396
1397 if (!IsCompAssign)
1398 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1399 CK_IntegralRealToComplex);
1400 return ComplexType;
1401}
1402
1403/// Return the rank of a given fixed point or integer type. The value itself
1404/// doesn't matter, but the values must be increasing with proper increasing
1405/// rank as described in N1169 4.1.1.
1406static unsigned GetFixedPointRank(QualType Ty) {
1407 const auto *BTy = Ty->getAs<BuiltinType>();
1408 assert(BTy && "Expected a builtin type.");
1409
1410 switch (BTy->getKind()) {
1411 case BuiltinType::ShortFract:
1412 case BuiltinType::UShortFract:
1413 case BuiltinType::SatShortFract:
1414 case BuiltinType::SatUShortFract:
1415 return 1;
1416 case BuiltinType::Fract:
1417 case BuiltinType::UFract:
1418 case BuiltinType::SatFract:
1419 case BuiltinType::SatUFract:
1420 return 2;
1421 case BuiltinType::LongFract:
1422 case BuiltinType::ULongFract:
1423 case BuiltinType::SatLongFract:
1424 case BuiltinType::SatULongFract:
1425 return 3;
1426 case BuiltinType::ShortAccum:
1427 case BuiltinType::UShortAccum:
1428 case BuiltinType::SatShortAccum:
1429 case BuiltinType::SatUShortAccum:
1430 return 4;
1431 case BuiltinType::Accum:
1432 case BuiltinType::UAccum:
1433 case BuiltinType::SatAccum:
1434 case BuiltinType::SatUAccum:
1435 return 5;
1436 case BuiltinType::LongAccum:
1437 case BuiltinType::ULongAccum:
1438 case BuiltinType::SatLongAccum:
1439 case BuiltinType::SatULongAccum:
1440 return 6;
1441 default:
1442 if (BTy->isInteger())
1443 return 0;
1444 llvm_unreachable("Unexpected fixed point or integer type");
1445 }
1446}
1447
1448/// handleFixedPointConversion - Fixed point operations between fixed
1449/// point types and integers or other fixed point types do not fall under
1450/// usual arithmetic conversion since these conversions could result in loss
1451/// of precsision (N1169 4.1.4). These operations should be calculated with
1452/// the full precision of their result type (N1169 4.1.6.2.1).
1454 QualType RHSTy) {
1455 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1456 "Expected at least one of the operands to be a fixed point type");
1457 assert((LHSTy->isFixedPointOrIntegerType() ||
1458 RHSTy->isFixedPointOrIntegerType()) &&
1459 "Special fixed point arithmetic operation conversions are only "
1460 "applied to ints or other fixed point types");
1461
1462 // If one operand has signed fixed-point type and the other operand has
1463 // unsigned fixed-point type, then the unsigned fixed-point operand is
1464 // converted to its corresponding signed fixed-point type and the resulting
1465 // type is the type of the converted operand.
1466 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1468 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1470
1471 // The result type is the type with the highest rank, whereby a fixed-point
1472 // conversion rank is always greater than an integer conversion rank; if the
1473 // type of either of the operands is a saturating fixedpoint type, the result
1474 // type shall be the saturating fixed-point type corresponding to the type
1475 // with the highest rank; the resulting value is converted (taking into
1476 // account rounding and overflow) to the precision of the resulting type.
1477 // Same ranks between signed and unsigned types are resolved earlier, so both
1478 // types are either signed or both unsigned at this point.
1479 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1480 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1481
1482 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1483
1485 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1486
1487 return ResultTy;
1488}
1489
1490/// Check that the usual arithmetic conversions can be performed on this pair of
1491/// expressions that might be of enumeration type.
1494 Sema::ArithConvKind ACK) {
1495 // C++2a [expr.arith.conv]p1:
1496 // If one operand is of enumeration type and the other operand is of a
1497 // different enumeration type or a floating-point type, this behavior is
1498 // deprecated ([depr.arith.conv.enum]).
1499 //
1500 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1501 // Eventually we will presumably reject these cases (in C++23 onwards?).
1503 R = RHS->getEnumCoercedType(S.Context);
1504 bool LEnum = L->isUnscopedEnumerationType(),
1505 REnum = R->isUnscopedEnumerationType();
1506 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1507 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1508 (REnum && L->isFloatingType())) {
1509 S.Diag(Loc, S.getLangOpts().CPlusPlus26
1510 ? diag::err_arith_conv_enum_float_cxx26
1511 : S.getLangOpts().CPlusPlus20
1512 ? diag::warn_arith_conv_enum_float_cxx20
1513 : diag::warn_arith_conv_enum_float)
1514 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1515 << L << R;
1516 } else if (!IsCompAssign && LEnum && REnum &&
1518 unsigned DiagID;
1519 // In C++ 26, usual arithmetic conversions between 2 different enum types
1520 // are ill-formed.
1521 if (S.getLangOpts().CPlusPlus26)
1522 DiagID = diag::err_conv_mixed_enum_types_cxx26;
1523 else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1524 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1525 // If either enumeration type is unnamed, it's less likely that the
1526 // user cares about this, but this situation is still deprecated in
1527 // C++2a. Use a different warning group.
1528 DiagID = S.getLangOpts().CPlusPlus20
1529 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1530 : diag::warn_arith_conv_mixed_anon_enum_types;
1531 } else if (ACK == Sema::ACK_Conditional) {
1532 // Conditional expressions are separated out because they have
1533 // historically had a different warning flag.
1534 DiagID = S.getLangOpts().CPlusPlus20
1535 ? diag::warn_conditional_mixed_enum_types_cxx20
1536 : diag::warn_conditional_mixed_enum_types;
1537 } else if (ACK == Sema::ACK_Comparison) {
1538 // Comparison expressions are separated out because they have
1539 // historically had a different warning flag.
1540 DiagID = S.getLangOpts().CPlusPlus20
1541 ? diag::warn_comparison_mixed_enum_types_cxx20
1542 : diag::warn_comparison_mixed_enum_types;
1543 } else {
1544 DiagID = S.getLangOpts().CPlusPlus20
1545 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1546 : diag::warn_arith_conv_mixed_enum_types;
1547 }
1548 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1549 << (int)ACK << L << R;
1550 }
1551}
1552
1553/// UsualArithmeticConversions - Performs various conversions that are common to
1554/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1555/// routine returns the first non-arithmetic type found. The client is
1556/// responsible for emitting appropriate error diagnostics.
1559 ArithConvKind ACK) {
1560 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1561
1562 if (ACK != ACK_CompAssign) {
1563 LHS = UsualUnaryConversions(LHS.get());
1564 if (LHS.isInvalid())
1565 return QualType();
1566 }
1567
1568 RHS = UsualUnaryConversions(RHS.get());
1569 if (RHS.isInvalid())
1570 return QualType();
1571
1572 // For conversion purposes, we ignore any qualifiers.
1573 // For example, "const float" and "float" are equivalent.
1574 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1575 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1576
1577 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1578 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1579 LHSType = AtomicLHS->getValueType();
1580
1581 // If both types are identical, no conversion is needed.
1582 if (Context.hasSameType(LHSType, RHSType))
1583 return Context.getCommonSugaredType(LHSType, RHSType);
1584
1585 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1586 // The caller can deal with this (e.g. pointer + int).
1587 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1588 return QualType();
1589
1590 // Apply unary and bitfield promotions to the LHS's type.
1591 QualType LHSUnpromotedType = LHSType;
1592 if (Context.isPromotableIntegerType(LHSType))
1593 LHSType = Context.getPromotedIntegerType(LHSType);
1594 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1595 if (!LHSBitfieldPromoteTy.isNull())
1596 LHSType = LHSBitfieldPromoteTy;
1597 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1598 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1599
1600 // If both types are identical, no conversion is needed.
1601 if (Context.hasSameType(LHSType, RHSType))
1602 return Context.getCommonSugaredType(LHSType, RHSType);
1603
1604 // At this point, we have two different arithmetic types.
1605
1606 // Diagnose attempts to convert between __ibm128, __float128 and long double
1607 // where such conversions currently can't be handled.
1608 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1609 return QualType();
1610
1611 // Handle complex types first (C99 6.3.1.8p1).
1612 if (LHSType->isComplexType() || RHSType->isComplexType())
1613 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1614 ACK == ACK_CompAssign);
1615
1616 // Now handle "real" floating types (i.e. float, double, long double).
1617 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1618 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1619 ACK == ACK_CompAssign);
1620
1621 // Handle GCC complex int extension.
1622 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1623 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1624 ACK == ACK_CompAssign);
1625
1626 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1627 return handleFixedPointConversion(*this, LHSType, RHSType);
1628
1629 // Finally, we have two differing integer types.
1630 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1631 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1632}
1633
1634//===----------------------------------------------------------------------===//
1635// Semantic Analysis for various Expression Types
1636//===----------------------------------------------------------------------===//
1637
1638
1640 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1641 bool PredicateIsExpr, void *ControllingExprOrType,
1642 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1643 unsigned NumAssocs = ArgTypes.size();
1644 assert(NumAssocs == ArgExprs.size());
1645
1646 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1647 for (unsigned i = 0; i < NumAssocs; ++i) {
1648 if (ArgTypes[i])
1649 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1650 else
1651 Types[i] = nullptr;
1652 }
1653
1654 // If we have a controlling type, we need to convert it from a parsed type
1655 // into a semantic type and then pass that along.
1656 if (!PredicateIsExpr) {
1657 TypeSourceInfo *ControllingType;
1658 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1659 &ControllingType);
1660 assert(ControllingType && "couldn't get the type out of the parser");
1661 ControllingExprOrType = ControllingType;
1662 }
1663
1665 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1666 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1667 delete [] Types;
1668 return ER;
1669}
1670
1672 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1673 bool PredicateIsExpr, void *ControllingExprOrType,
1675 unsigned NumAssocs = Types.size();
1676 assert(NumAssocs == Exprs.size());
1677 assert(ControllingExprOrType &&
1678 "Must have either a controlling expression or a controlling type");
1679
1680 Expr *ControllingExpr = nullptr;
1681 TypeSourceInfo *ControllingType = nullptr;
1682 if (PredicateIsExpr) {
1683 // Decay and strip qualifiers for the controlling expression type, and
1684 // handle placeholder type replacement. See committee discussion from WG14
1685 // DR423.
1689 reinterpret_cast<Expr *>(ControllingExprOrType));
1690 if (R.isInvalid())
1691 return ExprError();
1692 ControllingExpr = R.get();
1693 } else {
1694 // The extension form uses the type directly rather than converting it.
1695 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1696 if (!ControllingType)
1697 return ExprError();
1698 }
1699
1700 bool TypeErrorFound = false,
1701 IsResultDependent = ControllingExpr
1702 ? ControllingExpr->isTypeDependent()
1703 : ControllingType->getType()->isDependentType(),
1704 ContainsUnexpandedParameterPack =
1705 ControllingExpr
1706 ? ControllingExpr->containsUnexpandedParameterPack()
1707 : ControllingType->getType()->containsUnexpandedParameterPack();
1708
1709 // The controlling expression is an unevaluated operand, so side effects are
1710 // likely unintended.
1711 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1712 ControllingExpr->HasSideEffects(Context, false))
1713 Diag(ControllingExpr->getExprLoc(),
1714 diag::warn_side_effects_unevaluated_context);
1715
1716 for (unsigned i = 0; i < NumAssocs; ++i) {
1717 if (Exprs[i]->containsUnexpandedParameterPack())
1718 ContainsUnexpandedParameterPack = true;
1719
1720 if (Types[i]) {
1721 if (Types[i]->getType()->containsUnexpandedParameterPack())
1722 ContainsUnexpandedParameterPack = true;
1723
1724 if (Types[i]->getType()->isDependentType()) {
1725 IsResultDependent = true;
1726 } else {
1727 // We relax the restriction on use of incomplete types and non-object
1728 // types with the type-based extension of _Generic. Allowing incomplete
1729 // objects means those can be used as "tags" for a type-safe way to map
1730 // to a value. Similarly, matching on function types rather than
1731 // function pointer types can be useful. However, the restriction on VM
1732 // types makes sense to retain as there are open questions about how
1733 // the selection can be made at compile time.
1734 //
1735 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1736 // complete object type other than a variably modified type."
1737 unsigned D = 0;
1738 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1739 D = diag::err_assoc_type_incomplete;
1740 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1741 D = diag::err_assoc_type_nonobject;
1742 else if (Types[i]->getType()->isVariablyModifiedType())
1743 D = diag::err_assoc_type_variably_modified;
1744 else if (ControllingExpr) {
1745 // Because the controlling expression undergoes lvalue conversion,
1746 // array conversion, and function conversion, an association which is
1747 // of array type, function type, or is qualified can never be
1748 // reached. We will warn about this so users are less surprised by
1749 // the unreachable association. However, we don't have to handle
1750 // function types; that's not an object type, so it's handled above.
1751 //
1752 // The logic is somewhat different for C++ because C++ has different
1753 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1754 // If T is a non-class type, the type of the prvalue is the cv-
1755 // unqualified version of T. Otherwise, the type of the prvalue is T.
1756 // The result of these rules is that all qualified types in an
1757 // association in C are unreachable, and in C++, only qualified non-
1758 // class types are unreachable.
1759 //
1760 // NB: this does not apply when the first operand is a type rather
1761 // than an expression, because the type form does not undergo
1762 // conversion.
1763 unsigned Reason = 0;
1764 QualType QT = Types[i]->getType();
1765 if (QT->isArrayType())
1766 Reason = 1;
1767 else if (QT.hasQualifiers() &&
1768 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1769 Reason = 2;
1770
1771 if (Reason)
1772 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1773 diag::warn_unreachable_association)
1774 << QT << (Reason - 1);
1775 }
1776
1777 if (D != 0) {
1778 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1779 << Types[i]->getTypeLoc().getSourceRange()
1780 << Types[i]->getType();
1781 TypeErrorFound = true;
1782 }
1783
1784 // C11 6.5.1.1p2 "No two generic associations in the same generic
1785 // selection shall specify compatible types."
1786 for (unsigned j = i+1; j < NumAssocs; ++j)
1787 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1788 Context.typesAreCompatible(Types[i]->getType(),
1789 Types[j]->getType())) {
1790 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1791 diag::err_assoc_compatible_types)
1792 << Types[j]->getTypeLoc().getSourceRange()
1793 << Types[j]->getType()
1794 << Types[i]->getType();
1795 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1796 diag::note_compat_assoc)
1797 << Types[i]->getTypeLoc().getSourceRange()
1798 << Types[i]->getType();
1799 TypeErrorFound = true;
1800 }
1801 }
1802 }
1803 }
1804 if (TypeErrorFound)
1805 return ExprError();
1806
1807 // If we determined that the generic selection is result-dependent, don't
1808 // try to compute the result expression.
1809 if (IsResultDependent) {
1810 if (ControllingExpr)
1811 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1812 Types, Exprs, DefaultLoc, RParenLoc,
1813 ContainsUnexpandedParameterPack);
1814 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1815 Exprs, DefaultLoc, RParenLoc,
1816 ContainsUnexpandedParameterPack);
1817 }
1818
1819 SmallVector<unsigned, 1> CompatIndices;
1820 unsigned DefaultIndex = -1U;
1821 // Look at the canonical type of the controlling expression in case it was a
1822 // deduced type like __auto_type. However, when issuing diagnostics, use the
1823 // type the user wrote in source rather than the canonical one.
1824 for (unsigned i = 0; i < NumAssocs; ++i) {
1825 if (!Types[i])
1826 DefaultIndex = i;
1827 else if (ControllingExpr &&
1829 ControllingExpr->getType().getCanonicalType(),
1830 Types[i]->getType()))
1831 CompatIndices.push_back(i);
1832 else if (ControllingType &&
1834 ControllingType->getType().getCanonicalType(),
1835 Types[i]->getType()))
1836 CompatIndices.push_back(i);
1837 }
1838
1839 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1840 TypeSourceInfo *ControllingType) {
1841 // We strip parens here because the controlling expression is typically
1842 // parenthesized in macro definitions.
1843 if (ControllingExpr)
1844 ControllingExpr = ControllingExpr->IgnoreParens();
1845
1846 SourceRange SR = ControllingExpr
1847 ? ControllingExpr->getSourceRange()
1848 : ControllingType->getTypeLoc().getSourceRange();
1849 QualType QT = ControllingExpr ? ControllingExpr->getType()
1850 : ControllingType->getType();
1851
1852 return std::make_pair(SR, QT);
1853 };
1854
1855 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1856 // type compatible with at most one of the types named in its generic
1857 // association list."
1858 if (CompatIndices.size() > 1) {
1859 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1860 SourceRange SR = P.first;
1861 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1862 << SR << P.second << (unsigned)CompatIndices.size();
1863 for (unsigned I : CompatIndices) {
1864 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1865 diag::note_compat_assoc)
1866 << Types[I]->getTypeLoc().getSourceRange()
1867 << Types[I]->getType();
1868 }
1869 return ExprError();
1870 }
1871
1872 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1873 // its controlling expression shall have type compatible with exactly one of
1874 // the types named in its generic association list."
1875 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1876 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1877 SourceRange SR = P.first;
1878 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1879 return ExprError();
1880 }
1881
1882 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1883 // type name that is compatible with the type of the controlling expression,
1884 // then the result expression of the generic selection is the expression
1885 // in that generic association. Otherwise, the result expression of the
1886 // generic selection is the expression in the default generic association."
1887 unsigned ResultIndex =
1888 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1889
1890 if (ControllingExpr) {
1892 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1893 ContainsUnexpandedParameterPack, ResultIndex);
1894 }
1896 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1897 ContainsUnexpandedParameterPack, ResultIndex);
1898}
1899
1901 switch (Kind) {
1902 default:
1903 llvm_unreachable("unexpected TokenKind");
1904 case tok::kw___func__:
1905 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
1906 case tok::kw___FUNCTION__:
1908 case tok::kw___FUNCDNAME__:
1909 return PredefinedIdentKind::FuncDName; // [MS]
1910 case tok::kw___FUNCSIG__:
1911 return PredefinedIdentKind::FuncSig; // [MS]
1912 case tok::kw_L__FUNCTION__:
1913 return PredefinedIdentKind::LFunction; // [MS]
1914 case tok::kw_L__FUNCSIG__:
1915 return PredefinedIdentKind::LFuncSig; // [MS]
1916 case tok::kw___PRETTY_FUNCTION__:
1918 }
1919}
1920
1921/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1922/// to determine the value of a PredefinedExpr. This can be either a
1923/// block, lambda, captured statement, function, otherwise a nullptr.
1925 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))
1926 DC = DC->getParent();
1927 return cast_or_null<Decl>(DC);
1928}
1929
1930/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1931/// location of the token and the offset of the ud-suffix within it.
1933 unsigned Offset) {
1934 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1935 S.getLangOpts());
1936}
1937
1938/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1939/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1941 IdentifierInfo *UDSuffix,
1942 SourceLocation UDSuffixLoc,
1943 ArrayRef<Expr*> Args,
1944 SourceLocation LitEndLoc) {
1945 assert(Args.size() <= 2 && "too many arguments for literal operator");
1946
1947 QualType ArgTy[2];
1948 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1949 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1950 if (ArgTy[ArgIdx]->isArrayType())
1951 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1952 }
1953
1954 DeclarationName OpName =
1956 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1957 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1958
1959 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1960 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1961 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1962 /*AllowStringTemplatePack*/ false,
1963 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1964 return ExprError();
1965
1966 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1967}
1968
1970 // StringToks needs backing storage as it doesn't hold array elements itself
1971 std::vector<Token> ExpandedToks;
1972 if (getLangOpts().MicrosoftExt)
1973 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
1974
1975 StringLiteralParser Literal(StringToks, PP,
1977 if (Literal.hadError)
1978 return ExprError();
1979
1980 SmallVector<SourceLocation, 4> StringTokLocs;
1981 for (const Token &Tok : StringToks)
1982 StringTokLocs.push_back(Tok.getLocation());
1983
1985 Context, Literal.GetString(), StringLiteralKind::Unevaluated, false, {},
1986 &StringTokLocs[0], StringTokLocs.size());
1987
1988 if (!Literal.getUDSuffix().empty()) {
1989 SourceLocation UDSuffixLoc =
1990 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1991 Literal.getUDSuffixOffset());
1992 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1993 }
1994
1995 return Lit;
1996}
1997
1998std::vector<Token>
2000 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2001 // local macros that expand to string literals that may be concatenated.
2002 // These macros are expanded here (in Sema), because StringLiteralParser
2003 // (in Lex) doesn't know the enclosing function (because it hasn't been
2004 // parsed yet).
2005 assert(getLangOpts().MicrosoftExt);
2006
2007 // Note: Although function local macros are defined only inside functions,
2008 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2009 // expansion of macros into empty string literals without additional checks.
2010 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2011 if (!CurrentDecl)
2012 CurrentDecl = Context.getTranslationUnitDecl();
2013
2014 std::vector<Token> ExpandedToks;
2015 ExpandedToks.reserve(Toks.size());
2016 for (const Token &Tok : Toks) {
2017 if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
2018 assert(tok::isStringLiteral(Tok.getKind()));
2019 ExpandedToks.emplace_back(Tok);
2020 continue;
2021 }
2022 if (isa<TranslationUnitDecl>(CurrentDecl))
2023 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2024 // Stringify predefined expression
2025 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2026 << Tok.getKind();
2027 SmallString<64> Str;
2028 llvm::raw_svector_ostream OS(Str);
2029 Token &Exp = ExpandedToks.emplace_back();
2030 Exp.startToken();
2031 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2032 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2033 OS << 'L';
2034 Exp.setKind(tok::wide_string_literal);
2035 } else {
2036 Exp.setKind(tok::string_literal);
2037 }
2038 OS << '"'
2040 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2041 << '"';
2042 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2043 }
2044 return ExpandedToks;
2045}
2046
2049 assert(!StringToks.empty() && "Must have at least one string!");
2050
2051 // StringToks needs backing storage as it doesn't hold array elements itself
2052 std::vector<Token> ExpandedToks;
2053 if (getLangOpts().MicrosoftExt)
2054 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2055
2056 StringLiteralParser Literal(StringToks, PP);
2057 if (Literal.hadError)
2058 return ExprError();
2059
2060 SmallVector<SourceLocation, 4> StringTokLocs;
2061 for (const Token &Tok : StringToks)
2062 StringTokLocs.push_back(Tok.getLocation());
2063
2064 QualType CharTy = Context.CharTy;
2066 if (Literal.isWide()) {
2067 CharTy = Context.getWideCharType();
2069 } else if (Literal.isUTF8()) {
2070 if (getLangOpts().Char8)
2071 CharTy = Context.Char8Ty;
2072 else if (getLangOpts().C23)
2073 CharTy = Context.UnsignedCharTy;
2075 } else if (Literal.isUTF16()) {
2076 CharTy = Context.Char16Ty;
2078 } else if (Literal.isUTF32()) {
2079 CharTy = Context.Char32Ty;
2081 } else if (Literal.isPascal()) {
2082 CharTy = Context.UnsignedCharTy;
2083 }
2084
2085 // Warn on u8 string literals before C++20 and C23, whose type
2086 // was an array of char before but becomes an array of char8_t.
2087 // In C++20, it cannot be used where a pointer to char is expected.
2088 // In C23, it might have an unexpected value if char was signed.
2089 if (Kind == StringLiteralKind::UTF8 &&
2091 ? !getLangOpts().CPlusPlus20 && !getLangOpts().Char8
2092 : !getLangOpts().C23)) {
2093 Diag(StringTokLocs.front(), getLangOpts().CPlusPlus
2094 ? diag::warn_cxx20_compat_utf8_string
2095 : diag::warn_c23_compat_utf8_string);
2096
2097 // Create removals for all 'u8' prefixes in the string literal(s). This
2098 // ensures C++20/C23 compatibility (but may change the program behavior when
2099 // built by non-Clang compilers for which the execution character set is
2100 // not always UTF-8).
2101 auto RemovalDiag = PDiag(diag::note_cxx20_c23_compat_utf8_string_remove_u8);
2102 SourceLocation RemovalDiagLoc;
2103 for (const Token &Tok : StringToks) {
2104 if (Tok.getKind() == tok::utf8_string_literal) {
2105 if (RemovalDiagLoc.isInvalid())
2106 RemovalDiagLoc = Tok.getLocation();
2108 Tok.getLocation(),
2109 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2111 }
2112 }
2113 Diag(RemovalDiagLoc, RemovalDiag);
2114 }
2115
2116 QualType StrTy =
2117 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2118
2119 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2120 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2121 Kind, Literal.Pascal, StrTy,
2122 &StringTokLocs[0],
2123 StringTokLocs.size());
2124 if (Literal.getUDSuffix().empty())
2125 return Lit;
2126
2127 // We're building a user-defined literal.
2128 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2129 SourceLocation UDSuffixLoc =
2130 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2131 Literal.getUDSuffixOffset());
2132
2133 // Make sure we're allowed user-defined literals here.
2134 if (!UDLScope)
2135 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2136
2137 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2138 // operator "" X (str, len)
2139 QualType SizeType = Context.getSizeType();
2140
2141 DeclarationName OpName =
2143 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2144 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2145
2146 QualType ArgTy[] = {
2147 Context.getArrayDecayedType(StrTy), SizeType
2148 };
2149
2150 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2151 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2152 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2153 /*AllowStringTemplatePack*/ true,
2154 /*DiagnoseMissing*/ true, Lit)) {
2155
2156 case LOLR_Cooked: {
2157 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2158 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2159 StringTokLocs[0]);
2160 Expr *Args[] = { Lit, LenArg };
2161
2162 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2163 }
2164
2165 case LOLR_Template: {
2166 TemplateArgumentListInfo ExplicitArgs;
2167 TemplateArgument Arg(Lit);
2168 TemplateArgumentLocInfo ArgInfo(Lit);
2169 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2170 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2171 &ExplicitArgs);
2172 }
2173
2175 TemplateArgumentListInfo ExplicitArgs;
2176
2177 unsigned CharBits = Context.getIntWidth(CharTy);
2178 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2179 llvm::APSInt Value(CharBits, CharIsUnsigned);
2180
2181 TemplateArgument TypeArg(CharTy);
2183 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2184
2185 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2186 Value = Lit->getCodeUnit(I);
2187 TemplateArgument Arg(Context, Value, CharTy);
2189 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2190 }
2191 return BuildLiteralOperatorCall(R, OpNameInfo, {}, StringTokLocs.back(),
2192 &ExplicitArgs);
2193 }
2194 case LOLR_Raw:
2196 llvm_unreachable("unexpected literal operator lookup result");
2197 case LOLR_Error:
2198 return ExprError();
2199 }
2200 llvm_unreachable("unexpected literal operator lookup result");
2201}
2202
2206 const CXXScopeSpec *SS) {
2207 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2208 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2209}
2210
2213 const DeclarationNameInfo &NameInfo,
2214 const CXXScopeSpec *SS, NamedDecl *FoundD,
2215 SourceLocation TemplateKWLoc,
2216 const TemplateArgumentListInfo *TemplateArgs) {
2219 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2220 TemplateArgs);
2221}
2222
2223// CUDA/HIP: Check whether a captured reference variable is referencing a
2224// host variable in a device or host device lambda.
2226 VarDecl *VD) {
2227 if (!S.getLangOpts().CUDA || !VD->hasInit())
2228 return false;
2229 assert(VD->getType()->isReferenceType());
2230
2231 // Check whether the reference variable is referencing a host variable.
2232 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2233 if (!DRE)
2234 return false;
2235 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2236 if (!Referee || !Referee->hasGlobalStorage() ||
2237 Referee->hasAttr<CUDADeviceAttr>())
2238 return false;
2239
2240 // Check whether the current function is a device or host device lambda.
2241 // Check whether the reference variable is a capture by getDeclContext()
2242 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2243 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2244 if (MD && MD->getParent()->isLambda() &&
2245 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2246 VD->getDeclContext() != MD)
2247 return true;
2248
2249 return false;
2250}
2251
2253 // A declaration named in an unevaluated operand never constitutes an odr-use.
2255 return NOUR_Unevaluated;
2256
2257 // C++2a [basic.def.odr]p4:
2258 // A variable x whose name appears as a potentially-evaluated expression e
2259 // is odr-used by e unless [...] x is a reference that is usable in
2260 // constant expressions.
2261 // CUDA/HIP:
2262 // If a reference variable referencing a host variable is captured in a
2263 // device or host device lambda, the value of the referee must be copied
2264 // to the capture and the reference variable must be treated as odr-use
2265 // since the value of the referee is not known at compile time and must
2266 // be loaded from the captured.
2267 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2268 if (VD->getType()->isReferenceType() &&
2269 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2271 VD->isUsableInConstantExpressions(Context))
2272 return NOUR_Constant;
2273 }
2274
2275 // All remaining non-variable cases constitute an odr-use. For variables, we
2276 // need to wait and see how the expression is used.
2277 return NOUR_None;
2278}
2279
2282 const DeclarationNameInfo &NameInfo,
2283 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2284 SourceLocation TemplateKWLoc,
2285 const TemplateArgumentListInfo *TemplateArgs) {
2286 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2287 NeedToCaptureVariable(D, NameInfo.getLoc());
2288
2290 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2291 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2293
2294 // C++ [except.spec]p17:
2295 // An exception-specification is considered to be needed when:
2296 // - in an expression, the function is the unique lookup result or
2297 // the selected member of a set of overloaded functions.
2298 //
2299 // We delay doing this until after we've built the function reference and
2300 // marked it as used so that:
2301 // a) if the function is defaulted, we get errors from defining it before /
2302 // instead of errors from computing its exception specification, and
2303 // b) if the function is a defaulted comparison, we can use the body we
2304 // build when defining it as input to the exception specification
2305 // computation rather than computing a new body.
2306 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2307 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2308 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2310 }
2311 }
2312
2313 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2315 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2317
2318 const auto *FD = dyn_cast<FieldDecl>(D);
2319 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2320 FD = IFD->getAnonField();
2321 if (FD) {
2322 UnusedPrivateFields.remove(FD);
2323 // Just in case we're building an illegal pointer-to-member.
2324 if (FD->isBitField())
2326 }
2327
2328 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2329 // designates a bit-field.
2330 if (const auto *BD = dyn_cast<BindingDecl>(D))
2331 if (const auto *BE = BD->getBinding())
2332 E->setObjectKind(BE->getObjectKind());
2333
2334 return E;
2335}
2336
2337void
2340 DeclarationNameInfo &NameInfo,
2341 const TemplateArgumentListInfo *&TemplateArgs) {
2342 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2343 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2344 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2345
2346 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2347 Id.TemplateId->NumArgs);
2348 translateTemplateArguments(TemplateArgsPtr, Buffer);
2349
2350 TemplateName TName = Id.TemplateId->Template.get();
2351 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2352 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2353 TemplateArgs = &Buffer;
2354 } else {
2355 NameInfo = GetNameFromUnqualifiedId(Id);
2356 TemplateArgs = nullptr;
2357 }
2358}
2359
2361 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2363 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2364 DeclContext *Ctx =
2365 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2366 if (!TC) {
2367 // Emit a special diagnostic for failed member lookups.
2368 // FIXME: computing the declaration context might fail here (?)
2369 if (Ctx)
2370 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2371 << SS.getRange();
2372 else
2373 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2374 return;
2375 }
2376
2377 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2378 bool DroppedSpecifier =
2379 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2380 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2381 ? diag::note_implicit_param_decl
2382 : diag::note_previous_decl;
2383 if (!Ctx)
2384 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2385 SemaRef.PDiag(NoteID));
2386 else
2387 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2388 << Typo << Ctx << DroppedSpecifier
2389 << SS.getRange(),
2390 SemaRef.PDiag(NoteID));
2391}
2392
2394 // During a default argument instantiation the CurContext points
2395 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2396 // function parameter list, hence add an explicit check.
2397 bool isDefaultArgument =
2398 !CodeSynthesisContexts.empty() &&
2399 CodeSynthesisContexts.back().Kind ==
2401 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2402 bool isInstance = CurMethod && CurMethod->isInstance() &&
2403 R.getNamingClass() == CurMethod->getParent() &&
2404 !isDefaultArgument;
2405
2406 // There are two ways we can find a class-scope declaration during template
2407 // instantiation that we did not find in the template definition: if it is a
2408 // member of a dependent base class, or if it is declared after the point of
2409 // use in the same class. Distinguish these by comparing the class in which
2410 // the member was found to the naming class of the lookup.
2411 unsigned DiagID = diag::err_found_in_dependent_base;
2412 unsigned NoteID = diag::note_member_declared_at;
2414 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2415 : diag::err_found_later_in_class;
2416 } else if (getLangOpts().MSVCCompat) {
2417 DiagID = diag::ext_found_in_dependent_base;
2418 NoteID = diag::note_dependent_member_use;
2419 }
2420
2421 if (isInstance) {
2422 // Give a code modification hint to insert 'this->'.
2423 Diag(R.getNameLoc(), DiagID)
2424 << R.getLookupName()
2425 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2427 } else {
2428 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2429 // they're not shadowed).
2430 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2431 }
2432
2433 for (const NamedDecl *D : R)
2434 Diag(D->getLocation(), NoteID);
2435
2436 // Return true if we are inside a default argument instantiation
2437 // and the found name refers to an instance member function, otherwise
2438 // the caller will try to create an implicit member call and this is wrong
2439 // for default arguments.
2440 //
2441 // FIXME: Is this special case necessary? We could allow the caller to
2442 // diagnose this.
2443 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2444 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2445 return true;
2446 }
2447
2448 // Tell the callee to try to recover.
2449 return false;
2450}
2451
2454 TemplateArgumentListInfo *ExplicitTemplateArgs,
2455 ArrayRef<Expr *> Args, DeclContext *LookupCtx,
2456 TypoExpr **Out) {
2457 DeclarationName Name = R.getLookupName();
2458
2459 unsigned diagnostic = diag::err_undeclared_var_use;
2460 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2461 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2462 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2463 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2464 diagnostic = diag::err_undeclared_use;
2465 diagnostic_suggest = diag::err_undeclared_use_suggest;
2466 }
2467
2468 // If the original lookup was an unqualified lookup, fake an
2469 // unqualified lookup. This is useful when (for example) the
2470 // original lookup would not have found something because it was a
2471 // dependent name.
2472 DeclContext *DC =
2473 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2474 while (DC) {
2475 if (isa<CXXRecordDecl>(DC)) {
2476 if (ExplicitTemplateArgs) {
2478 R, S, SS, Context.getRecordType(cast<CXXRecordDecl>(DC)),
2479 /*EnteringContext*/ false, TemplateNameIsRequired,
2480 /*RequiredTemplateKind*/ nullptr, /*AllowTypoCorrection*/ true))
2481 return true;
2482 } else {
2483 LookupQualifiedName(R, DC);
2484 }
2485
2486 if (!R.empty()) {
2487 // Don't give errors about ambiguities in this lookup.
2489
2490 // If there's a best viable function among the results, only mention
2491 // that one in the notes.
2492 OverloadCandidateSet Candidates(R.getNameLoc(),
2494 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2496 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2497 OR_Success) {
2498 R.clear();
2499 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2500 R.resolveKind();
2501 }
2502
2504 }
2505
2506 R.clear();
2507 }
2508
2509 DC = DC->getLookupParent();
2510 }
2511
2512 // We didn't find anything, so try to correct for a typo.
2513 TypoCorrection Corrected;
2514 if (S && Out) {
2515 SourceLocation TypoLoc = R.getNameLoc();
2516 assert(!ExplicitTemplateArgs &&
2517 "Diagnosing an empty lookup with explicit template args!");
2518 *Out = CorrectTypoDelayed(
2519 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2520 [=](const TypoCorrection &TC) {
2521 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2522 diagnostic, diagnostic_suggest);
2523 },
2524 nullptr, CTK_ErrorRecovery, LookupCtx);
2525 if (*Out)
2526 return true;
2527 } else if (S && (Corrected =
2529 &SS, CCC, CTK_ErrorRecovery, LookupCtx))) {
2530 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2531 bool DroppedSpecifier =
2532 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2533 R.setLookupName(Corrected.getCorrection());
2534
2535 bool AcceptableWithRecovery = false;
2536 bool AcceptableWithoutRecovery = false;
2537 NamedDecl *ND = Corrected.getFoundDecl();
2538 if (ND) {
2539 if (Corrected.isOverloaded()) {
2543 for (NamedDecl *CD : Corrected) {
2544 if (FunctionTemplateDecl *FTD =
2545 dyn_cast<FunctionTemplateDecl>(CD))
2547 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2548 Args, OCS);
2549 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2550 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2552 Args, OCS);
2553 }
2554 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2555 case OR_Success:
2556 ND = Best->FoundDecl;
2557 Corrected.setCorrectionDecl(ND);
2558 break;
2559 default:
2560 // FIXME: Arbitrarily pick the first declaration for the note.
2561 Corrected.setCorrectionDecl(ND);
2562 break;
2563 }
2564 }
2565 R.addDecl(ND);
2566 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2567 CXXRecordDecl *Record = nullptr;
2568 if (Corrected.getCorrectionSpecifier()) {
2569 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2570 Record = Ty->getAsCXXRecordDecl();
2571 }
2572 if (!Record)
2573 Record = cast<CXXRecordDecl>(
2576 }
2577
2578 auto *UnderlyingND = ND->getUnderlyingDecl();
2579 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2580 isa<FunctionTemplateDecl>(UnderlyingND);
2581 // FIXME: If we ended up with a typo for a type name or
2582 // Objective-C class name, we're in trouble because the parser
2583 // is in the wrong place to recover. Suggest the typo
2584 // correction, but don't make it a fix-it since we're not going
2585 // to recover well anyway.
2586 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2587 getAsTypeTemplateDecl(UnderlyingND) ||
2588 isa<ObjCInterfaceDecl>(UnderlyingND);
2589 } else {
2590 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2591 // because we aren't able to recover.
2592 AcceptableWithoutRecovery = true;
2593 }
2594
2595 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2596 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2597 ? diag::note_implicit_param_decl
2598 : diag::note_previous_decl;
2599 if (SS.isEmpty())
2600 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2601 PDiag(NoteID), AcceptableWithRecovery);
2602 else
2603 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2604 << Name << computeDeclContext(SS, false)
2605 << DroppedSpecifier << SS.getRange(),
2606 PDiag(NoteID), AcceptableWithRecovery);
2607
2608 // Tell the callee whether to try to recover.
2609 return !AcceptableWithRecovery;
2610 }
2611 }
2612 R.clear();
2613
2614 // Emit a special diagnostic for failed member lookups.
2615 // FIXME: computing the declaration context might fail here (?)
2616 if (!SS.isEmpty()) {
2617 Diag(R.getNameLoc(), diag::err_no_member)
2618 << Name << computeDeclContext(SS, false)
2619 << SS.getRange();
2620 return true;
2621 }
2622
2623 // Give up, we can't recover.
2624 Diag(R.getNameLoc(), diagnostic) << Name;
2625 return true;
2626}
2627
2628/// In Microsoft mode, if we are inside a template class whose parent class has
2629/// dependent base classes, and we can't resolve an unqualified identifier, then
2630/// assume the identifier is a member of a dependent base class. We can only
2631/// recover successfully in static methods, instance methods, and other contexts
2632/// where 'this' is available. This doesn't precisely match MSVC's
2633/// instantiation model, but it's close enough.
2634static Expr *
2636 DeclarationNameInfo &NameInfo,
2637 SourceLocation TemplateKWLoc,
2638 const TemplateArgumentListInfo *TemplateArgs) {
2639 // Only try to recover from lookup into dependent bases in static methods or
2640 // contexts where 'this' is available.
2641 QualType ThisType = S.getCurrentThisType();
2642 const CXXRecordDecl *RD = nullptr;
2643 if (!ThisType.isNull())
2644 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2645 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2646 RD = MD->getParent();
2647 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2648 return nullptr;
2649
2650 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2651 // is available, suggest inserting 'this->' as a fixit.
2652 SourceLocation Loc = NameInfo.getLoc();
2653 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2654 DB << NameInfo.getName() << RD;
2655
2656 if (!ThisType.isNull()) {
2657 DB << FixItHint::CreateInsertion(Loc, "this->");
2659 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2660 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2661 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2662 }
2663
2664 // Synthesize a fake NNS that points to the derived class. This will
2665 // perform name lookup during template instantiation.
2666 CXXScopeSpec SS;
2667 auto *NNS =
2668 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2669 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2671 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2672 TemplateArgs);
2673}
2674
2677 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2678 bool HasTrailingLParen, bool IsAddressOfOperand,
2680 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2681 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2682 "cannot be direct & operand and have a trailing lparen");
2683 if (SS.isInvalid())
2684 return ExprError();
2685
2686 TemplateArgumentListInfo TemplateArgsBuffer;
2687
2688 // Decompose the UnqualifiedId into the following data.
2689 DeclarationNameInfo NameInfo;
2690 const TemplateArgumentListInfo *TemplateArgs;
2691 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2692
2693 DeclarationName Name = NameInfo.getName();
2694 IdentifierInfo *II = Name.getAsIdentifierInfo();
2695 SourceLocation NameLoc = NameInfo.getLoc();
2696
2697 if (II && II->isEditorPlaceholder()) {
2698 // FIXME: When typed placeholders are supported we can create a typed
2699 // placeholder expression node.
2700 return ExprError();
2701 }
2702
2703 // This specially handles arguments of attributes appertains to a type of C
2704 // struct field such that the name lookup within a struct finds the member
2705 // name, which is not the case for other contexts in C.
2706 if (isAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2707 // See if this is reference to a field of struct.
2708 LookupResult R(*this, NameInfo, LookupMemberName);
2709 // LookupName handles a name lookup from within anonymous struct.
2710 if (LookupName(R, S)) {
2711 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2712 QualType type = VD->getType().getNonReferenceType();
2713 // This will eventually be translated into MemberExpr upon
2714 // the use of instantiated struct fields.
2715 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2716 }
2717 }
2718 }
2719
2720 // Perform the required lookup.
2721 LookupResult R(*this, NameInfo,
2725 if (TemplateKWLoc.isValid() || TemplateArgs) {
2726 // Lookup the template name again to correctly establish the context in
2727 // which it was found. This is really unfortunate as we already did the
2728 // lookup to determine that it was a template name in the first place. If
2729 // this becomes a performance hit, we can work harder to preserve those
2730 // results until we get here but it's likely not worth it.
2731 AssumedTemplateKind AssumedTemplate;
2732 if (LookupTemplateName(R, S, SS, /*ObjectType=*/QualType(),
2733 /*EnteringContext=*/false, TemplateKWLoc,
2734 &AssumedTemplate))
2735 return ExprError();
2736
2738 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2739 IsAddressOfOperand, TemplateArgs);
2740 } else {
2741 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2742 LookupParsedName(R, S, &SS, /*ObjectType=*/QualType(),
2743 /*AllowBuiltinCreation=*/!IvarLookupFollowUp);
2744
2745 // If the result might be in a dependent base class, this is a dependent
2746 // id-expression.
2748 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2749 IsAddressOfOperand, TemplateArgs);
2750
2751 // If this reference is in an Objective-C method, then we need to do
2752 // some special Objective-C lookup, too.
2753 if (IvarLookupFollowUp) {
2754 ExprResult E(ObjC().LookupInObjCMethod(R, S, II, true));
2755 if (E.isInvalid())
2756 return ExprError();
2757
2758 if (Expr *Ex = E.getAs<Expr>())
2759 return Ex;
2760 }
2761 }
2762
2763 if (R.isAmbiguous())
2764 return ExprError();
2765
2766 // This could be an implicitly declared function reference if the language
2767 // mode allows it as a feature.
2768 if (R.empty() && HasTrailingLParen && II &&
2769 getLangOpts().implicitFunctionsAllowed()) {
2770 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2771 if (D) R.addDecl(D);
2772 }
2773
2774 // Determine whether this name might be a candidate for
2775 // argument-dependent lookup.
2776 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2777
2778 if (R.empty() && !ADL) {
2779 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2780 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2781 TemplateKWLoc, TemplateArgs))
2782 return E;
2783 }
2784
2785 // Don't diagnose an empty lookup for inline assembly.
2786 if (IsInlineAsmIdentifier)
2787 return ExprError();
2788
2789 // If this name wasn't predeclared and if this is not a function
2790 // call, diagnose the problem.
2791 TypoExpr *TE = nullptr;
2792 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2793 : nullptr);
2794 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2795 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2796 "Typo correction callback misconfigured");
2797 if (CCC) {
2798 // Make sure the callback knows what the typo being diagnosed is.
2799 CCC->setTypoName(II);
2800 if (SS.isValid())
2801 CCC->setTypoNNS(SS.getScopeRep());
2802 }
2803 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2804 // a template name, but we happen to have always already looked up the name
2805 // before we get here if it must be a template name.
2806 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2807 {}, nullptr, &TE)) {
2808 if (TE && KeywordReplacement) {
2809 auto &State = getTypoExprState(TE);
2810 auto BestTC = State.Consumer->getNextCorrection();
2811 if (BestTC.isKeyword()) {
2812 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2813 if (State.DiagHandler)
2814 State.DiagHandler(BestTC);
2815 KeywordReplacement->startToken();
2816 KeywordReplacement->setKind(II->getTokenID());
2817 KeywordReplacement->setIdentifierInfo(II);
2818 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2819 // Clean up the state associated with the TypoExpr, since it has
2820 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2821 clearDelayedTypo(TE);
2822 // Signal that a correction to a keyword was performed by returning a
2823 // valid-but-null ExprResult.
2824 return (Expr*)nullptr;
2825 }
2826 State.Consumer->resetCorrectionStream();
2827 }
2828 return TE ? TE : ExprError();
2829 }
2830
2831 assert(!R.empty() &&
2832 "DiagnoseEmptyLookup returned false but added no results");
2833
2834 // If we found an Objective-C instance variable, let
2835 // LookupInObjCMethod build the appropriate expression to
2836 // reference the ivar.
2837 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2838 R.clear();
2839 ExprResult E(ObjC().LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2840 // In a hopelessly buggy code, Objective-C instance variable
2841 // lookup fails and no expression will be built to reference it.
2842 if (!E.isInvalid() && !E.get())
2843 return ExprError();
2844 return E;
2845 }
2846 }
2847
2848 // This is guaranteed from this point on.
2849 assert(!R.empty() || ADL);
2850
2851 // Check whether this might be a C++ implicit instance member access.
2852 // C++ [class.mfct.non-static]p3:
2853 // When an id-expression that is not part of a class member access
2854 // syntax and not used to form a pointer to member is used in the
2855 // body of a non-static member function of class X, if name lookup
2856 // resolves the name in the id-expression to a non-static non-type
2857 // member of some class C, the id-expression is transformed into a
2858 // class member access expression using (*this) as the
2859 // postfix-expression to the left of the . operator.
2860 //
2861 // But we don't actually need to do this for '&' operands if R
2862 // resolved to a function or overloaded function set, because the
2863 // expression is ill-formed if it actually works out to be a
2864 // non-static member function:
2865 //
2866 // C++ [expr.ref]p4:
2867 // Otherwise, if E1.E2 refers to a non-static member function. . .
2868 // [t]he expression can be used only as the left-hand operand of a
2869 // member function call.
2870 //
2871 // There are other safeguards against such uses, but it's important
2872 // to get this right here so that we don't end up making a
2873 // spuriously dependent expression if we're inside a dependent
2874 // instance method.
2875 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2876 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2877 S);
2878
2879 if (TemplateArgs || TemplateKWLoc.isValid()) {
2880
2881 // In C++1y, if this is a variable template id, then check it
2882 // in BuildTemplateIdExpr().
2883 // The single lookup result must be a variable template declaration.
2884 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2885 Id.TemplateId->Kind == TNK_Var_template) {
2886 assert(R.getAsSingle<VarTemplateDecl>() &&
2887 "There should only be one declaration found.");
2888 }
2889
2890 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2891 }
2892
2893 return BuildDeclarationNameExpr(SS, R, ADL);
2894}
2895
2897 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2898 bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI) {
2899 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2900 LookupParsedName(R, /*S=*/nullptr, &SS, /*ObjectType=*/QualType());
2901
2902 if (R.isAmbiguous())
2903 return ExprError();
2904
2906 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2907 NameInfo, /*TemplateArgs=*/nullptr);
2908
2909 if (R.empty()) {
2910 // Don't diagnose problems with invalid record decl, the secondary no_member
2911 // diagnostic during template instantiation is likely bogus, e.g. if a class
2912 // is invalid because it's derived from an invalid base class, then missing
2913 // members were likely supposed to be inherited.
2915 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2916 if (CD->isInvalidDecl())
2917 return ExprError();
2918 Diag(NameInfo.getLoc(), diag::err_no_member)
2919 << NameInfo.getName() << DC << SS.getRange();
2920 return ExprError();
2921 }
2922
2923 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2924 // Diagnose a missing typename if this resolved unambiguously to a type in
2925 // a dependent context. If we can recover with a type, downgrade this to
2926 // a warning in Microsoft compatibility mode.
2927 unsigned DiagID = diag::err_typename_missing;
2928 if (RecoveryTSI && getLangOpts().MSVCCompat)
2929 DiagID = diag::ext_typename_missing;
2931 auto D = Diag(Loc, DiagID);
2932 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2933 << SourceRange(Loc, NameInfo.getEndLoc());
2934
2935 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2936 // context.
2937 if (!RecoveryTSI)
2938 return ExprError();
2939
2940 // Only issue the fixit if we're prepared to recover.
2941 D << FixItHint::CreateInsertion(Loc, "typename ");
2942
2943 // Recover by pretending this was an elaborated type.
2945 TypeLocBuilder TLB;
2946 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2947
2952
2953 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2954
2955 return ExprEmpty();
2956 }
2957
2958 // If necessary, build an implicit class member access.
2959 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2961 /*TemplateKWLoc=*/SourceLocation(),
2962 R, /*TemplateArgs=*/nullptr,
2963 /*S=*/nullptr);
2964
2965 return BuildDeclarationNameExpr(SS, R, /*ADL=*/false);
2966}
2967
2970 NestedNameSpecifier *Qualifier,
2971 NamedDecl *FoundDecl,
2972 NamedDecl *Member) {
2973 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2974 if (!RD)
2975 return From;
2976
2977 QualType DestRecordType;
2978 QualType DestType;
2979 QualType FromRecordType;
2980 QualType FromType = From->getType();
2981 bool PointerConversions = false;
2982 if (isa<FieldDecl>(Member)) {
2983 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2984 auto FromPtrType = FromType->getAs<PointerType>();
2985 DestRecordType = Context.getAddrSpaceQualType(
2986 DestRecordType, FromPtrType
2987 ? FromType->getPointeeType().getAddressSpace()
2988 : FromType.getAddressSpace());
2989
2990 if (FromPtrType) {
2991 DestType = Context.getPointerType(DestRecordType);
2992 FromRecordType = FromPtrType->getPointeeType();
2993 PointerConversions = true;
2994 } else {
2995 DestType = DestRecordType;
2996 FromRecordType = FromType;
2997 }
2998 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
2999 if (!Method->isImplicitObjectMemberFunction())
3000 return From;
3001
3002 DestType = Method->getThisType().getNonReferenceType();
3003 DestRecordType = Method->getFunctionObjectParameterType();
3004
3005 if (FromType->getAs<PointerType>()) {
3006 FromRecordType = FromType->getPointeeType();
3007 PointerConversions = true;
3008 } else {
3009 FromRecordType = FromType;
3010 DestType = DestRecordType;
3011 }
3012
3013 LangAS FromAS = FromRecordType.getAddressSpace();
3014 LangAS DestAS = DestRecordType.getAddressSpace();
3015 if (FromAS != DestAS) {
3016 QualType FromRecordTypeWithoutAS =
3017 Context.removeAddrSpaceQualType(FromRecordType);
3018 QualType FromTypeWithDestAS =
3019 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3020 if (PointerConversions)
3021 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3022 From = ImpCastExprToType(From, FromTypeWithDestAS,
3023 CK_AddressSpaceConversion, From->getValueKind())
3024 .get();
3025 }
3026 } else {
3027 // No conversion necessary.
3028 return From;
3029 }
3030
3031 if (DestType->isDependentType() || FromType->isDependentType())
3032 return From;
3033
3034 // If the unqualified types are the same, no conversion is necessary.
3035 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3036 return From;
3037
3038 SourceRange FromRange = From->getSourceRange();
3039 SourceLocation FromLoc = FromRange.getBegin();
3040
3041 ExprValueKind VK = From->getValueKind();
3042
3043 // C++ [class.member.lookup]p8:
3044 // [...] Ambiguities can often be resolved by qualifying a name with its
3045 // class name.
3046 //
3047 // If the member was a qualified name and the qualified referred to a
3048 // specific base subobject type, we'll cast to that intermediate type
3049 // first and then to the object in which the member is declared. That allows
3050 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3051 //
3052 // class Base { public: int x; };
3053 // class Derived1 : public Base { };
3054 // class Derived2 : public Base { };
3055 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3056 //
3057 // void VeryDerived::f() {
3058 // x = 17; // error: ambiguous base subobjects
3059 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3060 // }
3061 if (Qualifier && Qualifier->getAsType()) {
3062 QualType QType = QualType(Qualifier->getAsType(), 0);
3063 assert(QType->isRecordType() && "lookup done with non-record type");
3064
3065 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3066
3067 // In C++98, the qualifier type doesn't actually have to be a base
3068 // type of the object type, in which case we just ignore it.
3069 // Otherwise build the appropriate casts.
3070 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3071 CXXCastPath BasePath;
3072 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3073 FromLoc, FromRange, &BasePath))
3074 return ExprError();
3075
3076 if (PointerConversions)
3077 QType = Context.getPointerType(QType);
3078 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3079 VK, &BasePath).get();
3080
3081 FromType = QType;
3082 FromRecordType = QRecordType;
3083
3084 // If the qualifier type was the same as the destination type,
3085 // we're done.
3086 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3087 return From;
3088 }
3089 }
3090
3091 CXXCastPath BasePath;
3092 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3093 FromLoc, FromRange, &BasePath,
3094 /*IgnoreAccess=*/true))
3095 return ExprError();
3096
3097 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3098 VK, &BasePath);
3099}
3100
3102 const LookupResult &R,
3103 bool HasTrailingLParen) {
3104 // Only when used directly as the postfix-expression of a call.
3105 if (!HasTrailingLParen)
3106 return false;
3107
3108 // Never if a scope specifier was provided.
3109 if (SS.isNotEmpty())
3110 return false;
3111
3112 // Only in C++ or ObjC++.
3113 if (!getLangOpts().CPlusPlus)
3114 return false;
3115
3116 // Turn off ADL when we find certain kinds of declarations during
3117 // normal lookup:
3118 for (const NamedDecl *D : R) {
3119 // C++0x [basic.lookup.argdep]p3:
3120 // -- a declaration of a class member
3121 // Since using decls preserve this property, we check this on the
3122 // original decl.
3123 if (D->isCXXClassMember())
3124 return false;
3125
3126 // C++0x [basic.lookup.argdep]p3:
3127 // -- a block-scope function declaration that is not a
3128 // using-declaration
3129 // NOTE: we also trigger this for function templates (in fact, we
3130 // don't check the decl type at all, since all other decl types
3131 // turn off ADL anyway).
3132 if (isa<UsingShadowDecl>(D))
3133 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3135 return false;
3136
3137 // C++0x [basic.lookup.argdep]p3:
3138 // -- a declaration that is neither a function or a function
3139 // template
3140 // And also for builtin functions.
3141 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3142 // But also builtin functions.
3143 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3144 return false;
3145 } else if (!isa<FunctionTemplateDecl>(D))
3146 return false;
3147 }
3148
3149 return true;
3150}
3151
3152
3153/// Diagnoses obvious problems with the use of the given declaration
3154/// as an expression. This is only actually called for lookups that
3155/// were not overloaded, and it doesn't promise that the declaration
3156/// will in fact be used.
3158 bool AcceptInvalid) {
3159 if (D->isInvalidDecl() && !AcceptInvalid)
3160 return true;
3161
3162 if (isa<TypedefNameDecl>(D)) {
3163 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3164 return true;
3165 }
3166
3167 if (isa<ObjCInterfaceDecl>(D)) {
3168 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3169 return true;
3170 }
3171
3172 if (isa<NamespaceDecl>(D)) {
3173 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3174 return true;
3175 }
3176
3177 return false;
3178}
3179
3180// Certain multiversion types should be treated as overloaded even when there is
3181// only one result.
3183 assert(R.isSingleResult() && "Expected only a single result");
3184 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3185 return FD &&
3186 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3187}
3188
3190 LookupResult &R, bool NeedsADL,
3191 bool AcceptInvalidDecl) {
3192 // If this is a single, fully-resolved result and we don't need ADL,
3193 // just build an ordinary singleton decl ref.
3194 if (!NeedsADL && R.isSingleResult() &&
3198 R.getRepresentativeDecl(), nullptr,
3199 AcceptInvalidDecl);
3200
3201 // We only need to check the declaration if there's exactly one
3202 // result, because in the overloaded case the results can only be
3203 // functions and function templates.
3205 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3206 AcceptInvalidDecl))
3207 return ExprError();
3208
3209 // Otherwise, just build an unresolved lookup expression. Suppress
3210 // any lookup-related diagnostics; we'll hash these out later, when
3211 // we've picked a target.
3213
3216 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3217 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
3218
3219 return ULE;
3220}
3221
3223 SourceLocation loc,
3224 ValueDecl *var);
3225
3227 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3228 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3229 bool AcceptInvalidDecl) {
3230 assert(D && "Cannot refer to a NULL declaration");
3231 assert(!isa<FunctionTemplateDecl>(D) &&
3232 "Cannot refer unambiguously to a function template");
3233
3234 SourceLocation Loc = NameInfo.getLoc();
3235 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3236 // Recovery from invalid cases (e.g. D is an invalid Decl).
3237 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3238 // diagnostics, as invalid decls use int as a fallback type.
3239 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3240 }
3241
3242 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
3243 // Specifically diagnose references to class templates that are missing
3244 // a template argument list.
3245 diagnoseMissingTemplateArguments(SS, /*TemplateKeyword=*/false, TD, Loc);
3246 return ExprError();
3247 }
3248
3249 // Make sure that we're referring to a value.
3250 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3251 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3252 Diag(D->getLocation(), diag::note_declared_at);
3253 return ExprError();
3254 }
3255
3256 // Check whether this declaration can be used. Note that we suppress
3257 // this check when we're going to perform argument-dependent lookup
3258 // on this function name, because this might not be the function
3259 // that overload resolution actually selects.
3260 if (DiagnoseUseOfDecl(D, Loc))
3261 return ExprError();
3262
3263 auto *VD = cast<ValueDecl>(D);
3264
3265 // Only create DeclRefExpr's for valid Decl's.
3266 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3267 return ExprError();
3268
3269 // Handle members of anonymous structs and unions. If we got here,
3270 // and the reference is to a class member indirect field, then this
3271 // must be the subject of a pointer-to-member expression.
3272 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3273 IndirectField && !IndirectField->isCXXClassMember())
3275 IndirectField);
3276
3277 QualType type = VD->getType();
3278 if (type.isNull())
3279 return ExprError();
3280 ExprValueKind valueKind = VK_PRValue;
3281
3282 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3283 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3284 // is expanded by some outer '...' in the context of the use.
3285 type = type.getNonPackExpansionType();
3286
3287 switch (D->getKind()) {
3288 // Ignore all the non-ValueDecl kinds.
3289#define ABSTRACT_DECL(kind)
3290#define VALUE(type, base)
3291#define DECL(type, base) case Decl::type:
3292#include "clang/AST/DeclNodes.inc"
3293 llvm_unreachable("invalid value decl kind");
3294
3295 // These shouldn't make it here.
3296 case Decl::ObjCAtDefsField:
3297 llvm_unreachable("forming non-member reference to ivar?");
3298
3299 // Enum constants are always r-values and never references.
3300 // Unresolved using declarations are dependent.
3301 case Decl::EnumConstant:
3302 case Decl::UnresolvedUsingValue:
3303 case Decl::OMPDeclareReduction:
3304 case Decl::OMPDeclareMapper:
3305 valueKind = VK_PRValue;
3306 break;
3307
3308 // Fields and indirect fields that got here must be for
3309 // pointer-to-member expressions; we just call them l-values for
3310 // internal consistency, because this subexpression doesn't really
3311 // exist in the high-level semantics.
3312 case Decl::Field:
3313 case Decl::IndirectField:
3314 case Decl::ObjCIvar:
3315 assert((getLangOpts().CPlusPlus || isAttrContext()) &&
3316 "building reference to field in C?");
3317
3318 // These can't have reference type in well-formed programs, but
3319 // for internal consistency we do this anyway.
3320 type = type.getNonReferenceType();
3321 valueKind = VK_LValue;
3322 break;
3323
3324 // Non-type template parameters are either l-values or r-values
3325 // depending on the type.
3326 case Decl::NonTypeTemplateParm: {
3327 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3328 type = reftype->getPointeeType();
3329 valueKind = VK_LValue; // even if the parameter is an r-value reference
3330 break;
3331 }
3332
3333 // [expr.prim.id.unqual]p2:
3334 // If the entity is a template parameter object for a template
3335 // parameter of type T, the type of the expression is const T.
3336 // [...] The expression is an lvalue if the entity is a [...] template
3337 // parameter object.
3338 if (type->isRecordType()) {
3339 type = type.getUnqualifiedType().withConst();
3340 valueKind = VK_LValue;
3341 break;
3342 }
3343
3344 // For non-references, we need to strip qualifiers just in case
3345 // the template parameter was declared as 'const int' or whatever.
3346 valueKind = VK_PRValue;
3347 type = type.getUnqualifiedType();
3348 break;
3349 }
3350
3351 case Decl::Var:
3352 case Decl::VarTemplateSpecialization:
3353 case Decl::VarTemplatePartialSpecialization:
3354 case Decl::Decomposition:
3355 case Decl::Binding:
3356 case Decl::OMPCapturedExpr:
3357 // In C, "extern void blah;" is valid and is an r-value.
3358 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3359 type->isVoidType()) {
3360 valueKind = VK_PRValue;
3361 break;
3362 }
3363 [[fallthrough]];
3364
3365 case Decl::ImplicitParam:
3366 case Decl::ParmVar: {
3367 // These are always l-values.
3368 valueKind = VK_LValue;
3369 type = type.getNonReferenceType();
3370
3371 // FIXME: Does the addition of const really only apply in
3372 // potentially-evaluated contexts? Since the variable isn't actually
3373 // captured in an unevaluated context, it seems that the answer is no.
3374 if (!isUnevaluatedContext()) {
3375 QualType CapturedType = getCapturedDeclRefType(cast<ValueDecl>(VD), Loc);
3376 if (!CapturedType.isNull())
3377 type = CapturedType;
3378 }
3379 break;
3380 }
3381
3382 case Decl::Function: {
3383 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3386 valueKind = VK_PRValue;
3387 break;
3388 }
3389 }
3390
3391 const FunctionType *fty = type->castAs<FunctionType>();
3392
3393 // If we're referring to a function with an __unknown_anytype
3394 // result type, make the entire expression __unknown_anytype.
3395 if (fty->getReturnType() == Context.UnknownAnyTy) {
3397 valueKind = VK_PRValue;
3398 break;
3399 }
3400
3401 // Functions are l-values in C++.
3402 if (getLangOpts().CPlusPlus) {
3403 valueKind = VK_LValue;
3404 break;
3405 }
3406
3407 // C99 DR 316 says that, if a function type comes from a
3408 // function definition (without a prototype), that type is only
3409 // used for checking compatibility. Therefore, when referencing
3410 // the function, we pretend that we don't have the full function
3411 // type.
3412 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3414 fty->getExtInfo());
3415
3416 // Functions are r-values in C.
3417 valueKind = VK_PRValue;
3418 break;
3419 }
3420
3421 case Decl::CXXDeductionGuide:
3422 llvm_unreachable("building reference to deduction guide");
3423
3424 case Decl::MSProperty:
3425 case Decl::MSGuid:
3426 case Decl::TemplateParamObject:
3427 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3428 // capture in OpenMP, or duplicated between host and device?
3429 valueKind = VK_LValue;
3430 break;
3431
3432 case Decl::UnnamedGlobalConstant:
3433 valueKind = VK_LValue;
3434 break;
3435
3436 case Decl::CXXMethod:
3437 // If we're referring to a method with an __unknown_anytype
3438 // result type, make the entire expression __unknown_anytype.
3439 // This should only be possible with a type written directly.
3440 if (const FunctionProtoType *proto =
3441 dyn_cast<FunctionProtoType>(VD->getType()))
3442 if (proto->getReturnType() == Context.UnknownAnyTy) {
3444 valueKind = VK_PRValue;
3445 break;
3446 }
3447
3448 // C++ methods are l-values if static, r-values if non-static.
3449 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3450 valueKind = VK_LValue;
3451 break;
3452 }
3453 [[fallthrough]];
3454
3455 case Decl::CXXConversion:
3456 case Decl::CXXDestructor:
3457 case Decl::CXXConstructor:
3458 valueKind = VK_PRValue;
3459 break;
3460 }
3461
3462 auto *E =
3463 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3464 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3465 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3466 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3467 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3468 // diagnostics).
3469 if (VD->isInvalidDecl() && E)
3470 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3471 return E;
3472}
3473
3474static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3476 Target.resize(CharByteWidth * (Source.size() + 1));
3477 char *ResultPtr = &Target[0];
3478 const llvm::UTF8 *ErrorPtr;
3479 bool success =
3480 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3481 (void)success;
3482 assert(success);
3483 Target.resize(ResultPtr - &Target[0]);
3484}
3485
3488 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3489 if (!currentDecl) {
3490 Diag(Loc, diag::ext_predef_outside_function);
3491 currentDecl = Context.getTranslationUnitDecl();
3492 }
3493
3494 QualType ResTy;
3495 StringLiteral *SL = nullptr;
3496 if (cast<DeclContext>(currentDecl)->isDependentContext())
3497 ResTy = Context.DependentTy;
3498 else {
3499 // Pre-defined identifiers are of type char[x], where x is the length of
3500 // the string.
3501 bool ForceElaboratedPrinting =
3502 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3503 auto Str =
3504 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3505 unsigned Length = Str.length();
3506
3507 llvm::APInt LengthI(32, Length + 1);
3510 ResTy =
3512 SmallString<32> RawChars;
3514 Str, RawChars);
3515 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3517 /*IndexTypeQuals*/ 0);
3519 /*Pascal*/ false, ResTy, Loc);
3520 } else {
3522 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3524 /*IndexTypeQuals*/ 0);
3526 /*Pascal*/ false, ResTy, Loc);
3527 }
3528 }
3529
3530 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3531 SL);
3532}
3533
3536}
3537
3539 SmallString<16> CharBuffer;
3540 bool Invalid = false;
3541 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3542 if (Invalid)
3543 return ExprError();
3544
3545 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3546 PP, Tok.getKind());
3547 if (Literal.hadError())
3548 return ExprError();
3549
3550 QualType Ty;
3551 if (Literal.isWide())
3552 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3553 else if (Literal.isUTF8() && getLangOpts().C23)
3554 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3555 else if (Literal.isUTF8() && getLangOpts().Char8)
3556 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3557 else if (Literal.isUTF16())
3558 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3559 else if (Literal.isUTF32())
3560 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3561 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3562 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3563 else
3564 Ty = Context.CharTy; // 'x' -> char in C++;
3565 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3566
3568 if (Literal.isWide())
3570 else if (Literal.isUTF16())
3572 else if (Literal.isUTF32())
3574 else if (Literal.isUTF8())
3576
3577 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3578 Tok.getLocation());
3579
3580 if (Literal.getUDSuffix().empty())
3581 return Lit;
3582
3583 // We're building a user-defined literal.
3584 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3585 SourceLocation UDSuffixLoc =
3586 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3587
3588 // Make sure we're allowed user-defined literals here.
3589 if (!UDLScope)
3590 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3591
3592 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3593 // operator "" X (ch)
3594 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3595 Lit, Tok.getLocation());
3596}
3597
3599 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3601 llvm::APInt(IntSize, Val, /*isSigned=*/true),
3602 Context.IntTy, Loc);
3603}
3604
3607 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3608
3609 using llvm::APFloat;
3610 APFloat Val(Format);
3611
3612 llvm::RoundingMode RM = S.CurFPFeatures.getRoundingMode();
3613 if (RM == llvm::RoundingMode::Dynamic)
3614 RM = llvm::RoundingMode::NearestTiesToEven;
3615 APFloat::opStatus result = Literal.GetFloatValue(Val, RM);
3616
3617 // Overflow is always an error, but underflow is only an error if
3618 // we underflowed to zero (APFloat reports denormals as underflow).
3619 if ((result & APFloat::opOverflow) ||
3620 ((result & APFloat::opUnderflow) && Val.isZero())) {
3621 unsigned diagnostic;
3622 SmallString<20> buffer;
3623 if (result & APFloat::opOverflow) {
3624 diagnostic = diag::warn_float_overflow;
3625 APFloat::getLargest(Format).toString(buffer);
3626 } else {
3627 diagnostic = diag::warn_float_underflow;
3628 APFloat::getSmallest(Format).toString(buffer);
3629 }
3630
3631 S.Diag(Loc, diagnostic) << Ty << buffer.str();
3632 }
3633
3634 bool isExact = (result == APFloat::opOK);
3635 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3636}
3637
3639 assert(E && "Invalid expression");
3640
3641 if (E->isValueDependent())
3642 return false;
3643
3644 QualType QT = E->getType();
3645 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3646 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3647 return true;
3648 }
3649
3650 llvm::APSInt ValueAPS;
3652
3653 if (R.isInvalid())
3654 return true;
3655
3656 // GCC allows the value of unroll count to be 0.
3657 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3658 // "The values of 0 and 1 block any unrolling of the loop."
3659 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3660 // '#pragma unroll' cases.
3661 bool ValueIsPositive =
3662 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3663 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3664 Diag(E->getExprLoc(), diag::err_requires_positive_value)
3665 << toString(ValueAPS, 10) << ValueIsPositive;
3666 return true;
3667 }
3668
3669 return false;
3670}
3671
3673 // Fast path for a single digit (which is quite common). A single digit
3674 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3675 if (Tok.getLength() == 1 || Tok.getKind() == tok::binary_data) {
3676 const uint8_t Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3677 return ActOnIntegerConstant(Tok.getLocation(), Val);
3678 }
3679
3680 SmallString<128> SpellingBuffer;
3681 // NumericLiteralParser wants to overread by one character. Add padding to
3682 // the buffer in case the token is copied to the buffer. If getSpelling()
3683 // returns a StringRef to the memory buffer, it should have a null char at
3684 // the EOF, so it is also safe.
3685 SpellingBuffer.resize(Tok.getLength() + 1);
3686
3687 // Get the spelling of the token, which eliminates trigraphs, etc.
3688 bool Invalid = false;
3689 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3690 if (Invalid)
3691 return ExprError();
3692
3693 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3696 if (Literal.hadError)
3697 return ExprError();
3698
3699 if (Literal.hasUDSuffix()) {
3700 // We're building a user-defined literal.
3701 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3702 SourceLocation UDSuffixLoc =
3703 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3704
3705 // Make sure we're allowed user-defined literals here.
3706 if (!UDLScope)
3707 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3708
3709 QualType CookedTy;
3710 if (Literal.isFloatingLiteral()) {
3711 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3712 // long double, the literal is treated as a call of the form
3713 // operator "" X (f L)
3714 CookedTy = Context.LongDoubleTy;
3715 } else {
3716 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3717 // unsigned long long, the literal is treated as a call of the form
3718 // operator "" X (n ULL)
3719 CookedTy = Context.UnsignedLongLongTy;
3720 }
3721
3722 DeclarationName OpName =
3724 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3725 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3726
3727 SourceLocation TokLoc = Tok.getLocation();
3728
3729 // Perform literal operator lookup to determine if we're building a raw
3730 // literal or a cooked one.
3731 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3732 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3733 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3734 /*AllowStringTemplatePack*/ false,
3735 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3737 // Lookup failure for imaginary constants isn't fatal, there's still the
3738 // GNU extension producing _Complex types.
3739 break;
3740 case LOLR_Error:
3741 return ExprError();
3742 case LOLR_Cooked: {
3743 Expr *Lit;
3744 if (Literal.isFloatingLiteral()) {
3745 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3746 } else {
3747 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3748 if (Literal.GetIntegerValue(ResultVal))
3749 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3750 << /* Unsigned */ 1;
3751 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3752 Tok.getLocation());
3753 }
3754 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3755 }
3756
3757 case LOLR_Raw: {
3758 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3759 // literal is treated as a call of the form
3760 // operator "" X ("n")
3761 unsigned Length = Literal.getUDSuffixOffset();
3764 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
3765 Expr *Lit =
3766 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
3768 /*Pascal*/ false, StrTy, &TokLoc, 1);
3769 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3770 }
3771
3772 case LOLR_Template: {
3773 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3774 // template), L is treated as a call fo the form
3775 // operator "" X <'c1', 'c2', ... 'ck'>()
3776 // where n is the source character sequence c1 c2 ... ck.
3777 TemplateArgumentListInfo ExplicitArgs;
3778 unsigned CharBits = Context.getIntWidth(Context.CharTy);
3779 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3780 llvm::APSInt Value(CharBits, CharIsUnsigned);
3781 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3782 Value = TokSpelling[I];
3785 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3786 }
3787 return BuildLiteralOperatorCall(R, OpNameInfo, {}, TokLoc, &ExplicitArgs);
3788 }
3790 llvm_unreachable("unexpected literal operator lookup result");
3791 }
3792 }
3793
3794 Expr *Res;
3795
3796 if (Literal.isFixedPointLiteral()) {
3797 QualType Ty;
3798
3799 if (Literal.isAccum) {
3800 if (Literal.isHalf) {
3801 Ty = Context.ShortAccumTy;
3802 } else if (Literal.isLong) {
3803 Ty = Context.LongAccumTy;
3804 } else {
3805 Ty = Context.AccumTy;
3806 }
3807 } else if (Literal.isFract) {
3808 if (Literal.isHalf) {
3809 Ty = Context.ShortFractTy;
3810 } else if (Literal.isLong) {
3811 Ty = Context.LongFractTy;
3812 } else {
3813 Ty = Context.FractTy;
3814 }
3815 }
3816
3817 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3818
3819 bool isSigned = !Literal.isUnsigned;
3820 unsigned scale = Context.getFixedPointScale(Ty);
3821 unsigned bit_width = Context.getTypeInfo(Ty).Width;
3822
3823 llvm::APInt Val(bit_width, 0, isSigned);
3824 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3825 bool ValIsZero = Val.isZero() && !Overflowed;
3826
3827 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3828 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3829 // Clause 6.4.4 - The value of a constant shall be in the range of
3830 // representable values for its type, with exception for constants of a
3831 // fract type with a value of exactly 1; such a constant shall denote
3832 // the maximal value for the type.
3833 --Val;
3834 else if (Val.ugt(MaxVal) || Overflowed)
3835 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3836
3838 Tok.getLocation(), scale);
3839 } else if (Literal.isFloatingLiteral()) {
3840 QualType Ty;
3841 if (Literal.isHalf){
3842 if (getLangOpts().HLSL ||
3843 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3844 Ty = Context.HalfTy;
3845 else {
3846 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3847 return ExprError();
3848 }
3849 } else if (Literal.isFloat)
3850 Ty = Context.FloatTy;
3851 else if (Literal.isLong)
3853 else if (Literal.isFloat16)
3854 Ty = Context.Float16Ty;
3855 else if (Literal.isFloat128)
3856 Ty = Context.Float128Ty;
3857 else if (getLangOpts().HLSL)
3858 Ty = Context.FloatTy;
3859 else
3860 Ty = Context.DoubleTy;
3861
3862 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3863
3864 if (Ty == Context.DoubleTy) {
3865 if (getLangOpts().SinglePrecisionConstants) {
3866 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
3867 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3868 }
3869 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
3870 "cl_khr_fp64", getLangOpts())) {
3871 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3872 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
3874 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3875 }
3876 }
3877 } else if (!Literal.isIntegerLiteral()) {
3878 return ExprError();
3879 } else {
3880 QualType Ty;
3881
3882 // 'z/uz' literals are a C++23 feature.
3883 if (Literal.isSizeT)
3886 ? diag::warn_cxx20_compat_size_t_suffix
3887 : diag::ext_cxx23_size_t_suffix
3888 : diag::err_cxx23_size_t_suffix);
3889
3890 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
3891 // but we do not currently support the suffix in C++ mode because it's not
3892 // entirely clear whether WG21 will prefer this suffix to return a library
3893 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
3894 // literals are a C++ extension.
3895 if (Literal.isBitInt)
3896 PP.Diag(Tok.getLocation(),
3897 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
3898 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
3899 : diag::ext_c23_bitint_suffix);
3900
3901 // Get the value in the widest-possible width. What is "widest" depends on
3902 // whether the literal is a bit-precise integer or not. For a bit-precise
3903 // integer type, try to scan the source to determine how many bits are
3904 // needed to represent the value. This may seem a bit expensive, but trying
3905 // to get the integer value from an overly-wide APInt is *extremely*
3906 // expensive, so the naive approach of assuming
3907 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3908 unsigned BitsNeeded =
3909 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
3910 Literal.getLiteralDigits(), Literal.getRadix())
3912 llvm::APInt ResultVal(BitsNeeded, 0);
3913
3914 if (Literal.GetIntegerValue(ResultVal)) {
3915 // If this value didn't fit into uintmax_t, error and force to ull.
3916 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3917 << /* Unsigned */ 1;
3919 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3920 "long long is not intmax_t?");
3921 } else {
3922 // If this value fits into a ULL, try to figure out what else it fits into
3923 // according to the rules of C99 6.4.4.1p5.
3924
3925 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3926 // be an unsigned int.
3927 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3928
3929 // HLSL doesn't really have `long` or `long long`. We support the `ll`
3930 // suffix for portability of code with C++, but both `l` and `ll` are
3931 // 64-bit integer types, and we want the type of `1l` and `1ll` to be the
3932 // same.
3933 if (getLangOpts().HLSL && !Literal.isLong && Literal.isLongLong) {
3934 Literal.isLong = true;
3935 Literal.isLongLong = false;
3936 }
3937
3938 // Check from smallest to largest, picking the smallest type we can.
3939 unsigned Width = 0;
3940
3941 // Microsoft specific integer suffixes are explicitly sized.
3942 if (Literal.MicrosoftInteger) {
3943 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3944 Width = 8;
3945 Ty = Context.CharTy;
3946 } else {
3947 Width = Literal.MicrosoftInteger;
3948 Ty = Context.getIntTypeForBitwidth(Width,
3949 /*Signed=*/!Literal.isUnsigned);
3950 }
3951 }
3952
3953 // Bit-precise integer literals are automagically-sized based on the
3954 // width required by the literal.
3955 if (Literal.isBitInt) {
3956 // The signed version has one more bit for the sign value. There are no
3957 // zero-width bit-precise integers, even if the literal value is 0.
3958 Width = std::max(ResultVal.getActiveBits(), 1u) +
3959 (Literal.isUnsigned ? 0u : 1u);
3960
3961 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
3962 // and reset the type to the largest supported width.
3963 unsigned int MaxBitIntWidth =
3965 if (Width > MaxBitIntWidth) {
3966 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3967 << Literal.isUnsigned;
3968 Width = MaxBitIntWidth;
3969 }
3970
3971 // Reset the result value to the smaller APInt and select the correct
3972 // type to be used. Note, we zext even for signed values because the
3973 // literal itself is always an unsigned value (a preceeding - is a
3974 // unary operator, not part of the literal).
3975 ResultVal = ResultVal.zextOrTrunc(Width);
3976 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
3977 }
3978
3979 // Check C++23 size_t literals.
3980 if (Literal.isSizeT) {
3981 assert(!Literal.MicrosoftInteger &&
3982 "size_t literals can't be Microsoft literals");
3983 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
3985
3986 // Does it fit in size_t?
3987 if (ResultVal.isIntN(SizeTSize)) {
3988 // Does it fit in ssize_t?
3989 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
3991 else if (AllowUnsigned)
3992 Ty = Context.getSizeType();
3993 Width = SizeTSize;
3994 }
3995 }
3996
3997 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
3998 !Literal.isSizeT) {
3999 // Are int/unsigned possibilities?
4000 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4001
4002 // Does it fit in a unsigned int?
4003 if (ResultVal.isIntN(IntSize)) {
4004 // Does it fit in a signed int?
4005 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4006 Ty = Context.IntTy;
4007 else if (AllowUnsigned)
4009 Width = IntSize;
4010 }
4011 }
4012
4013 // Are long/unsigned long possibilities?
4014 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4015 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4016
4017 // Does it fit in a unsigned long?
4018 if (ResultVal.isIntN(LongSize)) {
4019 // Does it fit in a signed long?
4020 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4021 Ty = Context.LongTy;
4022 else if (AllowUnsigned)
4024 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4025 // is compatible.
4026 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4027 const unsigned LongLongSize =
4029 Diag(Tok.getLocation(),
4031 ? Literal.isLong
4032 ? diag::warn_old_implicitly_unsigned_long_cxx
4033 : /*C++98 UB*/ diag::
4034 ext_old_implicitly_unsigned_long_cxx
4035 : diag::warn_old_implicitly_unsigned_long)
4036 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4037 : /*will be ill-formed*/ 1);
4039 }
4040 Width = LongSize;
4041 }
4042 }
4043
4044 // Check long long if needed.
4045 if (Ty.isNull() && !Literal.isSizeT) {
4046 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4047
4048 // Does it fit in a unsigned long long?
4049 if (ResultVal.isIntN(LongLongSize)) {
4050 // Does it fit in a signed long long?
4051 // To be compatible with MSVC, hex integer literals ending with the
4052 // LL or i64 suffix are always signed in Microsoft mode.
4053 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4054 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4055 Ty = Context.LongLongTy;
4056 else if (AllowUnsigned)
4058 Width = LongLongSize;
4059
4060 // 'long long' is a C99 or C++11 feature, whether the literal
4061 // explicitly specified 'long long' or we needed the extra width.
4062 if (getLangOpts().CPlusPlus)
4063 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4064 ? diag::warn_cxx98_compat_longlong
4065 : diag::ext_cxx11_longlong);
4066 else if (!getLangOpts().C99)
4067 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4068 }
4069 }
4070
4071 // If we still couldn't decide a type, we either have 'size_t' literal
4072 // that is out of range, or a decimal literal that does not fit in a
4073 // signed long long and has no U suffix.
4074 if (Ty.isNull()) {
4075 if (Literal.isSizeT)
4076 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4077 << Literal.isUnsigned;
4078 else
4079 Diag(Tok.getLocation(),
4080 diag::ext_integer_literal_too_large_for_signed);
4083 }
4084
4085 if (ResultVal.getBitWidth() != Width)
4086 ResultVal = ResultVal.trunc(Width);
4087 }
4088 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4089 }
4090
4091 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4092 if (Literal.isImaginary) {
4093 Res = new (Context) ImaginaryLiteral(Res,
4095
4096 // In C++, this is a GNU extension. In C, it's a C2y extension.
4097 unsigned DiagId;
4098 if (getLangOpts().CPlusPlus)
4099 DiagId = diag::ext_gnu_imaginary_constant;
4100 else if (getLangOpts().C2y)
4101 DiagId = diag::warn_c23_compat_imaginary_constant;
4102 else
4103 DiagId = diag::ext_c2y_imaginary_constant;
4104 Diag(Tok.getLocation(), DiagId);
4105 }
4106 return Res;
4107}
4108
4110 assert(E && "ActOnParenExpr() missing expr");
4111 QualType ExprTy = E->getType();
4112 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4113 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4114 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4115 return new (Context) ParenExpr(L, R, E);
4116}
4117
4120 SourceRange ArgRange) {
4121 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4122 // scalar or vector data type argument..."
4123 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4124 // type (C99 6.2.5p18) or void.
4125 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4126 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4127 << T << ArgRange;
4128 return true;
4129 }
4130
4131 assert((T->isVoidType() || !T->isIncompleteType()) &&
4132 "Scalar types should always be complete");
4133 return false;
4134}
4135
4138 SourceRange ArgRange) {
4139 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4140 if (!T->isVectorType() && !T->isSizelessVectorType())
4141 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4142 << ""
4143 << "__builtin_vectorelements" << T << ArgRange;
4144
4145 return false;
4146}
4147
4150 SourceRange ArgRange) {
4151 if (S.checkPointerAuthEnabled(Loc, ArgRange))
4152 return true;
4153
4154 if (!T->isFunctionType() && !T->isFunctionPointerType() &&
4156 S.Diag(Loc, diag::err_ptrauth_type_disc_undiscriminated) << T << ArgRange;
4157 return true;
4158 }
4159
4160 return false;
4161}
4162
4165 SourceRange ArgRange,
4166 UnaryExprOrTypeTrait TraitKind) {
4167 // Invalid types must be hard errors for SFINAE in C++.
4168 if (S.LangOpts.CPlusPlus)
4169 return true;
4170
4171 // C99 6.5.3.4p1:
4172 if (T->isFunctionType() &&
4173 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4174 TraitKind == UETT_PreferredAlignOf)) {
4175 // sizeof(function)/alignof(function) is allowed as an extension.
4176 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4177 << getTraitSpelling(TraitKind) << ArgRange;
4178 return false;
4179 }
4180
4181 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4182 // this is an error (OpenCL v1.1 s6.3.k)
4183 if (T->isVoidType()) {
4184 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4185 : diag::ext_sizeof_alignof_void_type;
4186 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4187 return false;
4188 }
4189
4190 return true;
4191}
4192
4195 SourceRange ArgRange,
4196 UnaryExprOrTypeTrait TraitKind) {
4197 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4198 // runtime doesn't allow it.
4200 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4201 << T << (TraitKind == UETT_SizeOf)
4202 << ArgRange;
4203 return true;
4204 }
4205
4206 return false;
4207}
4208
4209/// Check whether E is a pointer from a decayed array type (the decayed
4210/// pointer type is equal to T) and emit a warning if it is.
4212 const Expr *E) {
4213 // Don't warn if the operation changed the type.
4214 if (T != E->getType())
4215 return;
4216
4217 // Now look for array decays.
4218 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4219 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4220 return;
4221
4222 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4223 << ICE->getType()
4224 << ICE->getSubExpr()->getType();
4225}
4226
4228 UnaryExprOrTypeTrait ExprKind) {
4229 QualType ExprTy = E->getType();
4230 assert(!ExprTy->isReferenceType());
4231
4232 bool IsUnevaluatedOperand =
4233 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4234 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4235 ExprKind == UETT_VecStep);
4236 if (IsUnevaluatedOperand) {
4238 if (Result.isInvalid())
4239 return true;
4240 E = Result.get();
4241 }
4242
4243 // The operand for sizeof and alignof is in an unevaluated expression context,
4244 // so side effects could result in unintended consequences.
4245 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4246 // used to build SFINAE gadgets.
4247 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4248 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4250 !E->getType()->isVariableArrayType() &&
4251 E->HasSideEffects(Context, false))
4252 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4253
4254 if (ExprKind == UETT_VecStep)
4255 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4256 E->getSourceRange());
4257
4258 if (ExprKind == UETT_VectorElements)
4259 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4260 E->getSourceRange());
4261
4262 // Explicitly list some types as extensions.
4263 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4264 E->getSourceRange(), ExprKind))
4265 return false;
4266
4267 // WebAssembly tables are always illegal operands to unary expressions and
4268 // type traits.
4269 if (Context.getTargetInfo().getTriple().isWasm() &&
4271 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4272 << getTraitSpelling(ExprKind);
4273 return true;
4274 }
4275
4276 // 'alignof' applied to an expression only requires the base element type of
4277 // the expression to be complete. 'sizeof' requires the expression's type to
4278 // be complete (and will attempt to complete it if it's an array of unknown
4279 // bound).
4280 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4283 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4284 getTraitSpelling(ExprKind), E->getSourceRange()))
4285 return true;
4286 } else {
4288 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4289 getTraitSpelling(ExprKind), E->getSourceRange()))
4290 return true;
4291 }
4292
4293 // Completing the expression's type may have changed it.
4294 ExprTy = E->getType();
4295 assert(!ExprTy->isReferenceType());
4296
4297 if (ExprTy->isFunctionType()) {
4298 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4299 << getTraitSpelling(ExprKind) << E->getSourceRange();
4300 return true;
4301 }
4302
4303 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4304 E->getSourceRange(), ExprKind))
4305 return true;
4306
4307 if (ExprKind == UETT_SizeOf) {
4308 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4309 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4310 QualType OType = PVD->getOriginalType();
4311 QualType Type = PVD->getType();
4312 if (Type->isPointerType() && OType->isArrayType()) {
4313 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4314 << Type << OType;
4315 Diag(PVD->getLocation(), diag::note_declared_at);
4316 }
4317 }
4318 }
4319
4320 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4321 // decays into a pointer and returns an unintended result. This is most
4322 // likely a typo for "sizeof(array) op x".
4323 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4324 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4325 BO->getLHS());
4326 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4327 BO->getRHS());
4328 }
4329 }
4330
4331 return false;
4332}
4333
4334static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4335 // Cannot know anything else if the expression is dependent.
4336 if (E->isTypeDependent())
4337 return false;
4338
4339 if (E->getObjectKind() == OK_BitField) {
4340 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4341 << 1 << E->getSourceRange();
4342 return true;
4343 }
4344
4345 ValueDecl *D = nullptr;
4346 Expr *Inner = E->IgnoreParens();
4347 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4348 D = DRE->getDecl();
4349 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4350 D = ME->getMemberDecl();
4351 }
4352
4353 // If it's a field, require the containing struct to have a
4354 // complete definition so that we can compute the layout.
4355 //
4356 // This can happen in C++11 onwards, either by naming the member
4357 // in a way that is not transformed into a member access expression
4358 // (in an unevaluated operand, for instance), or by naming the member
4359 // in a trailing-return-type.
4360 //
4361 // For the record, since __alignof__ on expressions is a GCC
4362 // extension, GCC seems to permit this but always gives the
4363 // nonsensical answer 0.
4364 //
4365 // We don't really need the layout here --- we could instead just
4366 // directly check for all the appropriate alignment-lowing
4367 // attributes --- but that would require duplicating a lot of
4368 // logic that just isn't worth duplicating for such a marginal
4369 // use-case.
4370 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4371 // Fast path this check, since we at least know the record has a
4372 // definition if we can find a member of it.
4373 if (!FD->getParent()->isCompleteDefinition()) {
4374 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4375 << E->getSourceRange();
4376 return true;
4377 }
4378
4379 // Otherwise, if it's a field, and the field doesn't have
4380 // reference type, then it must have a complete type (or be a
4381 // flexible array member, which we explicitly want to
4382 // white-list anyway), which makes the following checks trivial.
4383 if (!FD->getType()->isReferenceType())
4384 return false;
4385 }
4386
4387 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4388}
4389
4391 E = E->IgnoreParens();
4392
4393 // Cannot know anything else if the expression is dependent.
4394 if (E->isTypeDependent())
4395 return false;
4396
4397 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4398}
4399
4401 CapturingScopeInfo *CSI) {
4402 assert(T->isVariablyModifiedType());
4403 assert(CSI != nullptr);
4404
4405 // We're going to walk down into the type and look for VLA expressions.
4406 do {
4407 const Type *Ty = T.getTypePtr();
4408 switch (Ty->getTypeClass()) {
4409#define TYPE(Class, Base)
4410#define ABSTRACT_TYPE(Class, Base)
4411#define NON_CANONICAL_TYPE(Class, Base)
4412#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4413#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4414#include "clang/AST/TypeNodes.inc"
4415 T = QualType();
4416 break;
4417 // These types are never variably-modified.
4418 case Type::Builtin:
4419 case Type::Complex:
4420 case Type::Vector:
4421 case Type::ExtVector:
4422 case Type::ConstantMatrix:
4423 case Type::Record:
4424 case Type::Enum:
4425 case Type::TemplateSpecialization:
4426 case Type::ObjCObject:
4427 case Type::ObjCInterface:
4428 case Type::ObjCObjectPointer:
4429 case Type::ObjCTypeParam:
4430 case Type::Pipe:
4431 case Type::BitInt:
4432 llvm_unreachable("type class is never variably-modified!");
4433 case Type::Elaborated:
4434 T = cast<ElaboratedType>(Ty)->getNamedType();
4435 break;
4436 case Type::Adjusted:
4437 T = cast<AdjustedType>(Ty)->getOriginalType();
4438 break;
4439 case Type::Decayed:
4440 T = cast<DecayedType>(Ty)->getPointeeType();
4441 break;
4442 case Type::ArrayParameter:
4443 T = cast<ArrayParameterType>(Ty)->getElementType();
4444 break;
4445 case Type::Pointer:
4446 T = cast<PointerType>(Ty)->getPointeeType();
4447 break;
4448 case Type::BlockPointer:
4449 T = cast<BlockPointerType>(Ty)->getPointeeType();
4450 break;
4451 case Type::LValueReference:
4452 case Type::RValueReference:
4453 T = cast<ReferenceType>(Ty)->getPointeeType();
4454 break;
4455 case Type::MemberPointer:
4456 T = cast<MemberPointerType>(Ty)->getPointeeType();
4457 break;
4458 case Type::ConstantArray:
4459 case Type::IncompleteArray:
4460 // Losing element qualification here is fine.
4461 T = cast<ArrayType>(Ty)->getElementType();
4462 break;
4463 case Type::VariableArray: {
4464 // Losing element qualification here is fine.
4465 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4466
4467 // Unknown size indication requires no size computation.
4468 // Otherwise, evaluate and record it.
4469 auto Size = VAT->getSizeExpr();
4470 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4471 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4472 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4473
4474 T = VAT->getElementType();
4475 break;
4476 }
4477 case Type::FunctionProto:
4478 case Type::FunctionNoProto:
4479 T = cast<FunctionType>(Ty)->getReturnType();
4480 break;
4481 case Type::Paren:
4482 case Type::TypeOf:
4483 case Type::UnaryTransform:
4484 case Type::Attributed:
4485 case Type::BTFTagAttributed:
4486 case Type::HLSLAttributedResource:
4487 case Type::SubstTemplateTypeParm:
4488 case Type::MacroQualified:
4489 case Type::CountAttributed:
4490 // Keep walking after single level desugaring.
4491 T = T.getSingleStepDesugaredType(Context);
4492 break;
4493 case Type::Typedef:
4494 T = cast<TypedefType>(Ty)->desugar();
4495 break;
4496 case Type::Decltype:
4497 T = cast<DecltypeType>(Ty)->desugar();
4498 break;
4499 case Type::PackIndexing:
4500 T = cast<PackIndexingType>(Ty)->desugar();
4501 break;
4502 case Type::Using:
4503 T = cast<UsingType>(Ty)->desugar();
4504 break;
4505 case Type::Auto:
4506 case Type::DeducedTemplateSpecialization:
4507 T = cast<DeducedType>(Ty)->getDeducedType();
4508 break;
4509 case Type::TypeOfExpr:
4510 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4511 break;
4512 case Type::Atomic:
4513 T = cast<AtomicType>(Ty)->getValueType();
4514 break;
4515 }
4516 } while (!T.isNull() && T->isVariablyModifiedType());
4517}
4518
4520 SourceLocation OpLoc,
4521 SourceRange ExprRange,
4522 UnaryExprOrTypeTrait ExprKind,
4523 StringRef KWName) {
4524 if (ExprType->isDependentType())
4525 return false;
4526
4527 // C++ [expr.sizeof]p2:
4528 // When applied to a reference or a reference type, the result
4529 // is the size of the referenced type.
4530 // C++11 [expr.alignof]p3:
4531 // When alignof is applied to a reference type, the result
4532 // shall be the alignment of the referenced type.
4533 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4534 ExprType = Ref->getPointeeType();
4535
4536 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4537 // When alignof or _Alignof is applied to an array type, the result
4538 // is the alignment of the element type.
4539 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4540 ExprKind == UETT_OpenMPRequiredSimdAlign) {
4541 // If the trait is 'alignof' in C before C2y, the ability to apply the
4542 // trait to an incomplete array is an extension.
4543 if (ExprKind == UETT_AlignOf && !getLangOpts().CPlusPlus &&
4544 ExprType->isIncompleteArrayType())
4545 Diag(OpLoc, getLangOpts().C2y
4546 ? diag::warn_c2y_compat_alignof_incomplete_array
4547 : diag::ext_c2y_alignof_incomplete_array);
4548 ExprType = Context.getBaseElementType(ExprType);
4549 }
4550
4551 if (ExprKind == UETT_VecStep)
4552 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4553
4554 if (ExprKind == UETT_VectorElements)
4555 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4556 ExprRange);
4557
4558 if (ExprKind == UETT_PtrAuthTypeDiscriminator)
4559 return checkPtrAuthTypeDiscriminatorOperandType(*this, ExprType, OpLoc,
4560 ExprRange);
4561
4562 // Explicitly list some types as extensions.
4563 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4564 ExprKind))
4565 return false;
4566
4568 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4569 KWName, ExprRange))
4570 return true;
4571
4572 if (ExprType->isFunctionType()) {
4573 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4574 return true;
4575 }
4576
4577 // WebAssembly tables are always illegal operands to unary expressions and
4578 // type traits.
4579 if (Context.getTargetInfo().getTriple().isWasm() &&
4580 ExprType->isWebAssemblyTableType()) {
4581 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4582 << getTraitSpelling(ExprKind);
4583 return true;
4584 }
4585
4586 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4587 ExprKind))
4588 return true;
4589
4590 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4591 if (auto *TT = ExprType->getAs<TypedefType>()) {
4592 for (auto I = FunctionScopes.rbegin(),
4593 E = std::prev(FunctionScopes.rend());
4594 I != E; ++I) {
4595 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4596 if (CSI == nullptr)
4597 break;
4598 DeclContext *DC = nullptr;
4599 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4600 DC = LSI->CallOperator;
4601 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4602 DC = CRSI->TheCapturedDecl;
4603 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4604 DC = BSI->TheDecl;
4605 if (DC) {
4606 if (DC->containsDecl(TT->getDecl()))
4607 break;
4608 captureVariablyModifiedType(Context, ExprType, CSI);
4609 }
4610 }
4611 }
4612 }
4613
4614 return false;
4615}
4616
4618 SourceLocation OpLoc,
4619 UnaryExprOrTypeTrait ExprKind,
4620 SourceRange R) {
4621 if (!TInfo)
4622 return ExprError();
4623
4624 QualType T = TInfo->getType();
4625
4626 if (!T->isDependentType() &&
4627 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4628 getTraitSpelling(ExprKind)))
4629 return ExprError();
4630
4631 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4632 // properly deal with VLAs in nested calls of sizeof and typeof.
4633 if (currentEvaluationContext().isUnevaluated() &&
4634 currentEvaluationContext().InConditionallyConstantEvaluateContext &&
4635 ExprKind == UETT_SizeOf && TInfo->getType()->isVariablyModifiedType())
4636 TInfo = TransformToPotentiallyEvaluated(TInfo);
4637
4638 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4639 return new (Context) UnaryExprOrTypeTraitExpr(
4640 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4641}
4642
4645 UnaryExprOrTypeTrait ExprKind) {
4647 if (PE.isInvalid())
4648 return ExprError();
4649
4650 E = PE.get();
4651
4652 // Verify that the operand is valid.
4653 bool isInvalid = false;
4654 if (E->isTypeDependent()) {
4655 // Delay type-checking for type-dependent expressions.
4656 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4657 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4658 } else if (ExprKind == UETT_VecStep) {
4660 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4661 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4662 isInvalid = true;
4663 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4664 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4665 isInvalid = true;
4666 } else if (ExprKind == UETT_VectorElements) {
4667 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements);
4668 } else {
4670 }
4671
4672 if (isInvalid)
4673 return ExprError();
4674
4675 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4677 if (PE.isInvalid()) return ExprError();
4678 E = PE.get();
4679 }
4680
4681 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4682 return new (Context) UnaryExprOrTypeTraitExpr(
4683 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4684}
4685
4688 UnaryExprOrTypeTrait ExprKind, bool IsType,
4689 void *TyOrEx, SourceRange ArgRange) {
4690 // If error parsing type, ignore.
4691 if (!TyOrEx) return ExprError();
4692
4693 if (IsType) {
4694 TypeSourceInfo *TInfo;
4695 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4696 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4697 }
4698
4699 Expr *ArgEx = (Expr *)TyOrEx;
4700 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4701 return Result;
4702}
4703
4705 SourceLocation OpLoc, SourceRange R) {
4706 if (!TInfo)
4707 return true;
4708 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4709 UETT_AlignOf, KWName);
4710}
4711
4713 SourceLocation OpLoc, SourceRange R) {
4714 TypeSourceInfo *TInfo;
4716 &TInfo);
4717 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4718}
4719
4721 bool IsReal) {
4722 if (V.get()->isTypeDependent())
4723 return S.Context.DependentTy;
4724
4725 // _Real and _Imag are only l-values for normal l-values.
4726 if (V.get()->getObjectKind() != OK_Ordinary) {
4727 V = S.DefaultLvalueConversion(V.get());
4728 if (V.isInvalid())
4729 return QualType();
4730 }
4731
4732 // These operators return the element type of a complex type.
4733 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4734 return CT->getElementType();
4735
4736 // Otherwise they pass through real integer and floating point types here.
4737 if (V.get()->getType()->isArithmeticType())
4738 return V.get()->getType();
4739
4740 // Test for placeholders.
4741 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4742 if (PR.isInvalid()) return QualType();
4743 if (PR.get() != V.get()) {
4744 V = PR;
4745 return CheckRealImagOperand(S, V, Loc, IsReal);
4746 }
4747
4748 // Reject anything else.
4749 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4750 << (IsReal ? "__real" : "__imag");
4751 return QualType();
4752}
4753
4754
4755
4758 tok::TokenKind Kind, Expr *Input) {
4760 switch (Kind) {
4761 default: llvm_unreachable("Unknown unary op!");
4762 case tok::plusplus: Opc = UO_PostInc; break;
4763 case tok::minusminus: Opc = UO_PostDec; break;
4764 }
4765
4766 // Since this might is a postfix expression, get rid of ParenListExprs.
4768 if (Result.isInvalid()) return ExprError();
4769 Input = Result.get();
4770
4771 return BuildUnaryOp(S, OpLoc, Opc, Input);
4772}
4773
4774/// Diagnose if arithmetic on the given ObjC pointer is illegal.
4775///
4776/// \return true on error
4778 SourceLocation opLoc,
4779 Expr *op) {
4780 assert(op->getType()->isObjCObjectPointerType());
4782 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4783 return false;
4784
4785 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4787 << op->getSourceRange();
4788 return true;
4789}
4790
4792 auto *BaseNoParens = Base->IgnoreParens();
4793 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4794 return MSProp->getPropertyDecl()->getType()->isArrayType();
4795 return isa<MSPropertySubscriptExpr>(BaseNoParens);
4796}
4797
4798// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4799// Typically this is DependentTy, but can sometimes be more precise.
4800//
4801// There are cases when we could determine a non-dependent type:
4802// - LHS and RHS may have non-dependent types despite being type-dependent
4803// (e.g. unbounded array static members of the current instantiation)
4804// - one may be a dependent-sized array with known element type
4805// - one may be a dependent-typed valid index (enum in current instantiation)
4806//
4807// We *always* return a dependent type, in such cases it is DependentTy.
4808// This avoids creating type-dependent expressions with non-dependent types.
4809// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4811 const ASTContext &Ctx) {
4812 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
4813 QualType LTy = LHS->getType(), RTy = RHS->getType();
4815 if (RTy->isIntegralOrUnscopedEnumerationType()) {
4816 if (const PointerType *PT = LTy->getAs<PointerType>())
4817 Result = PT->getPointeeType();
4818 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
4819 Result = AT->getElementType();
4820 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
4821 if (const PointerType *PT = RTy->getAs<PointerType>())
4822 Result = PT->getPointeeType();
4823 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
4824 Result = AT->getElementType();
4825 }
4826 // Ensure we return a dependent type.
4827 return Result->isDependentType() ? Result : Ctx.DependentTy;
4828}
4829
4831 SourceLocation lbLoc,
4832 MultiExprArg ArgExprs,
4833 SourceLocation rbLoc) {
4834
4835 if (base && !base->getType().isNull() &&
4836 base->hasPlaceholderType(BuiltinType::ArraySection)) {
4837 auto *AS = cast<ArraySectionExpr>(base);
4838 if (AS->isOMPArraySection())
4840 base, lbLoc, ArgExprs.front(), SourceLocation(), SourceLocation(),
4841 /*Length*/ nullptr,
4842 /*Stride=*/nullptr, rbLoc);
4843
4844 return OpenACC().ActOnArraySectionExpr(base, lbLoc, ArgExprs.front(),
4845 SourceLocation(), /*Length*/ nullptr,
4846 rbLoc);
4847 }
4848
4849 // Since this might be a postfix expression, get rid of ParenListExprs.
4850 if (isa<ParenListExpr>(base)) {
4852 if (result.isInvalid())
4853 return ExprError();
4854 base = result.get();
4855 }
4856
4857 // Check if base and idx form a MatrixSubscriptExpr.
4858 //
4859 // Helper to check for comma expressions, which are not allowed as indices for
4860 // matrix subscript expressions.
4861 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
4862 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
4863 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
4864 << SourceRange(base->getBeginLoc(), rbLoc);
4865 return true;
4866 }
4867 return false;
4868 };
4869 // The matrix subscript operator ([][])is considered a single operator.
4870 // Separating the index expressions by parenthesis is not allowed.
4871 if (base && !base->getType().isNull() &&
4872 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
4873 !isa<MatrixSubscriptExpr>(base)) {
4874 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
4875 << SourceRange(base->getBeginLoc(), rbLoc);
4876 return ExprError();
4877 }
4878 // If the base is a MatrixSubscriptExpr, try to create a new
4879 // MatrixSubscriptExpr.
4880 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
4881 if (matSubscriptE) {
4882 assert(ArgExprs.size() == 1);
4883 if (CheckAndReportCommaError(ArgExprs.front()))
4884 return ExprError();
4885
4886 assert(matSubscriptE->isIncomplete() &&
4887 "base has to be an incomplete matrix subscript");
4888 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
4889 matSubscriptE->getRowIdx(),
4890 ArgExprs.front(), rbLoc);
4891 }
4892 if (base->getType()->isWebAssemblyTableType()) {
4893 Diag(base->getExprLoc(), diag::err_wasm_table_art)
4894 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
4895 return ExprError();
4896 }
4897
4898 CheckInvalidBuiltinCountedByRef(base, ArraySubscriptKind);
4899
4900 // Handle any non-overload placeholder types in the base and index
4901 // expressions. We can't handle overloads here because the other
4902 // operand might be an overloadable type, in which case the overload
4903 // resolution for the operator overload should get the first crack
4904 // at the overload.
4905 bool IsMSPropertySubscript = false;
4906 if (base->getType()->isNonOverloadPlaceholderType()) {
4907 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4908 if (!IsMSPropertySubscript) {
4909 ExprResult result = CheckPlaceholderExpr(base);
4910 if (result.isInvalid())
4911 return ExprError();
4912 base = result.get();
4913 }
4914 }
4915
4916 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4917 if (base->getType()->isMatrixType()) {
4918 assert(ArgExprs.size() == 1);
4919 if (CheckAndReportCommaError(ArgExprs.front()))
4920 return ExprError();
4921
4922 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
4923 rbLoc);
4924 }
4925
4926 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
4927 Expr *idx = ArgExprs[0];
4928 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
4929 (isa<CXXOperatorCallExpr>(idx) &&
4930 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
4931 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
4932 << SourceRange(base->getBeginLoc(), rbLoc);
4933 }
4934 }
4935
4936 if (ArgExprs.size() == 1 &&
4937 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
4938 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
4939 if (result.isInvalid())
4940 return ExprError();
4941 ArgExprs[0] = result.get();
4942 } else {
4943 if (CheckArgsForPlaceholders(ArgExprs))
4944 return ExprError();
4945 }
4946
4947 // Build an unanalyzed expression if either operand is type-dependent.
4948 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
4949 (base->isTypeDependent() ||
4951 !isa<PackExpansionExpr>(ArgExprs[0])) {
4952 return new (Context) ArraySubscriptExpr(
4953 base, ArgExprs.front(),
4954 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
4955 VK_LValue, OK_Ordinary, rbLoc);
4956 }
4957
4958 // MSDN, property (C++)
4959 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4960 // This attribute can also be used in the declaration of an empty array in a
4961 // class or structure definition. For example:
4962 // __declspec(property(get=GetX, put=PutX)) int x[];
4963 // The above statement indicates that x[] can be used with one or more array
4964 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4965 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4966 if (IsMSPropertySubscript) {
4967 assert(ArgExprs.size() == 1);
4968 // Build MS property subscript expression if base is MS property reference
4969 // or MS property subscript.
4970 return new (Context)
4971 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
4972 VK_LValue, OK_Ordinary, rbLoc);
4973 }
4974
4975 // Use C++ overloaded-operator rules if either operand has record
4976 // type. The spec says to do this if either type is *overloadable*,
4977 // but enum types can't declare subscript operators or conversion
4978 // operators, so there's nothing interesting for overload resolution
4979 // to do if there aren't any record types involved.
4980 //
4981 // ObjC pointers have their own subscripting logic that is not tied
4982 // to overload resolution and so should not take this path.
4983 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
4984 ((base->getType()->isRecordType() ||
4985 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
4986 ArgExprs[0]->getType()->isRecordType())))) {
4987 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
4988 }
4989
4990 ExprResult Res =
4991 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
4992
4993 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4994 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4995
4996 return Res;
4997}
4998
5001 InitializationKind Kind =
5003 InitializationSequence InitSeq(*this, Entity, Kind, E);
5004 return InitSeq.Perform(*this, Entity, Kind, E);
5005}
5006
5008 Expr *ColumnIdx,
5009 SourceLocation RBLoc) {
5011 if (BaseR.isInvalid())
5012 return BaseR;
5013 Base = BaseR.get();
5014
5015 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5016 if (RowR.isInvalid())
5017 return RowR;
5018 RowIdx = RowR.get();
5019
5020 if (!ColumnIdx)
5021 return new (Context) MatrixSubscriptExpr(
5022 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5023
5024 // Build an unanalyzed expression if any of the operands is type-dependent.
5025 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5026 ColumnIdx->isTypeDependent())
5027 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5028 Context.DependentTy, RBLoc);
5029
5030 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5031 if (ColumnR.isInvalid())
5032 return ColumnR;
5033 ColumnIdx = ColumnR.get();
5034
5035 // Check that IndexExpr is an integer expression. If it is a constant
5036 // expression, check that it is less than Dim (= the number of elements in the
5037 // corresponding dimension).
5038 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5039 bool IsColumnIdx) -> Expr * {
5040 if (!IndexExpr->getType()->isIntegerType() &&
5041 !IndexExpr->isTypeDependent()) {
5042 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5043 << IsColumnIdx;
5044 return nullptr;
5045 }
5046
5047 if (std::optional<llvm::APSInt> Idx =
5048 IndexExpr->getIntegerConstantExpr(Context)) {
5049 if ((*Idx < 0 || *Idx >= Dim)) {
5050 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5051 << IsColumnIdx << Dim;
5052 return nullptr;
5053 }
5054 }
5055
5056 ExprResult ConvExpr = IndexExpr;
5057 assert(!ConvExpr.isInvalid() &&
5058 "should be able to convert any integer type to size type");
5059 return ConvExpr.get();
5060 };
5061
5062 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5063 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5064 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5065 if (!RowIdx || !ColumnIdx)
5066 return ExprError();
5067
5068 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5069 MTy->getElementType(), RBLoc);
5070}
5071
5072void Sema::CheckAddressOfNoDeref(const Expr *E) {
5073 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5074 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5075
5076 // For expressions like `&(*s).b`, the base is recorded and what should be
5077 // checked.
5078 const MemberExpr *Member = nullptr;
5079 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5080 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5081
5082 LastRecord.PossibleDerefs.erase(StrippedExpr);
5083}
5084
5085void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5087 return;
5088
5089 QualType ResultTy = E->getType();
5090 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5091
5092 // Bail if the element is an array since it is not memory access.
5093 if (isa<ArrayType>(ResultTy))
5094 return;
5095
5096 if (ResultTy->hasAttr(attr::NoDeref)) {
5097 LastRecord.PossibleDerefs.insert(E);
5098 return;
5099 }
5100
5101 // Check if the base type is a pointer to a member access of a struct
5102 // marked with noderef.
5103 const Expr *Base = E->getBase();
5104 QualType BaseTy = Base->getType();
5105 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5106 // Not a pointer access
5107 return;
5108
5109 const MemberExpr *Member = nullptr;
5110 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5111 Member->isArrow())
5112 Base = Member->getBase();
5113
5114 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5115 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5116 LastRecord.PossibleDerefs.insert(E);
5117 }
5118}
5119
5122 Expr *Idx, SourceLocation RLoc) {
5123 Expr *LHSExp = Base;
5124 Expr *RHSExp = Idx;
5125
5128
5129 // Per C++ core issue 1213, the result is an xvalue if either operand is
5130 // a non-lvalue array, and an lvalue otherwise.
5131 if (getLangOpts().CPlusPlus11) {
5132 for (auto *Op : {LHSExp, RHSExp}) {
5133 Op = Op->IgnoreImplicit();
5134 if (Op->getType()->isArrayType() && !Op->isLValue())
5135 VK = VK_XValue;
5136 }
5137 }
5138
5139 // Perform default conversions.
5140 if (!LHSExp->getType()->isSubscriptableVectorType()) {
5142 if (Result.isInvalid())
5143 return ExprError();
5144 LHSExp = Result.get();
5145 }
5147 if (Result.isInvalid())
5148 return ExprError();
5149 RHSExp = Result.get();
5150
5151 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5152
5153 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5154 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5155 // in the subscript position. As a result, we need to derive the array base
5156 // and index from the expression types.
5157 Expr *BaseExpr, *IndexExpr;
5158 QualType ResultType;
5159 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5160 BaseExpr = LHSExp;
5161 IndexExpr = RHSExp;
5162 ResultType =
5164 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5165 BaseExpr = LHSExp;
5166 IndexExpr = RHSExp;
5167 ResultType = PTy->getPointeeType();
5168 } else if (const ObjCObjectPointerType *PTy =
5169 LHSTy->getAs<ObjCObjectPointerType>()) {
5170 BaseExpr = LHSExp;
5171 IndexExpr = RHSExp;
5172
5173 // Use custom logic if this should be the pseudo-object subscript
5174 // expression.
5176 return ObjC().BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr,
5177 nullptr, nullptr);
5178
5179 ResultType = PTy->getPointeeType();
5180 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5181 // Handle the uncommon case of "123[Ptr]".
5182 BaseExpr = RHSExp;
5183 IndexExpr = LHSExp;
5184 ResultType = PTy->getPointeeType();
5185 } else if (const ObjCObjectPointerType *PTy =
5186 RHSTy->getAs<ObjCObjectPointerType>()) {
5187 // Handle the uncommon case of "123[Ptr]".
5188 BaseExpr = RHSExp;
5189 IndexExpr = LHSExp;
5190 ResultType = PTy->getPointeeType();
5192 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5193 << ResultType << BaseExpr->getSourceRange();
5194 return ExprError();
5195 }
5196 } else if (LHSTy->isSubscriptableVectorType()) {
5197 if (LHSTy->isBuiltinType() &&
5198 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5199 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5200 if (BTy->isSVEBool())
5201 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5202 << LHSExp->getSourceRange()
5203 << RHSExp->getSourceRange());
5204 ResultType = BTy->getSveEltType(Context);
5205 } else {
5206 const VectorType *VTy = LHSTy->getAs<VectorType>();
5207 ResultType = VTy->getElementType();
5208 }
5209 BaseExpr = LHSExp; // vectors: V[123]
5210 IndexExpr = RHSExp;
5211 // We apply C++ DR1213 to vector subscripting too.
5212 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5213 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5214 if (Materialized.isInvalid())
5215 return ExprError();
5216 LHSExp = Materialized.get();
5217 }
5218 VK = LHSExp->getValueKind();
5219 if (VK != VK_PRValue)
5220 OK = OK_VectorComponent;
5221
5222 QualType BaseType = BaseExpr->getType();
5223 Qualifiers BaseQuals = BaseType.getQualifiers();
5224 Qualifiers MemberQuals = ResultType.getQualifiers();
5225 Qualifiers Combined = BaseQuals + MemberQuals;
5226 if (Combined != MemberQuals)
5227 ResultType = Context.getQualifiedType(ResultType, Combined);
5228 } else if (LHSTy->isArrayType()) {
5229 // If we see an array that wasn't promoted by
5230 // DefaultFunctionArrayLvalueConversion, it must be an array that
5231 // wasn't promoted because of the C90 rule that doesn't
5232 // allow promoting non-lvalue arrays. Warn, then
5233 // force the promotion here.
5234 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5235 << LHSExp->getSourceRange();
5236 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5237 CK_ArrayToPointerDecay).get();
5238 LHSTy = LHSExp->getType();
5239
5240 BaseExpr = LHSExp;
5241 IndexExpr = RHSExp;
5242 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5243 } else if (RHSTy->isArrayType()) {
5244 // Same as previous, except for 123[f().a] case
5245 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5246 << RHSExp->getSourceRange();
5247 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5248 CK_ArrayToPointerDecay).get();
5249 RHSTy = RHSExp->getType();
5250
5251 BaseExpr = RHSExp;
5252 IndexExpr = LHSExp;
5253 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5254 } else {
5255 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5256 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5257 }
5258 // C99 6.5.2.1p1
5259 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5260 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5261 << IndexExpr->getSourceRange());
5262
5263 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5264 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5265 !IndexExpr->isTypeDependent()) {
5266 std::optional<llvm::APSInt> IntegerContantExpr =
5268 if (!IntegerContantExpr.has_value() ||
5269 IntegerContantExpr.value().isNegative())
5270 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5271 }
5272
5273 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5274 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5275 // type. Note that Functions are not objects, and that (in C99 parlance)
5276 // incomplete types are not object types.
5277 if (ResultType->isFunctionType()) {
5278 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5279 << ResultType << BaseExpr->getSourceRange();
5280 return ExprError();
5281 }
5282
5283 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5284 // GNU extension: subscripting on pointer to void
5285 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5286 << BaseExpr->getSourceRange();
5287
5288 // C forbids expressions of unqualified void type from being l-values.
5289 // See IsCForbiddenLValueType.
5290 if (!ResultType.hasQualifiers())
5291 VK = VK_PRValue;
5292 } else if (!ResultType->isDependentType() &&
5293 !ResultType.isWebAssemblyReferenceType() &&
5295 LLoc, ResultType,
5296 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5297 return ExprError();
5298
5299 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5300 !ResultType.isCForbiddenLValueType());
5301
5303 FunctionScopes.size() > 1) {
5304 if (auto *TT =
5305 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5306 for (auto I = FunctionScopes.rbegin(),
5307 E = std::prev(FunctionScopes.rend());
5308 I != E; ++I) {
5309 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5310 if (CSI == nullptr)
5311 break;
5312 DeclContext *DC = nullptr;
5313 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5314 DC = LSI->CallOperator;
5315 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5316 DC = CRSI->TheCapturedDecl;
5317 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5318 DC = BSI->TheDecl;
5319 if (DC) {
5320 if (DC->containsDecl(TT->getDecl()))
5321 break;
5323 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5324 }
5325 }
5326 }
5327 }
5328
5329 return new (Context)
5330 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5331}
5332
5334 ParmVarDecl *Param, Expr *RewrittenInit,
5335 bool SkipImmediateInvocations) {
5336 if (Param->hasUnparsedDefaultArg()) {
5337 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5338 // If we've already cleared out the location for the default argument,
5339 // that means we're parsing it right now.
5340 if (!UnparsedDefaultArgLocs.count(Param)) {
5341 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5342 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5343 Param->setInvalidDecl();
5344 return true;
5345 }
5346
5347 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5348 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5350 diag::note_default_argument_declared_here);
5351 return true;
5352 }
5353
5354 if (Param->hasUninstantiatedDefaultArg()) {
5355 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5356 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5357 return true;
5358 }
5359
5360 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5361 assert(Init && "default argument but no initializer?");
5362
5363 // If the default expression creates temporaries, we need to
5364 // push them to the current stack of expression temporaries so they'll
5365 // be properly destroyed.
5366 // FIXME: We should really be rebuilding the default argument with new
5367 // bound temporaries; see the comment in PR5810.
5368 // We don't need to do that with block decls, though, because
5369 // blocks in default argument expression can never capture anything.
5370 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5371 // Set the "needs cleanups" bit regardless of whether there are
5372 // any explicit objects.
5373 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5374 // Append all the objects to the cleanup list. Right now, this
5375 // should always be a no-op, because blocks in default argument
5376 // expressions should never be able to capture anything.
5377 assert(!InitWithCleanup->getNumObjects() &&
5378 "default argument expression has capturing blocks?");
5379 }
5380 // C++ [expr.const]p15.1:
5381 // An expression or conversion is in an immediate function context if it is
5382 // potentially evaluated and [...] its innermost enclosing non-block scope
5383 // is a function parameter scope of an immediate function.
5385 *this,
5389 Param);
5390 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5391 SkipImmediateInvocations;
5392 runWithSufficientStackSpace(CallLoc, [&] {
5393 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5394 });
5395 return false;
5396}
5397
5400 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {
5401 ShouldVisitImplicitCode = true;
5402 }
5403
5404 bool HasImmediateCalls = false;
5405
5406 bool VisitCallExpr(CallExpr *E) override {
5407 if (const FunctionDecl *FD = E->getDirectCallee())
5408 HasImmediateCalls |= FD->isImmediateFunction();
5410 }
5411
5413 if (const FunctionDecl *FD = E->getConstructor())
5414 HasImmediateCalls |= FD->isImmediateFunction();
5416 }
5417
5418 // SourceLocExpr are not immediate invocations
5419 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5420 // need to be rebuilt so that they refer to the correct SourceLocation and
5421 // DeclContext.
5423 HasImmediateCalls = true;
5425 }
5426
5427 // A nested lambda might have parameters with immediate invocations
5428 // in their default arguments.
5429 // The compound statement is not visited (as it does not constitute a
5430 // subexpression).
5431 // FIXME: We should consider visiting and transforming captures
5432 // with init expressions.
5433 bool VisitLambdaExpr(LambdaExpr *E) override {
5434 return VisitCXXMethodDecl(E->getCallOperator());
5435 }
5436
5438 return TraverseStmt(E->getExpr());
5439 }
5440
5442 return TraverseStmt(E->getExpr());
5443 }
5444};
5445
5447 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5449 : TreeTransform(SemaRef) {}
5450
5451 bool AlwaysRebuild() { return true; }
5452
5453 // Lambda can only have immediate invocations in the default
5454 // args of their parameters, which is transformed upon calling the closure.
5455 // The body is not a subexpression, so we have nothing to do.
5456 // FIXME: Immediate calls in capture initializers should be transformed.
5459
5460 // Make sure we don't rebuild the this pointer as it would
5461 // cause it to incorrectly point it to the outermost class
5462 // in the case of nested struct initialization.
5464
5465 // Rewrite to source location to refer to the context in which they are used.
5467 DeclContext *DC = E->getParentContext();
5468 if (DC == SemaRef.CurContext)
5469 return E;
5470
5471 // FIXME: During instantiation, because the rebuild of defaults arguments
5472 // is not always done in the context of the template instantiator,
5473 // we run the risk of producing a dependent source location
5474 // that would never be rebuilt.
5475 // This usually happens during overload resolution, or in contexts
5476 // where the value of the source location does not matter.
5477 // However, we should find a better way to deal with source location
5478 // of function templates.
5479 if (!SemaRef.CurrentInstantiationScope ||
5480 !SemaRef.CurContext->isDependentContext() || DC->isDependentContext())
5481 DC = SemaRef.CurContext;
5482
5483 return getDerived().RebuildSourceLocExpr(
5484 E->getIdentKind(), E->getType(), E->getBeginLoc(), E->getEndLoc(), DC);
5485 }
5486};
5487
5489 FunctionDecl *FD, ParmVarDecl *Param,
5490 Expr *Init) {
5491 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5492
5493 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5494 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5495 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5496 InitializationContext =
5498 if (!InitializationContext.has_value())
5499 InitializationContext.emplace(CallLoc, Param, CurContext);
5500
5501 if (!Init && !Param->hasUnparsedDefaultArg()) {
5502 // Mark that we are replacing a default argument first.
5503 // If we are instantiating a template we won't have to
5504 // retransform immediate calls.
5505 // C++ [expr.const]p15.1:
5506 // An expression or conversion is in an immediate function context if it
5507 // is potentially evaluated and [...] its innermost enclosing non-block
5508 // scope is a function parameter scope of an immediate function.
5510 *this,
5514 Param);
5515
5516 if (Param->hasUninstantiatedDefaultArg()) {
5517 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5518 return ExprError();
5519 }
5520 // CWG2631
5521 // An immediate invocation that is not evaluated where it appears is
5522 // evaluated and checked for whether it is a constant expression at the
5523 // point where the enclosing initializer is used in a function call.
5525 if (!NestedDefaultChecking)
5526 V.TraverseDecl(Param);
5527
5528 // Rewrite the call argument that was created from the corresponding
5529 // parameter's default argument.
5530 if (V.HasImmediateCalls ||
5531 (NeedRebuild && isa_and_present<ExprWithCleanups>(Param->getInit()))) {
5532 if (V.HasImmediateCalls)
5533 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5534 CallLoc, Param, CurContext};
5535 // Pass down lifetime extending flag, and collect temporaries in
5536 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5540 ExprResult Res;
5541 runWithSufficientStackSpace(CallLoc, [&] {
5542 Res = Immediate.TransformInitializer(Param->getInit(),
5543 /*NotCopy=*/false);
5544 });
5545 if (Res.isInvalid())
5546 return ExprError();
5547 Res = ConvertParamDefaultArgument(Param, Res.get(),
5548 Res.get()->getBeginLoc());
5549 if (Res.isInvalid())
5550 return ExprError();
5551 Init = Res.get();
5552 }
5553 }
5554
5556 CallLoc, FD, Param, Init,
5557 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5558 return ExprError();
5559
5560 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5561 Init, InitializationContext->Context);
5562}
5563
5565 FieldDecl *Field) {
5566 if (FieldDecl *Pattern = Ctx.getInstantiatedFromUnnamedFieldDecl(Field))
5567 return Pattern;
5568 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5569 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5571 ClassPattern->lookup(Field->getDeclName());
5572 auto Rng = llvm::make_filter_range(
5573 Lookup, [](auto &&L) { return isa<FieldDecl>(*L); });
5574 if (Rng.empty())
5575 return nullptr;
5576 // FIXME: this breaks clang/test/Modules/pr28812.cpp
5577 // assert(std::distance(Rng.begin(), Rng.end()) <= 1
5578 // && "Duplicated instantiation pattern for field decl");
5579 return cast<FieldDecl>(*Rng.begin());
5580}
5581
5583 assert(Field->hasInClassInitializer());
5584
5585 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5586
5587 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5588
5589 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5590 InitializationContext =
5592 if (!InitializationContext.has_value())
5593 InitializationContext.emplace(Loc, Field, CurContext);
5594
5595 Expr *Init = nullptr;
5596
5597 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5598 bool NeedRebuild = needsRebuildOfDefaultArgOrInit();
5601
5602 if (!Field->getInClassInitializer()) {
5603 // Maybe we haven't instantiated the in-class initializer. Go check the
5604 // pattern FieldDecl to see if it has one.
5605 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5606 FieldDecl *Pattern =
5608 assert(Pattern && "We must have set the Pattern!");
5609 if (!Pattern->hasInClassInitializer() ||
5610 InstantiateInClassInitializer(Loc, Field, Pattern,
5612 Field->setInvalidDecl();
5613 return ExprError();
5614 }
5615 }
5616 }
5617
5618 // CWG2631
5619 // An immediate invocation that is not evaluated where it appears is
5620 // evaluated and checked for whether it is a constant expression at the
5621 // point where the enclosing initializer is used in a [...] a constructor
5622 // definition, or an aggregate initialization.
5624 if (!NestedDefaultChecking)
5625 V.TraverseDecl(Field);
5626
5627 // CWG1815
5628 // Support lifetime extension of temporary created by aggregate
5629 // initialization using a default member initializer. We should rebuild
5630 // the initializer in a lifetime extension context if the initializer
5631 // expression is an ExprWithCleanups. Then make sure the normal lifetime
5632 // extension code recurses into the default initializer and does lifetime
5633 // extension when warranted.
5634 bool ContainsAnyTemporaries =
5635 isa_and_present<ExprWithCleanups>(Field->getInClassInitializer());
5636 if (Field->getInClassInitializer() &&
5637 !Field->getInClassInitializer()->containsErrors() &&
5638 (V.HasImmediateCalls || (NeedRebuild && ContainsAnyTemporaries))) {
5639 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5640 CurContext};
5641 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5642 NestedDefaultChecking;
5643 // Pass down lifetime extending flag, and collect temporaries in
5644 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5648 ExprResult Res;
5650 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5651 /*CXXDirectInit=*/false);
5652 });
5653 if (!Res.isInvalid())
5654 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5655 if (Res.isInvalid()) {
5656 Field->setInvalidDecl();
5657 return ExprError();
5658 }
5659 Init = Res.get();
5660 }
5661
5662 if (Field->getInClassInitializer()) {
5663 Expr *E = Init ? Init : Field->getInClassInitializer();
5664 if (!NestedDefaultChecking)
5666 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5667 });
5670 // C++11 [class.base.init]p7:
5671 // The initialization of each base and member constitutes a
5672 // full-expression.
5673 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5674 if (Res.isInvalid()) {
5675 Field->setInvalidDecl();
5676 return ExprError();
5677 }
5678 Init = Res.get();
5679
5680 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5681 Field, InitializationContext->Context,
5682 Init);
5683 }
5684
5685 // DR1351:
5686 // If the brace-or-equal-initializer of a non-static data member
5687 // invokes a defaulted default constructor of its class or of an
5688 // enclosing class in a potentially evaluated subexpression, the
5689 // program is ill-formed.
5690 //
5691 // This resolution is unworkable: the exception specification of the
5692 // default constructor can be needed in an unevaluated context, in
5693 // particular, in the operand of a noexcept-expression, and we can be
5694 // unable to compute an exception specification for an enclosed class.
5695 //
5696 // Any attempt to resolve the exception specification of a defaulted default
5697 // constructor before the initializer is lexically complete will ultimately
5698 // come here at which point we can diagnose it.
5699 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5700 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5701 << OutermostClass << Field;
5702 Diag(Field->getEndLoc(),
5703 diag::note_default_member_initializer_not_yet_parsed);
5704 // Recover by marking the field invalid, unless we're in a SFINAE context.
5705 if (!isSFINAEContext())
5706 Field->setInvalidDecl();
5707 return ExprError();
5708}
5709
5712 Expr *Fn) {
5713 if (Proto && Proto->isVariadic()) {
5714 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5715 return VariadicConstructor;
5716 else if (Fn && Fn->getType()->isBlockPointerType())
5717 return VariadicBlock;
5718 else if (FDecl) {
5719 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5720 if (Method->isInstance())
5721 return VariadicMethod;
5722 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5723 return VariadicMethod;
5724 return VariadicFunction;
5725 }
5726 return VariadicDoesNotApply;
5727}
5728
5729namespace {
5730class FunctionCallCCC final : public FunctionCallFilterCCC {
5731public:
5732 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5733 unsigned NumArgs, MemberExpr *ME)
5734 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5735 FunctionName(FuncName) {}
5736
5737 bool ValidateCandidate(const TypoCorrection &candidate) override {
5738 if (!candidate.getCorrectionSpecifier() ||
5739 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5740 return false;
5741 }
5742
5744 }
5745
5746 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5747 return std::make_unique<FunctionCallCCC>(*this);
5748 }
5749
5750private:
5751 const IdentifierInfo *const FunctionName;
5752};
5753}
5754
5756 FunctionDecl *FDecl,
5757 ArrayRef<Expr *> Args) {
5758 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5759 DeclarationName FuncName = FDecl->getDeclName();
5760 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5761
5762 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5763 if (TypoCorrection Corrected = S.CorrectTypo(
5765 S.getScopeForContext(S.CurContext), nullptr, CCC,
5767 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5768 if (Corrected.isOverloaded()) {
5771 for (NamedDecl *CD : Corrected) {
5772 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5774 OCS);
5775 }
5776 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5777 case OR_Success:
5778 ND = Best->FoundDecl;
5779 Corrected.setCorrectionDecl(ND);
5780 break;
5781 default:
5782 break;
5783 }
5784 }
5785 ND = ND->getUnderlyingDecl();
5786 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5787 return Corrected;
5788 }
5789 }
5790 return TypoCorrection();
5791}
5792
5793// [C++26][[expr.unary.op]/p4
5794// A pointer to member is only formed when an explicit &
5795// is used and its operand is a qualified-id not enclosed in parentheses.
5797 if (!isa<ParenExpr>(Fn))
5798 return false;
5799
5800 Fn = Fn->IgnoreParens();
5801
5802 auto *UO = dyn_cast<UnaryOperator>(Fn);
5803 if (!UO || UO->getOpcode() != clang::UO_AddrOf)
5804 return false;
5805 if (auto *DRE = dyn_cast<DeclRefExpr>(UO->getSubExpr()->IgnoreParens())) {
5806 return DRE->hasQualifier();
5807 }
5808 if (auto *OVL = dyn_cast<OverloadExpr>(UO->getSubExpr()->IgnoreParens()))
5809 return OVL->getQualifier();
5810 return false;
5811}
5812
5813bool
5815 FunctionDecl *FDecl,
5816 const FunctionProtoType *Proto,
5817 ArrayRef<Expr *> Args,
5818 SourceLocation RParenLoc,
5819 bool IsExecConfig) {
5820 // Bail out early if calling a builtin with custom typechecking.
5821 if (FDecl)
5822 if (unsigned ID = FDecl->getBuiltinID())
5824 return false;
5825
5826 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
5827 // assignment, to the types of the corresponding parameter, ...
5828
5829 bool AddressOf = isParenthetizedAndQualifiedAddressOfExpr(Fn);
5830 bool HasExplicitObjectParameter =
5831 !AddressOf && FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
5832 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
5833 unsigned NumParams = Proto->getNumParams();
5834 bool Invalid = false;
5835 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
5836 unsigned FnKind = Fn->getType()->isBlockPointerType()
5837 ? 1 /* block */
5838 : (IsExecConfig ? 3 /* kernel function (exec config) */
5839 : 0 /* function */);
5840
5841 // If too few arguments are available (and we don't have default
5842 // arguments for the remaining parameters), don't make the call.
5843 if (Args.size() < NumParams) {
5844 if (Args.size() < MinArgs) {
5845 TypoCorrection TC;
5846 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5847 unsigned diag_id =
5848 MinArgs == NumParams && !Proto->isVariadic()
5849 ? diag::err_typecheck_call_too_few_args_suggest
5850 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5852 TC, PDiag(diag_id)
5853 << FnKind << MinArgs - ExplicitObjectParameterOffset
5854 << static_cast<unsigned>(Args.size()) -
5855 ExplicitObjectParameterOffset
5856 << HasExplicitObjectParameter << TC.getCorrectionRange());
5857 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
5858 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5859 ->getDeclName())
5860 Diag(RParenLoc,
5861 MinArgs == NumParams && !Proto->isVariadic()
5862 ? diag::err_typecheck_call_too_few_args_one
5863 : diag::err_typecheck_call_too_few_args_at_least_one)
5864 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5865 << HasExplicitObjectParameter << Fn->getSourceRange();
5866 else
5867 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5868 ? diag::err_typecheck_call_too_few_args
5869 : diag::err_typecheck_call_too_few_args_at_least)
5870 << FnKind << MinArgs - ExplicitObjectParameterOffset
5871 << static_cast<unsigned>(Args.size()) -
5872 ExplicitObjectParameterOffset
5873 << HasExplicitObjectParameter << Fn->getSourceRange();
5874
5875 // Emit the location of the prototype.
5876 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5877 Diag(FDecl->getLocation(), diag::note_callee_decl)
5878 << FDecl << FDecl->getParametersSourceRange();
5879
5880 return true;
5881 }
5882 // We reserve space for the default arguments when we create
5883 // the call expression, before calling ConvertArgumentsForCall.
5884 assert((Call->getNumArgs() == NumParams) &&
5885 "We should have reserved space for the default arguments before!");
5886 }
5887
5888 // If too many are passed and not variadic, error on the extras and drop
5889 // them.
5890 if (Args.size() > NumParams) {
5891 if (!Proto->isVariadic()) {
5892 TypoCorrection TC;
5893 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5894 unsigned diag_id =
5895 MinArgs == NumParams && !Proto->isVariadic()
5896 ? diag::err_typecheck_call_too_many_args_suggest
5897 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5899 TC, PDiag(diag_id)
5900 << FnKind << NumParams - ExplicitObjectParameterOffset
5901 << static_cast<unsigned>(Args.size()) -
5902 ExplicitObjectParameterOffset
5903 << HasExplicitObjectParameter << TC.getCorrectionRange());
5904 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
5905 FDecl->getParamDecl(ExplicitObjectParameterOffset)
5906 ->getDeclName())
5907 Diag(Args[NumParams]->getBeginLoc(),
5908 MinArgs == NumParams
5909 ? diag::err_typecheck_call_too_many_args_one
5910 : diag::err_typecheck_call_too_many_args_at_most_one)
5911 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
5912 << static_cast<unsigned>(Args.size()) -
5913 ExplicitObjectParameterOffset
5914 << HasExplicitObjectParameter << Fn->getSourceRange()
5915 << SourceRange(Args[NumParams]->getBeginLoc(),
5916 Args.back()->getEndLoc());
5917 else
5918 Diag(Args[NumParams]->getBeginLoc(),
5919 MinArgs == NumParams
5920 ? diag::err_typecheck_call_too_many_args
5921 : diag::err_typecheck_call_too_many_args_at_most)
5922 << FnKind << NumParams - ExplicitObjectParameterOffset
5923 << static_cast<unsigned>(Args.size()) -
5924 ExplicitObjectParameterOffset
5925 << HasExplicitObjectParameter << Fn->getSourceRange()
5926 << SourceRange(Args[NumParams]->getBeginLoc(),
5927 Args.back()->getEndLoc());
5928
5929 // Emit the location of the prototype.
5930 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5931 Diag(FDecl->getLocation(), diag::note_callee_decl)
5932 << FDecl << FDecl->getParametersSourceRange();
5933
5934 // This deletes the extra arguments.
5935 Call->shrinkNumArgs(NumParams);
5936 return true;
5937 }
5938 }
5939 SmallVector<Expr *, 8> AllArgs;
5940 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5941
5942 Invalid = GatherArgumentsForCall(Call->getExprLoc(), FDecl, Proto, 0, Args,
5943 AllArgs, CallType);
5944 if (Invalid)
5945 return true;
5946 unsigned TotalNumArgs = AllArgs.size();
5947 for (unsigned i = 0; i < TotalNumArgs; ++i)
5948 Call->setArg(i, AllArgs[i]);
5949
5950 Call->computeDependence();
5951 return false;
5952}
5953
5955 const FunctionProtoType *Proto,
5956 unsigned FirstParam, ArrayRef<Expr *> Args,
5957 SmallVectorImpl<Expr *> &AllArgs,
5958 VariadicCallType CallType, bool AllowExplicit,
5959 bool IsListInitialization) {
5960 unsigned NumParams = Proto->getNumParams();
5961 bool Invalid = false;
5962 size_t ArgIx = 0;
5963 // Continue to check argument types (even if we have too few/many args).
5964 for (unsigned i = FirstParam; i < NumParams; i++) {
5965 QualType ProtoArgType = Proto->getParamType(i);
5966
5967 Expr *Arg;
5968 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5969 if (ArgIx < Args.size()) {
5970 Arg = Args[ArgIx++];
5971
5972 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5973 diag::err_call_incomplete_argument, Arg))
5974 return true;
5975
5976 // Strip the unbridged-cast placeholder expression off, if applicable.
5977 bool CFAudited = false;
5978 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5979 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5980 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5981 Arg = ObjC().stripARCUnbridgedCast(Arg);
5982 else if (getLangOpts().ObjCAutoRefCount &&
5983 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5984 (!Param || !Param->hasAttr<CFConsumedAttr>()))
5985 CFAudited = true;
5986
5987 if (Proto->getExtParameterInfo(i).isNoEscape() &&
5988 ProtoArgType->isBlockPointerType())
5989 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5990 BE->getBlockDecl()->setDoesNotEscape();
5991 if ((Proto->getExtParameterInfo(i).getABI() == ParameterABI::HLSLOut ||
5993 ExprResult ArgExpr = HLSL().ActOnOutParamExpr(Param, Arg);
5994 if (ArgExpr.isInvalid())
5995 return true;
5996 Arg = ArgExpr.getAs<Expr>();
5997 }
5998
5999 InitializedEntity Entity =
6001 ProtoArgType)
6003 Context, ProtoArgType, Proto->isParamConsumed(i));
6004
6005 // Remember that parameter belongs to a CF audited API.
6006 if (CFAudited)
6007 Entity.setParameterCFAudited();
6008
6010 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6011 if (ArgE.isInvalid())
6012 return true;
6013
6014 Arg = ArgE.getAs<Expr>();
6015 } else {
6016 assert(Param && "can't use default arguments without a known callee");
6017
6018 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6019 if (ArgExpr.isInvalid())
6020 return true;
6021
6022 Arg = ArgExpr.getAs<Expr>();
6023 }
6024
6025 // Check for array bounds violations for each argument to the call. This
6026 // check only triggers warnings when the argument isn't a more complex Expr
6027 // with its own checking, such as a BinaryOperator.
6028 CheckArrayAccess(Arg);
6029
6030 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6031 CheckStaticArrayArgument(CallLoc, Param, Arg);
6032
6033 AllArgs.push_back(Arg);
6034 }
6035
6036 // If this is a variadic call, handle args passed through "...".
6037 if (CallType != VariadicDoesNotApply) {
6038 // Assume that extern "C" functions with variadic arguments that
6039 // return __unknown_anytype aren't *really* variadic.
6040 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6041 FDecl->isExternC()) {
6042 for (Expr *A : Args.slice(ArgIx)) {
6043 QualType paramType; // ignored
6044 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6045 Invalid |= arg.isInvalid();
6046 AllArgs.push_back(arg.get());
6047 }
6048
6049 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6050 } else {
6051 for (Expr *A : Args.slice(ArgIx)) {
6052 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6053 Invalid |= Arg.isInvalid();
6054 AllArgs.push_back(Arg.get());
6055 }
6056 }
6057
6058 // Check for array bounds violations.
6059 for (Expr *A : Args.slice(ArgIx))
6060 CheckArrayAccess(A);
6061 }
6062 return Invalid;
6063}
6064
6066 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6067 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6068 TL = DTL.getOriginalLoc();
6069 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6070 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6071 << ATL.getLocalSourceRange();
6072}
6073
6074void
6076 ParmVarDecl *Param,
6077 const Expr *ArgExpr) {
6078 // Static array parameters are not supported in C++.
6079 if (!Param || getLangOpts().CPlusPlus)
6080 return;
6081
6082 QualType OrigTy = Param->getOriginalType();
6083
6084 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6085 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6086 return;
6087
6088 if (ArgExpr->isNullPointerConstant(Context,
6090 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6091 DiagnoseCalleeStaticArrayParam(*this, Param);
6092 return;
6093 }
6094
6095 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6096 if (!CAT)
6097 return;
6098
6099 const ConstantArrayType *ArgCAT =
6101 if (!ArgCAT)
6102 return;
6103
6104 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6105 ArgCAT->getElementType())) {
6106 if (ArgCAT->getSize().ult(CAT->getSize())) {
6107 Diag(CallLoc, diag::warn_static_array_too_small)
6108 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6109 << (unsigned)CAT->getZExtSize() << 0;
6110 DiagnoseCalleeStaticArrayParam(*this, Param);
6111 }
6112 return;
6113 }
6114
6115 std::optional<CharUnits> ArgSize =
6117 std::optional<CharUnits> ParmSize =
6119 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6120 Diag(CallLoc, diag::warn_static_array_too_small)
6121 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6122 << (unsigned)ParmSize->getQuantity() << 1;
6123 DiagnoseCalleeStaticArrayParam(*this, Param);
6124 }
6125}
6126
6127/// Given a function expression of unknown-any type, try to rebuild it
6128/// to have a function type.
6130
6131/// Is the given type a placeholder that we need to lower out
6132/// immediately during argument processing?
6134 // Placeholders are never sugared.
6135 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6136 if (!placeholder) return false;
6137
6138 switch (placeholder->getKind()) {
6139 // Ignore all the non-placeholder types.
6140#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6141 case BuiltinType::Id:
6142#include "clang/Basic/OpenCLImageTypes.def"
6143#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6144 case BuiltinType::Id:
6145#include "clang/Basic/OpenCLExtensionTypes.def"
6146 // In practice we'll never use this, since all SVE types are sugared
6147 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6148#define SVE_TYPE(Name, Id, SingletonId) \
6149 case BuiltinType::Id:
6150#include "clang/Basic/AArch64SVEACLETypes.def"
6151#define PPC_VECTOR_TYPE(Name, Id, Size) \
6152 case BuiltinType::Id:
6153#include "clang/Basic/PPCTypes.def"
6154#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6155#include "clang/Basic/RISCVVTypes.def"
6156#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6157#include "clang/Basic/WebAssemblyReferenceTypes.def"
6158#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
6159#include "clang/Basic/AMDGPUTypes.def"
6160#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6161#include "clang/Basic/HLSLIntangibleTypes.def"
6162#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6163#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6164#include "clang/AST/BuiltinTypes.def"
6165 return false;
6166
6167 case BuiltinType::UnresolvedTemplate:
6168 // We cannot lower out overload sets; they might validly be resolved
6169 // by the call machinery.
6170 case BuiltinType::Overload:
6171 return false;
6172
6173 // Unbridged casts in ARC can be handled in some call positions and
6174 // should be left in place.
6175 case BuiltinType::ARCUnbridgedCast:
6176 return false;
6177
6178 // Pseudo-objects should be converted as soon as possible.
6179 case BuiltinType::PseudoObject:
6180 return true;
6181
6182 // The debugger mode could theoretically but currently does not try
6183 // to resolve unknown-typed arguments based on known parameter types.
6184 case BuiltinType::UnknownAny:
6185 return true;
6186
6187 // These are always invalid as call arguments and should be reported.
6188 case BuiltinType::BoundMember:
6189 case BuiltinType::BuiltinFn:
6190 case BuiltinType::IncompleteMatrixIdx:
6191 case BuiltinType::ArraySection:
6192 case BuiltinType::OMPArrayShaping:
6193 case BuiltinType::OMPIterator:
6194 return true;
6195
6196 }
6197 llvm_unreachable("bad builtin type kind");
6198}
6199
6201 // Apply this processing to all the arguments at once instead of
6202 // dying at the first failure.
6203 bool hasInvalid = false;
6204 for (size_t i = 0, e = args.size(); i != e; i++) {
6205 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6206 ExprResult result = CheckPlaceholderExpr(args[i]);
6207 if (result.isInvalid()) hasInvalid = true;
6208 else args[i] = result.get();
6209 }
6210 }
6211 return hasInvalid;
6212}
6213
6214/// If a builtin function has a pointer argument with no explicit address
6215/// space, then it should be able to accept a pointer to any address
6216/// space as input. In order to do this, we need to replace the
6217/// standard builtin declaration with one that uses the same address space
6218/// as the call.
6219///
6220/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6221/// it does not contain any pointer arguments without
6222/// an address space qualifer. Otherwise the rewritten
6223/// FunctionDecl is returned.
6224/// TODO: Handle pointer return types.
6226 FunctionDecl *FDecl,
6227 MultiExprArg ArgExprs) {
6228
6229 QualType DeclType = FDecl->getType();
6230 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6231
6232 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6233 ArgExprs.size() < FT->getNumParams())
6234 return nullptr;
6235
6236 bool NeedsNewDecl = false;
6237 unsigned i = 0;
6238 SmallVector<QualType, 8> OverloadParams;
6239
6240 for (QualType ParamType : FT->param_types()) {
6241
6242 // Convert array arguments to pointer to simplify type lookup.
6243 ExprResult ArgRes =
6245 if (ArgRes.isInvalid())
6246 return nullptr;
6247 Expr *Arg = ArgRes.get();
6248 QualType ArgType = Arg->getType();
6249 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6250 !ArgType->isPointerType() ||
6251 !ArgType->getPointeeType().hasAddressSpace() ||
6253 OverloadParams.push_back(ParamType);
6254 continue;
6255 }
6256
6257 QualType PointeeType = ParamType->getPointeeType();
6258 if (PointeeType.hasAddressSpace())
6259 continue;
6260
6261 NeedsNewDecl = true;
6262 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6263
6264 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6265 OverloadParams.push_back(Context.getPointerType(PointeeType));
6266 }
6267
6268 if (!NeedsNewDecl)
6269 return nullptr;
6270
6272 EPI.Variadic = FT->isVariadic();
6273 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6274 OverloadParams, EPI);
6275 DeclContext *Parent = FDecl->getParent();
6276 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6277 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6278 FDecl->getIdentifier(), OverloadTy,
6279 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6280 false,
6281 /*hasPrototype=*/true);
6283 FT = cast<FunctionProtoType>(OverloadTy);
6284 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6285 QualType ParamType = FT->getParamType(i);
6286 ParmVarDecl *Parm =
6287 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6288 SourceLocation(), nullptr, ParamType,
6289 /*TInfo=*/nullptr, SC_None, nullptr);
6290 Parm->setScopeInfo(0, i);
6291 Params.push_back(Parm);
6292 }
6293 OverloadDecl->setParams(Params);
6294 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6295 return OverloadDecl;
6296}
6297
6298static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6299 FunctionDecl *Callee,
6300 MultiExprArg ArgExprs) {
6301 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6302 // similar attributes) really don't like it when functions are called with an
6303 // invalid number of args.
6304 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6305 /*PartialOverloading=*/false) &&
6306 !Callee->isVariadic())
6307 return;
6308 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6309 return;
6310
6311 if (const EnableIfAttr *Attr =
6312 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6313 S.Diag(Fn->getBeginLoc(),
6314 isa<CXXMethodDecl>(Callee)
6315 ? diag::err_ovl_no_viable_member_function_in_call
6316 : diag::err_ovl_no_viable_function_in_call)
6317 << Callee << Callee->getSourceRange();
6318 S.Diag(Callee->getLocation(),
6319 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6320 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6321 return;
6322 }
6323}
6324
6326 const UnresolvedMemberExpr *const UME, Sema &S) {
6327
6328 const auto GetFunctionLevelDCIfCXXClass =
6329 [](Sema &S) -> const CXXRecordDecl * {
6330 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6331 if (!DC || !DC->getParent())
6332 return nullptr;
6333
6334 // If the call to some member function was made from within a member
6335 // function body 'M' return return 'M's parent.
6336 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6337 return MD->getParent()->getCanonicalDecl();
6338 // else the call was made from within a default member initializer of a
6339 // class, so return the class.
6340 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6341 return RD->getCanonicalDecl();
6342 return nullptr;
6343 };
6344 // If our DeclContext is neither a member function nor a class (in the
6345 // case of a lambda in a default member initializer), we can't have an
6346 // enclosing 'this'.
6347
6348 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6349 if (!CurParentClass)
6350 return false;
6351
6352 // The naming class for implicit member functions call is the class in which
6353 // name lookup starts.
6354 const CXXRecordDecl *const NamingClass =
6356 assert(NamingClass && "Must have naming class even for implicit access");
6357
6358 // If the unresolved member functions were found in a 'naming class' that is
6359 // related (either the same or derived from) to the class that contains the
6360 // member function that itself contained the implicit member access.
6361
6362 return CurParentClass == NamingClass ||
6363 CurParentClass->isDerivedFrom(NamingClass);
6364}
6365
6366static void
6368 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6369
6370 if (!UME)
6371 return;
6372
6373 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6374 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6375 // already been captured, or if this is an implicit member function call (if
6376 // it isn't, an attempt to capture 'this' should already have been made).
6377 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6378 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6379 return;
6380
6381 // Check if the naming class in which the unresolved members were found is
6382 // related (same as or is a base of) to the enclosing class.
6383
6385 return;
6386
6387
6388 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6389 // If the enclosing function is not dependent, then this lambda is
6390 // capture ready, so if we can capture this, do so.
6391 if (!EnclosingFunctionCtx->isDependentContext()) {
6392 // If the current lambda and all enclosing lambdas can capture 'this' -
6393 // then go ahead and capture 'this' (since our unresolved overload set
6394 // contains at least one non-static member function).
6395 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6396 S.CheckCXXThisCapture(CallLoc);
6397 } else if (S.CurContext->isDependentContext()) {
6398 // ... since this is an implicit member reference, that might potentially
6399 // involve a 'this' capture, mark 'this' for potential capture in
6400 // enclosing lambdas.
6401 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6402 CurLSI->addPotentialThisCapture(CallLoc);
6403 }
6404}
6405
6406// Once a call is fully resolved, warn for unqualified calls to specific
6407// C++ standard functions, like move and forward.
6409 const CallExpr *Call) {
6410 // We are only checking unary move and forward so exit early here.
6411 if (Call->getNumArgs() != 1)
6412 return;
6413
6414 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6415 if (!E || isa<UnresolvedLookupExpr>(E))
6416 return;
6417 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6418 if (!DRE || !DRE->getLocation().isValid())
6419 return;
6420
6421 if (DRE->getQualifier())
6422 return;
6423
6424 const FunctionDecl *FD = Call->getDirectCallee();
6425 if (!FD)
6426 return;
6427
6428 // Only warn for some functions deemed more frequent or problematic.
6429 unsigned BuiltinID = FD->getBuiltinID();
6430 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6431 return;
6432
6433 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6435 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6436}
6437
6439 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6440 Expr *ExecConfig) {
6442 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6443 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6444 if (Call.isInvalid())
6445 return Call;
6446
6447 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6448 // language modes.
6449 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6450 ULE && ULE->hasExplicitTemplateArgs() &&
6451 ULE->decls_begin() == ULE->decls_end()) {
6452 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
6453 ? diag::warn_cxx17_compat_adl_only_template_id
6454 : diag::ext_adl_only_template_id)
6455 << ULE->getName();
6456 }
6457
6458 if (LangOpts.OpenMP)
6459 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6460 ExecConfig);
6461 if (LangOpts.CPlusPlus) {
6462 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6464
6465 // If we previously found that the id-expression of this call refers to a
6466 // consteval function but the call is dependent, we should not treat is an
6467 // an invalid immediate call.
6468 if (auto *DRE = dyn_cast<DeclRefExpr>(Fn->IgnoreParens());
6469 DRE && Call.get()->isValueDependent()) {
6471 }
6472 }
6473 return Call;
6474}
6475
6477 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6478 Expr *ExecConfig, bool IsExecConfig,
6479 bool AllowRecovery) {
6480 // Since this might be a postfix expression, get rid of ParenListExprs.
6482 if (Result.isInvalid()) return ExprError();
6483 Fn = Result.get();
6484
6485 if (CheckArgsForPlaceholders(ArgExprs))
6486 return ExprError();
6487
6488 // The result of __builtin_counted_by_ref cannot be used as a function
6489 // argument. It allows leaking and modification of bounds safety information.
6490 for (const Expr *Arg : ArgExprs)
6491 if (CheckInvalidBuiltinCountedByRef(Arg, FunctionArgKind))
6492 return ExprError();
6493
6494 if (getLangOpts().CPlusPlus) {
6495 // If this is a pseudo-destructor expression, build the call immediately.
6496 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6497 if (!ArgExprs.empty()) {
6498 // Pseudo-destructor calls should not have any arguments.
6499 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6501 SourceRange(ArgExprs.front()->getBeginLoc(),
6502 ArgExprs.back()->getEndLoc()));
6503 }
6504
6505 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6506 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6507 }
6508 if (Fn->getType() == Context.PseudoObjectTy) {
6509 ExprResult result = CheckPlaceholderExpr(Fn);
6510 if (result.isInvalid()) return ExprError();
6511 Fn = result.get();
6512 }
6513
6514 // Determine whether this is a dependent call inside a C++ template,
6515 // in which case we won't do any semantic analysis now.
6516 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6517 if (ExecConfig) {
6519 cast<CallExpr>(ExecConfig), ArgExprs,
6521 RParenLoc, CurFPFeatureOverrides());
6522 } else {
6523
6525 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6526 Fn->getBeginLoc());
6527
6528 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6529 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6530 }
6531 }
6532
6533 // Determine whether this is a call to an object (C++ [over.call.object]).
6534 if (Fn->getType()->isRecordType())
6535 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6536 RParenLoc);
6537
6538 if (Fn->getType() == Context.UnknownAnyTy) {
6539 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6540 if (result.isInvalid()) return ExprError();
6541 Fn = result.get();
6542 }
6543
6544 if (Fn->getType() == Context.BoundMemberTy) {
6545 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6546 RParenLoc, ExecConfig, IsExecConfig,
6547 AllowRecovery);
6548 }
6549 }
6550
6551 // Check for overloaded calls. This can happen even in C due to extensions.
6552 if (Fn->getType() == Context.OverloadTy) {
6554
6555 // We aren't supposed to apply this logic if there's an '&' involved.
6558 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6559 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6560 OverloadExpr *ovl = find.Expression;
6561 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6563 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6564 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6565 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6566 RParenLoc, ExecConfig, IsExecConfig,
6567 AllowRecovery);
6568 }
6569 }
6570
6571 // If we're directly calling a function, get the appropriate declaration.
6572 if (Fn->getType() == Context.UnknownAnyTy) {
6573 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6574 if (result.isInvalid()) return ExprError();
6575 Fn = result.get();
6576 }
6577
6578 Expr *NakedFn = Fn->IgnoreParens();
6579
6580 bool CallingNDeclIndirectly = false;
6581 NamedDecl *NDecl = nullptr;
6582 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6583 if (UnOp->getOpcode() == UO_AddrOf) {
6584 CallingNDeclIndirectly = true;
6585 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6586 }
6587 }
6588
6589 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6590 NDecl = DRE->getDecl();
6591
6592 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6593 if (FDecl && FDecl->getBuiltinID()) {
6594 // Rewrite the function decl for this builtin by replacing parameters
6595 // with no explicit address space with the address space of the arguments
6596 // in ArgExprs.
6597 if ((FDecl =
6598 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6599 NDecl = FDecl;
6601 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6602 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6603 nullptr, DRE->isNonOdrUse());
6604 }
6605 }
6606 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6607 NDecl = ME->getMemberDecl();
6608
6609 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6610 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6611 FD, /*Complain=*/true, Fn->getBeginLoc()))
6612 return ExprError();
6613
6614 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6615
6616 // If this expression is a call to a builtin function in HIP device
6617 // compilation, allow a pointer-type argument to default address space to be
6618 // passed as a pointer-type parameter to a non-default address space.
6619 // If Arg is declared in the default address space and Param is declared
6620 // in a non-default address space, perform an implicit address space cast to
6621 // the parameter type.
6622 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6623 FD->getBuiltinID()) {
6624 for (unsigned Idx = 0; Idx < ArgExprs.size() && Idx < FD->param_size();
6625 ++Idx) {
6626 ParmVarDecl *Param = FD->getParamDecl(Idx);
6627 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6628 !ArgExprs[Idx]->getType()->isPointerType())
6629 continue;
6630
6631 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6632 auto ArgTy = ArgExprs[Idx]->getType();
6633 auto ArgPtTy = ArgTy->getPointeeType();
6634 auto ArgAS = ArgPtTy.getAddressSpace();
6635
6636 // Add address space cast if target address spaces are different
6637 bool NeedImplicitASC =
6638 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6639 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6640 // or from specific AS which has target AS matching that of Param.
6642 if (!NeedImplicitASC)
6643 continue;
6644
6645 // First, ensure that the Arg is an RValue.
6646 if (ArgExprs[Idx]->isGLValue()) {
6647 ArgExprs[Idx] = ImplicitCastExpr::Create(
6648 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6649 nullptr, VK_PRValue, FPOptionsOverride());
6650 }
6651
6652 // Construct a new arg type with address space of Param
6653 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6654 ArgPtQuals.setAddressSpace(ParamAS);
6655 auto NewArgPtTy =
6656 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6657 auto NewArgTy =
6659 ArgTy.getQualifiers());
6660
6661 // Finally perform an implicit address space cast
6662 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6663 CK_AddressSpaceConversion)
6664 .get();
6665 }
6666 }
6667 }
6668
6670 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs))) {
6671 assert(!getLangOpts().CPlusPlus);
6672 assert((Fn->containsErrors() ||
6673 llvm::any_of(ArgExprs,
6674 [](clang::Expr *E) { return E->containsErrors(); })) &&
6675 "should only occur in error-recovery path.");
6676 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6677 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6678 }
6679 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6680 ExecConfig, IsExecConfig);
6681}
6682
6684 MultiExprArg CallArgs) {
6685 StringRef Name = Context.BuiltinInfo.getName(Id);
6686 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6688 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6689
6690 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6691 assert(BuiltInDecl && "failed to find builtin declaration");
6692
6693 ExprResult DeclRef =
6694 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6695 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6696
6698 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6699
6700 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6701 return Call.get();
6702}
6703
6705 SourceLocation BuiltinLoc,
6706 SourceLocation RParenLoc) {
6707 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6708 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6709}
6710
6712 SourceLocation BuiltinLoc,
6713 SourceLocation RParenLoc) {
6716 QualType SrcTy = E->getType();
6717 if (!SrcTy->isDependentType() &&
6718 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6719 return ExprError(
6720 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6721 << DestTy << SrcTy << E->getSourceRange());
6722 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6723}
6724
6726 SourceLocation BuiltinLoc,
6727 SourceLocation RParenLoc) {
6728 TypeSourceInfo *TInfo;
6729 GetTypeFromParser(ParsedDestTy, &TInfo);
6730 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6731}
6732
6734 SourceLocation LParenLoc,
6735 ArrayRef<Expr *> Args,
6736 SourceLocation RParenLoc, Expr *Config,
6737 bool IsExecConfig, ADLCallKind UsesADL) {
6738 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6739 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6740
6741 // Functions with 'interrupt' attribute cannot be called directly.
6742 if (FDecl) {
6743 if (FDecl->hasAttr<AnyX86InterruptAttr>()) {
6744 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6745 return ExprError();
6746 }
6747 if (FDecl->hasAttr<ARMInterruptAttr>()) {
6748 Diag(Fn->getExprLoc(), diag::err_arm_interrupt_called);
6749 return ExprError();
6750 }
6751 }
6752
6753 // X86 interrupt handlers may only call routines with attribute
6754 // no_caller_saved_registers since there is no efficient way to
6755 // save and restore the non-GPR state.
6756 if (auto *Caller = getCurFunctionDecl()) {
6757 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6758 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6759 const TargetInfo &TI = Context.getTargetInfo();
6760 bool HasNonGPRRegisters =
6761 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
6762 if (HasNonGPRRegisters &&
6763 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6764 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
6765 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6766 if (FDecl)
6767 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6768 }
6769 }
6770 }
6771
6772 // Promote the function operand.
6773 // We special-case function promotion here because we only allow promoting
6774 // builtin functions to function pointers in the callee of a call.
6776 QualType ResultTy;
6777 if (BuiltinID &&
6778 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6779 // Extract the return type from the (builtin) function pointer type.
6780 // FIXME Several builtins still have setType in
6781 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6782 // Builtins.td to ensure they are correct before removing setType calls.
6783 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6784 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6785 ResultTy = FDecl->getCallResultType();
6786 } else {
6788 ResultTy = Context.BoolTy;
6789 }
6790 if (Result.isInvalid())
6791 return ExprError();
6792 Fn = Result.get();
6793
6794 // Check for a valid function type, but only if it is not a builtin which
6795 // requires custom type checking. These will be handled by
6796 // CheckBuiltinFunctionCall below just after creation of the call expression.
6797 const FunctionType *FuncT = nullptr;
6798 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6799 retry:
6800 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6801 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6802 // have type pointer to function".
6803 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6804 if (!FuncT)
6805 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6806 << Fn->getType() << Fn->getSourceRange());
6807 } else if (const BlockPointerType *BPT =
6808 Fn->getType()->getAs<BlockPointerType>()) {
6809 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6810 } else {
6811 // Handle calls to expressions of unknown-any type.
6812 if (Fn->getType() == Context.UnknownAnyTy) {
6813 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6814 if (rewrite.isInvalid())
6815 return ExprError();
6816 Fn = rewrite.get();
6817 goto retry;
6818 }
6819
6820 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6821 << Fn->getType() << Fn->getSourceRange());
6822 }
6823 }
6824
6825 // Get the number of parameters in the function prototype, if any.
6826 // We will allocate space for max(Args.size(), NumParams) arguments
6827 // in the call expression.
6828 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
6829 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
6830
6831 CallExpr *TheCall;
6832 if (Config) {
6833 assert(UsesADL == ADLCallKind::NotADL &&
6834 "CUDAKernelCallExpr should not use ADL");
6835 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
6836 Args, ResultTy, VK_PRValue, RParenLoc,
6837 CurFPFeatureOverrides(), NumParams);
6838 } else {
6839 TheCall =
6840 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6841 CurFPFeatureOverrides(), NumParams, UsesADL);
6842 }
6843
6845 // Forget about the nulled arguments since typo correction
6846 // do not handle them well.
6847 TheCall->shrinkNumArgs(Args.size());
6848 // C cannot always handle TypoExpr nodes in builtin calls and direct
6849 // function calls as their argument checking don't necessarily handle
6850 // dependent types properly, so make sure any TypoExprs have been
6851 // dealt with.
6853 if (!Result.isUsable()) return ExprError();
6854 CallExpr *TheOldCall = TheCall;
6855 TheCall = dyn_cast<CallExpr>(Result.get());
6856 bool CorrectedTypos = TheCall != TheOldCall;
6857 if (!TheCall) return Result;
6858 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
6859
6860 // A new call expression node was created if some typos were corrected.
6861 // However it may not have been constructed with enough storage. In this
6862 // case, rebuild the node with enough storage. The waste of space is
6863 // immaterial since this only happens when some typos were corrected.
6864 if (CorrectedTypos && Args.size() < NumParams) {
6865 if (Config)
6867 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
6868 RParenLoc, CurFPFeatureOverrides(), NumParams);
6869 else
6870 TheCall =
6871 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
6872 CurFPFeatureOverrides(), NumParams, UsesADL);
6873 }
6874 // We can now handle the nulled arguments for the default arguments.
6875 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
6876 }
6877
6878 // Bail out early if calling a builtin with custom type checking.
6879 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6880 ExprResult E = CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
6881 if (!E.isInvalid() && Context.BuiltinInfo.isImmediate(BuiltinID))
6883 return E;
6884 }
6885
6886 if (getLangOpts().CUDA) {
6887 if (Config) {
6888 // CUDA: Kernel calls must be to global functions
6889 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
6890 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
6891 << FDecl << Fn->getSourceRange());
6892
6893 // CUDA: Kernel function must have 'void' return type
6894 if (!FuncT->getReturnType()->isVoidType() &&
6895 !FuncT->getReturnType()->getAs<AutoType>() &&
6897 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
6898 << Fn->getType() << Fn->getSourceRange());
6899 } else {
6900 // CUDA: Calls to global functions must be configured
6901 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
6902 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
6903 << FDecl << Fn->getSourceRange());
6904 }
6905 }
6906
6907 // Check for a valid return type
6908 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
6909 FDecl))
6910 return ExprError();
6911
6912 // We know the result type of the call, set it.
6913 TheCall->setType(FuncT->getCallResultType(Context));
6915
6916 // WebAssembly tables can't be used as arguments.
6917 if (Context.getTargetInfo().getTriple().isWasm()) {
6918 for (const Expr *Arg : Args) {
6919 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
6920 return ExprError(Diag(Arg->getExprLoc(),
6921 diag::err_wasm_table_as_function_parameter));
6922 }
6923 }
6924 }
6925
6926 if (Proto) {
6927 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
6928 IsExecConfig))
6929 return ExprError();
6930 } else {
6931 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
6932
6933 if (FDecl) {
6934 // Check if we have too few/too many template arguments, based
6935 // on our knowledge of the function definition.
6936 const FunctionDecl *Def = nullptr;
6937 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
6938 Proto = Def->getType()->getAs<FunctionProtoType>();
6939 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
6940 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
6941 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
6942 }
6943
6944 // If the function we're calling isn't a function prototype, but we have
6945 // a function prototype from a prior declaratiom, use that prototype.
6946 if (!FDecl->hasPrototype())
6947 Proto = FDecl->getType()->getAs<FunctionProtoType>();
6948 }
6949
6950 // If we still haven't found a prototype to use but there are arguments to
6951 // the call, diagnose this as calling a function without a prototype.
6952 // However, if we found a function declaration, check to see if
6953 // -Wdeprecated-non-prototype was disabled where the function was declared.
6954 // If so, we will silence the diagnostic here on the assumption that this
6955 // interface is intentional and the user knows what they're doing. We will
6956 // also silence the diagnostic if there is a function declaration but it
6957 // was implicitly defined (the user already gets diagnostics about the
6958 // creation of the implicit function declaration, so the additional warning
6959 // is not helpful).
6960 if (!Proto && !Args.empty() &&
6961 (!FDecl || (!FDecl->isImplicit() &&
6962 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
6963 FDecl->getLocation()))))
6964 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
6965 << (FDecl != nullptr) << FDecl;
6966
6967 // Promote the arguments (C99 6.5.2.2p6).
6968 for (unsigned i = 0, e = Args.size(); i != e; i++) {
6969 Expr *Arg = Args[i];
6970
6971 if (Proto && i < Proto->getNumParams()) {
6973 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
6974 ExprResult ArgE =
6976 if (ArgE.isInvalid())
6977 return true;
6978
6979 Arg = ArgE.getAs<Expr>();
6980
6981 } else {
6983
6984 if (ArgE.isInvalid())
6985 return true;
6986
6987 Arg = ArgE.getAs<Expr>();
6988 }
6989
6990 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
6991 diag::err_call_incomplete_argument, Arg))
6992 return ExprError();
6993
6994 TheCall->setArg(i, Arg);
6995 }
6996 TheCall->computeDependence();
6997 }
6998
6999 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7000 if (Method->isImplicitObjectMemberFunction())
7001 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7002 << Fn->getSourceRange() << 0);
7003
7004 // Check for sentinels
7005 if (NDecl)
7006 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7007
7008 // Warn for unions passing across security boundary (CMSE).
7009 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7010 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7011 if (const auto *RT =
7012 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7013 if (RT->getDecl()->isOrContainsUnion())
7014 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7015 << 0 << i;
7016 }
7017 }
7018 }
7019
7020 // Do special checking on direct calls to functions.
7021 if (FDecl) {
7022 if (CheckFunctionCall(FDecl, TheCall, Proto))
7023 return ExprError();
7024
7025 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7026
7027 if (BuiltinID)
7028 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7029 } else if (NDecl) {
7030 if (CheckPointerCall(NDecl, TheCall, Proto))
7031 return ExprError();
7032 } else {
7033 if (CheckOtherCall(TheCall, Proto))
7034 return ExprError();
7035 }
7036
7037 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7038}
7039
7042 SourceLocation RParenLoc, Expr *InitExpr) {
7043 assert(Ty && "ActOnCompoundLiteral(): missing type");
7044 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7045
7046 TypeSourceInfo *TInfo;
7047 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7048 if (!TInfo)
7049 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7050
7051 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7052}
7053
7056 SourceLocation RParenLoc, Expr *LiteralExpr) {
7057 QualType literalType = TInfo->getType();
7058
7059 if (literalType->isArrayType()) {
7061 LParenLoc, Context.getBaseElementType(literalType),
7062 diag::err_array_incomplete_or_sizeless_type,
7063 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7064 return ExprError();
7065 if (literalType->isVariableArrayType()) {
7066 // C23 6.7.10p4: An entity of variable length array type shall not be
7067 // initialized except by an empty initializer.
7068 //
7069 // The C extension warnings are issued from ParseBraceInitializer() and
7070 // do not need to be issued here. However, we continue to issue an error
7071 // in the case there are initializers or we are compiling C++. We allow
7072 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7073 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7074 // FIXME: should we allow this construct in C++ when it makes sense to do
7075 // so?
7076 //
7077 // But: C99-C23 6.5.2.5 Compound literals constraint 1: The type name
7078 // shall specify an object type or an array of unknown size, but not a
7079 // variable length array type. This seems odd, as it allows 'int a[size] =
7080 // {}', but forbids 'int *a = (int[size]){}'. As this is what the standard
7081 // says, this is what's implemented here for C (except for the extension
7082 // that permits constant foldable size arrays)
7083
7084 auto diagID = LangOpts.CPlusPlus
7085 ? diag::err_variable_object_no_init
7086 : diag::err_compound_literal_with_vla_type;
7087 if (!tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7088 diagID))
7089 return ExprError();
7090 }
7091 } else if (!literalType->isDependentType() &&
7092 RequireCompleteType(LParenLoc, literalType,
7093 diag::err_typecheck_decl_incomplete_type,
7094 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7095 return ExprError();
7096
7097 InitializedEntity Entity
7101 SourceRange(LParenLoc, RParenLoc),
7102 /*InitList=*/true);
7103 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7104 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7105 &literalType);
7106 if (Result.isInvalid())
7107 return ExprError();
7108 LiteralExpr = Result.get();
7109
7110 bool isFileScope = !CurContext->isFunctionOrMethod();
7111
7112 // In C, compound literals are l-values for some reason.
7113 // For GCC compatibility, in C++, file-scope array compound literals with
7114 // constant initializers are also l-values, and compound literals are
7115 // otherwise prvalues.
7116 //
7117 // (GCC also treats C++ list-initialized file-scope array prvalues with
7118 // constant initializers as l-values, but that's non-conforming, so we don't
7119 // follow it there.)
7120 //
7121 // FIXME: It would be better to handle the lvalue cases as materializing and
7122 // lifetime-extending a temporary object, but our materialized temporaries
7123 // representation only supports lifetime extension from a variable, not "out
7124 // of thin air".
7125 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7126 // is bound to the result of applying array-to-pointer decay to the compound
7127 // literal.
7128 // FIXME: GCC supports compound literals of reference type, which should
7129 // obviously have a value kind derived from the kind of reference involved.
7130 ExprValueKind VK =
7131 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7132 ? VK_PRValue
7133 : VK_LValue;
7134
7135 if (isFileScope)
7136 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7137 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7138 Expr *Init = ILE->getInit(i);
7139 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7140 }
7141
7142 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7143 VK, LiteralExpr, isFileScope);
7144 if (isFileScope) {
7145 if (!LiteralExpr->isTypeDependent() &&
7146 !LiteralExpr->isValueDependent() &&
7147 !literalType->isDependentType()) // C99 6.5.2.5p3
7148 if (CheckForConstantInitializer(LiteralExpr))
7149 return ExprError();
7150 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7151 literalType.getAddressSpace() != LangAS::Default) {
7152 // Embedded-C extensions to C99 6.5.2.5:
7153 // "If the compound literal occurs inside the body of a function, the
7154 // type name shall not be qualified by an address-space qualifier."
7155 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7156 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7157 return ExprError();
7158 }
7159
7160 if (!isFileScope && !getLangOpts().CPlusPlus) {
7161 // Compound literals that have automatic storage duration are destroyed at
7162 // the end of the scope in C; in C++, they're just temporaries.
7163
7164 // Emit diagnostics if it is or contains a C union type that is non-trivial
7165 // to destruct.
7169
7170 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7171 if (literalType.isDestructedType()) {
7173 ExprCleanupObjects.push_back(E);
7175 }
7176 }
7177
7180 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7181 E->getInitializer()->getExprLoc());
7182
7183 return MaybeBindToTemporary(E);
7184}
7185
7188 SourceLocation RBraceLoc) {
7189 // Only produce each kind of designated initialization diagnostic once.
7190 SourceLocation FirstDesignator;
7191 bool DiagnosedArrayDesignator = false;
7192 bool DiagnosedNestedDesignator = false;
7193 bool DiagnosedMixedDesignator = false;
7194
7195 // Check that any designated initializers are syntactically valid in the
7196 // current language mode.
7197 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7198 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7199 if (FirstDesignator.isInvalid())
7200 FirstDesignator = DIE->getBeginLoc();
7201
7202 if (!getLangOpts().CPlusPlus)
7203 break;
7204
7205 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7206 DiagnosedNestedDesignator = true;
7207 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7208 << DIE->getDesignatorsSourceRange();
7209 }
7210
7211 for (auto &Desig : DIE->designators()) {
7212 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7213 DiagnosedArrayDesignator = true;
7214 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7215 << Desig.getSourceRange();
7216 }
7217 }
7218
7219 if (!DiagnosedMixedDesignator &&
7220 !isa<DesignatedInitExpr>(InitArgList[0])) {
7221 DiagnosedMixedDesignator = true;
7222 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7223 << DIE->getSourceRange();
7224 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7225 << InitArgList[0]->getSourceRange();
7226 }
7227 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7228 isa<DesignatedInitExpr>(InitArgList[0])) {
7229 DiagnosedMixedDesignator = true;
7230 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7231 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7232 << DIE->getSourceRange();
7233 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7234 << InitArgList[I]->getSourceRange();
7235 }
7236 }
7237
7238 if (FirstDesignator.isValid()) {
7239 // Only diagnose designated initiaization as a C++20 extension if we didn't
7240 // already diagnose use of (non-C++20) C99 designator syntax.
7241 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7242 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7243 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7244 ? diag::warn_cxx17_compat_designated_init
7245 : diag::ext_cxx_designated_init);
7246 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7247 Diag(FirstDesignator, diag::ext_designated_init);
7248 }
7249 }
7250
7251 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7252}
7253
7256 SourceLocation RBraceLoc) {
7257 // Semantic analysis for initializers is done by ActOnDeclarator() and
7258 // CheckInitializer() - it requires knowledge of the object being initialized.
7259
7260 // Immediately handle non-overload placeholders. Overloads can be
7261 // resolved contextually, but everything else here can't.
7262 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7263 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7264 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7265
7266 // Ignore failures; dropping the entire initializer list because
7267 // of one failure would be terrible for indexing/etc.
7268 if (result.isInvalid()) continue;
7269
7270 InitArgList[I] = result.get();
7271 }
7272 }
7273
7274 InitListExpr *E =
7275 new (Context) InitListExpr(Context, LBraceLoc, InitArgList, RBraceLoc);
7276 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7277 return E;
7278}
7279
7281 assert(E.get()->getType()->isBlockPointerType());
7282 assert(E.get()->isPRValue());
7283
7284 // Only do this in an r-value context.
7285 if (!getLangOpts().ObjCAutoRefCount) return;
7286
7288 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7289 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7291}
7292
7294 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7295 // Also, callers should have filtered out the invalid cases with
7296 // pointers. Everything else should be possible.
7297
7298 QualType SrcTy = Src.get()->getType();
7299 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7300 return CK_NoOp;
7301
7302 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7304 llvm_unreachable("member pointer type in C");
7305
7306 case Type::STK_CPointer:
7309 switch (DestTy->getScalarTypeKind()) {
7310 case Type::STK_CPointer: {
7311 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7312 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7313 if (SrcAS != DestAS)
7314 return CK_AddressSpaceConversion;
7315 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7316 return CK_NoOp;
7317 return CK_BitCast;
7318 }
7320 return (SrcKind == Type::STK_BlockPointer
7321 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7323 if (SrcKind == Type::STK_ObjCObjectPointer)
7324 return CK_BitCast;
7325 if (SrcKind == Type::STK_CPointer)
7326 return CK_CPointerToObjCPointerCast;
7328 return CK_BlockPointerToObjCPointerCast;
7329 case Type::STK_Bool:
7330 return CK_PointerToBoolean;
7331 case Type::STK_Integral:
7332 return CK_PointerToIntegral;
7333 case Type::STK_Floating:
7338 llvm_unreachable("illegal cast from pointer");
7339 }
7340 llvm_unreachable("Should have returned before this");
7341
7343 switch (DestTy->getScalarTypeKind()) {
7345 return CK_FixedPointCast;
7346 case Type::STK_Bool:
7347 return CK_FixedPointToBoolean;
7348 case Type::STK_Integral:
7349 return CK_FixedPointToIntegral;
7350 case Type::STK_Floating:
7351 return CK_FixedPointToFloating;
7354 Diag(Src.get()->getExprLoc(),
7355 diag::err_unimplemented_conversion_with_fixed_point_type)
7356 << DestTy;
7357 return CK_IntegralCast;
7358 case Type::STK_CPointer:
7362 llvm_unreachable("illegal cast to pointer type");
7363 }
7364 llvm_unreachable("Should have returned before this");
7365
7366 case Type::STK_Bool: // casting from bool is like casting from an integer
7367 case Type::STK_Integral:
7368 switch (DestTy->getScalarTypeKind()) {
7369 case Type::STK_CPointer:
7374 return CK_NullToPointer;
7375 return CK_IntegralToPointer;
7376 case Type::STK_Bool:
7377 return CK_IntegralToBoolean;
7378 case Type::STK_Integral:
7379 return CK_IntegralCast;
7380 case Type::STK_Floating:
7381 return CK_IntegralToFloating;
7383 Src = ImpCastExprToType(Src.get(),
7384 DestTy->castAs<ComplexType>()->getElementType(),
7385 CK_IntegralCast);
7386 return CK_IntegralRealToComplex;
7388 Src = ImpCastExprToType(Src.get(),
7389 DestTy->castAs<ComplexType>()->getElementType(),
7390 CK_IntegralToFloating);
7391 return CK_FloatingRealToComplex;
7393 llvm_unreachable("member pointer type in C");
7395 return CK_IntegralToFixedPoint;
7396 }
7397 llvm_unreachable("Should have returned before this");
7398
7399 case Type::STK_Floating:
7400 switch (DestTy->getScalarTypeKind()) {
7401 case Type::STK_Floating:
7402 return CK_FloatingCast;
7403 case Type::STK_Bool:
7404 return CK_FloatingToBoolean;
7405 case Type::STK_Integral:
7406 return CK_FloatingToIntegral;
7408 Src = ImpCastExprToType(Src.get(),
7409 DestTy->castAs<ComplexType>()->getElementType(),
7410 CK_FloatingCast);
7411 return CK_FloatingRealToComplex;
7413 Src = ImpCastExprToType(Src.get(),
7414 DestTy->castAs<ComplexType>()->getElementType(),
7415 CK_FloatingToIntegral);
7416 return CK_IntegralRealToComplex;
7417 case Type::STK_CPointer:
7420 llvm_unreachable("valid float->pointer cast?");
7422 llvm_unreachable("member pointer type in C");
7424 return CK_FloatingToFixedPoint;
7425 }
7426 llvm_unreachable("Should have returned before this");
7427
7429 switch (DestTy->getScalarTypeKind()) {
7431 return CK_FloatingComplexCast;
7433 return CK_FloatingComplexToIntegralComplex;
7434 case Type::STK_Floating: {
7435 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7436 if (Context.hasSameType(ET, DestTy))
7437 return CK_FloatingComplexToReal;
7438 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7439 return CK_FloatingCast;
7440 }
7441 case Type::STK_Bool:
7442 return CK_FloatingComplexToBoolean;
7443 case Type::STK_Integral:
7444 Src = ImpCastExprToType(Src.get(),
7445 SrcTy->castAs<ComplexType>()->getElementType(),
7446 CK_FloatingComplexToReal);
7447 return CK_FloatingToIntegral;
7448 case Type::STK_CPointer:
7451 llvm_unreachable("valid complex float->pointer cast?");
7453 llvm_unreachable("member pointer type in C");
7455 Diag(Src.get()->getExprLoc(),
7456 diag::err_unimplemented_conversion_with_fixed_point_type)
7457 << SrcTy;
7458 return CK_IntegralCast;
7459 }
7460 llvm_unreachable("Should have returned before this");
7461
7463 switch (DestTy->getScalarTypeKind()) {
7465 return CK_IntegralComplexToFloatingComplex;
7467 return CK_IntegralComplexCast;
7468 case Type::STK_Integral: {
7469 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7470 if (Context.hasSameType(ET, DestTy))
7471 return CK_IntegralComplexToReal;
7472 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7473 return CK_IntegralCast;
7474 }
7475 case Type::STK_Bool:
7476 return CK_IntegralComplexToBoolean;
7477 case Type::STK_Floating:
7478 Src = ImpCastExprToType(Src.get(),
7479 SrcTy->castAs<ComplexType>()->getElementType(),
7480 CK_IntegralComplexToReal);
7481 return CK_IntegralToFloating;
7482 case Type::STK_CPointer:
7485 llvm_unreachable("valid complex int->pointer cast?");
7487 llvm_unreachable("member pointer type in C");
7489 Diag(Src.get()->getExprLoc(),
7490 diag::err_unimplemented_conversion_with_fixed_point_type)
7491 << SrcTy;
7492 return CK_IntegralCast;
7493 }
7494 llvm_unreachable("Should have returned before this");
7495 }
7496
7497 llvm_unreachable("Unhandled scalar cast");
7498}
7499
7500static bool breakDownVectorType(QualType type, uint64_t &len,
7501 QualType &eltType) {
7502 // Vectors are simple.
7503 if (const VectorType *vecType = type->getAs<VectorType>()) {
7504 len = vecType->getNumElements();
7505 eltType = vecType->getElementType();
7506 assert(eltType->isScalarType() || eltType->isMFloat8Type());
7507 return true;
7508 }
7509
7510 // We allow lax conversion to and from non-vector types, but only if
7511 // they're real types (i.e. non-complex, non-pointer scalar types).
7512 if (!type->isRealType()) return false;
7513
7514 len = 1;
7515 eltType = type;
7516 return true;
7517}
7518
7520 assert(srcTy->isVectorType() || destTy->isVectorType());
7521
7522 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7523 if (!FirstType->isSVESizelessBuiltinType())
7524 return false;
7525
7526 const auto *VecTy = SecondType->getAs<VectorType>();
7527 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7528 };
7529
7530 return ValidScalableConversion(srcTy, destTy) ||
7531 ValidScalableConversion(destTy, srcTy);
7532}
7533
7535 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7536 return false;
7537
7538 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7539 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7540
7541 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7542 matSrcType->getNumColumns() == matDestType->getNumColumns();
7543}
7544
7546 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7547
7548 uint64_t SrcLen, DestLen;
7549 QualType SrcEltTy, DestEltTy;
7550 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7551 return false;
7552 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7553 return false;
7554
7555 // ASTContext::getTypeSize will return the size rounded up to a
7556 // power of 2, so instead of using that, we need to use the raw
7557 // element size multiplied by the element count.
7558 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7559 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7560
7561 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7562}
7563
7565 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7566 "expected at least one type to be a vector here");
7567
7568 bool IsSrcTyAltivec =
7569 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7571 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7573 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7575
7576 bool IsDestTyAltivec = DestTy->isVectorType() &&
7577 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7579 (DestTy->castAs<VectorType>()->getVectorKind() ==
7581 (DestTy->castAs<VectorType>()->getVectorKind() ==
7583
7584 return (IsSrcTyAltivec || IsDestTyAltivec);
7585}
7586
7588 assert(destTy->isVectorType() || srcTy->isVectorType());
7589
7590 // Disallow lax conversions between scalars and ExtVectors (these
7591 // conversions are allowed for other vector types because common headers
7592 // depend on them). Most scalar OP ExtVector cases are handled by the
7593 // splat path anyway, which does what we want (convert, not bitcast).
7594 // What this rules out for ExtVectors is crazy things like char4*float.
7595 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7596 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7597
7598 return areVectorTypesSameSize(srcTy, destTy);
7599}
7600
7602 assert(destTy->isVectorType() || srcTy->isVectorType());
7603
7604 switch (Context.getLangOpts().getLaxVectorConversions()) {
7606 return false;
7607
7609 if (!srcTy->isIntegralOrEnumerationType()) {
7610 auto *Vec = srcTy->getAs<VectorType>();
7611 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7612 return false;
7613 }
7614 if (!destTy->isIntegralOrEnumerationType()) {
7615 auto *Vec = destTy->getAs<VectorType>();
7616 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7617 return false;
7618 }
7619 // OK, integer (vector) -> integer (vector) bitcast.
7620 break;
7621
7623 break;
7624 }
7625
7626 return areLaxCompatibleVectorTypes(srcTy, destTy);
7627}
7628
7630 CastKind &Kind) {
7631 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7632 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7633 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7634 << DestTy << SrcTy << R;
7635 }
7636 } else if (SrcTy->isMatrixType()) {
7637 return Diag(R.getBegin(),
7638 diag::err_invalid_conversion_between_matrix_and_type)
7639 << SrcTy << DestTy << R;
7640 } else if (DestTy->isMatrixType()) {
7641 return Diag(R.getBegin(),
7642 diag::err_invalid_conversion_between_matrix_and_type)
7643 << DestTy << SrcTy << R;
7644 }
7645
7646 Kind = CK_MatrixCast;
7647 return false;
7648}
7649
7651 CastKind &Kind) {
7652 assert(VectorTy->isVectorType() && "Not a vector type!");
7653
7654 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7655 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7656 return Diag(R.getBegin(),
7657 Ty->isVectorType() ?
7658 diag::err_invalid_conversion_between_vectors :
7659 diag::err_invalid_conversion_between_vector_and_integer)
7660 << VectorTy << Ty << R;
7661 } else
7662 return Diag(R.getBegin(),
7663 diag::err_invalid_conversion_between_vector_and_scalar)
7664 << VectorTy << Ty << R;
7665
7666 Kind = CK_BitCast;
7667 return false;
7668}
7669
7671 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7672
7673 if (DestElemTy == SplattedExpr->getType())
7674 return SplattedExpr;
7675
7676 assert(DestElemTy->isFloatingType() ||
7677 DestElemTy->isIntegralOrEnumerationType());
7678
7679 CastKind CK;
7680 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7681 // OpenCL requires that we convert `true` boolean expressions to -1, but
7682 // only when splatting vectors.
7683 if (DestElemTy->isFloatingType()) {
7684 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7685 // in two steps: boolean to signed integral, then to floating.
7686 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7687 CK_BooleanToSignedIntegral);
7688 SplattedExpr = CastExprRes.get();
7689 CK = CK_IntegralToFloating;
7690 } else {
7691 CK = CK_BooleanToSignedIntegral;
7692 }
7693 } else {
7694 ExprResult CastExprRes = SplattedExpr;
7695 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7696 if (CastExprRes.isInvalid())
7697 return ExprError();
7698 SplattedExpr = CastExprRes.get();
7699 }
7700 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7701}
7702
7704 Expr *CastExpr, CastKind &Kind) {
7705 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7706
7707 QualType SrcTy = CastExpr->getType();
7708
7709 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7710 // an ExtVectorType.
7711 // In OpenCL, casts between vectors of different types are not allowed.
7712 // (See OpenCL 6.2).
7713 if (SrcTy->isVectorType()) {
7714 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7715 (getLangOpts().OpenCL &&
7716 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7717 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7718 << DestTy << SrcTy << R;
7719 return ExprError();
7720 }
7721 Kind = CK_BitCast;
7722 return CastExpr;
7723 }
7724
7725 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7726 // conversion will take place first from scalar to elt type, and then
7727 // splat from elt type to vector.
7728 if (SrcTy->isPointerType())
7729 return Diag(R.getBegin(),
7730 diag::err_invalid_conversion_between_vector_and_scalar)
7731 << DestTy << SrcTy << R;
7732
7733 Kind = CK_VectorSplat;
7734 return prepareVectorSplat(DestTy, CastExpr);
7735}
7736
7739 Declarator &D, ParsedType &Ty,
7740 SourceLocation RParenLoc, Expr *CastExpr) {
7741 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7742 "ActOnCastExpr(): missing type or expr");
7743
7745 if (D.isInvalidType())
7746 return ExprError();
7747
7748 if (getLangOpts().CPlusPlus) {
7749 // Check that there are no default arguments (C++ only).
7751 } else {
7752 // Make sure any TypoExprs have been dealt with.
7754 if (!Res.isUsable())
7755 return ExprError();
7756 CastExpr = Res.get();
7757 }
7758
7760
7761 QualType castType = castTInfo->getType();
7762 Ty = CreateParsedType(castType, castTInfo);
7763
7764 bool isVectorLiteral = false;
7765
7766 // Check for an altivec or OpenCL literal,
7767 // i.e. all the elements are integer constants.
7768 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
7769 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
7770 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
7771 && castType->isVectorType() && (PE || PLE)) {
7772 if (PLE && PLE->getNumExprs() == 0) {
7773 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
7774 return ExprError();
7775 }
7776 if (PE || PLE->getNumExprs() == 1) {
7777 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
7778 if (!E->isTypeDependent() && !E->getType()->isVectorType())
7779 isVectorLiteral = true;
7780 }
7781 else
7782 isVectorLiteral = true;
7783 }
7784
7785 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
7786 // then handle it as such.
7787 if (isVectorLiteral)
7788 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
7789
7790 // If the Expr being casted is a ParenListExpr, handle it specially.
7791 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
7792 // sequence of BinOp comma operators.
7793 if (isa<ParenListExpr>(CastExpr)) {
7795 if (Result.isInvalid()) return ExprError();
7796 CastExpr = Result.get();
7797 }
7798
7799 if (getLangOpts().CPlusPlus && !castType->isVoidType())
7800 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
7801
7803
7805
7807
7808 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
7809}
7810
7812 SourceLocation RParenLoc, Expr *E,
7813 TypeSourceInfo *TInfo) {
7814 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
7815 "Expected paren or paren list expression");
7816
7817 Expr **exprs;
7818 unsigned numExprs;
7819 Expr *subExpr;
7820 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
7821 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
7822 LiteralLParenLoc = PE->getLParenLoc();
7823 LiteralRParenLoc = PE->getRParenLoc();
7824 exprs = PE->getExprs();
7825 numExprs = PE->getNumExprs();
7826 } else { // isa<ParenExpr> by assertion at function entrance
7827 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
7828 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
7829 subExpr = cast<ParenExpr>(E)->getSubExpr();
7830 exprs = &subExpr;
7831 numExprs = 1;
7832 }
7833
7834 QualType Ty = TInfo->getType();
7835 assert(Ty->isVectorType() && "Expected vector type");
7836
7837 SmallVector<Expr *, 8> initExprs;
7838 const VectorType *VTy = Ty->castAs<VectorType>();
7839 unsigned numElems = VTy->getNumElements();
7840
7841 // '(...)' form of vector initialization in AltiVec: the number of
7842 // initializers must be one or must match the size of the vector.
7843 // If a single value is specified in the initializer then it will be
7844 // replicated to all the components of the vector
7846 VTy->getElementType()))
7847 return ExprError();
7849 // The number of initializers must be one or must match the size of the
7850 // vector. If a single value is specified in the initializer then it will
7851 // be replicated to all the components of the vector
7852 if (numExprs == 1) {
7853 QualType ElemTy = VTy->getElementType();
7854 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7855 if (Literal.isInvalid())
7856 return ExprError();
7857 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7858 PrepareScalarCast(Literal, ElemTy));
7859 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7860 }
7861 else if (numExprs < numElems) {
7862 Diag(E->getExprLoc(),
7863 diag::err_incorrect_number_of_vector_initializers);
7864 return ExprError();
7865 }
7866 else
7867 initExprs.append(exprs, exprs + numExprs);
7868 }
7869 else {
7870 // For OpenCL, when the number of initializers is a single value,
7871 // it will be replicated to all components of the vector.
7873 numExprs == 1) {
7874 QualType ElemTy = VTy->getElementType();
7875 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
7876 if (Literal.isInvalid())
7877 return ExprError();
7878 Literal = ImpCastExprToType(Literal.get(), ElemTy,
7879 PrepareScalarCast(Literal, ElemTy));
7880 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
7881 }
7882
7883 initExprs.append(exprs, exprs + numExprs);
7884 }
7885 // FIXME: This means that pretty-printing the final AST will produce curly
7886 // braces instead of the original commas.
7887 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
7888 initExprs, LiteralRParenLoc);
7889 initE->setType(Ty);
7890 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
7891}
7892
7895 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
7896 if (!E)
7897 return OrigExpr;
7898
7899 ExprResult Result(E->getExpr(0));
7900
7901 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
7902 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
7903 E->getExpr(i));
7904
7905 if (Result.isInvalid()) return ExprError();
7906
7907 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
7908}
7909
7912 MultiExprArg Val) {
7913 return ParenListExpr::Create(Context, L, Val, R);
7914}
7915
7916bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
7917 SourceLocation QuestionLoc) {
7918 const Expr *NullExpr = LHSExpr;
7919 const Expr *NonPointerExpr = RHSExpr;
7923
7924 if (NullKind == Expr::NPCK_NotNull) {
7925 NullExpr = RHSExpr;
7926 NonPointerExpr = LHSExpr;
7927 NullKind =
7930 }
7931
7932 if (NullKind == Expr::NPCK_NotNull)
7933 return false;
7934
7935 if (NullKind == Expr::NPCK_ZeroExpression)
7936 return false;
7937
7938 if (NullKind == Expr::NPCK_ZeroLiteral) {
7939 // In this case, check to make sure that we got here from a "NULL"
7940 // string in the source code.
7941 NullExpr = NullExpr->IgnoreParenImpCasts();
7942 SourceLocation loc = NullExpr->getExprLoc();
7943 if (!findMacroSpelling(loc, "NULL"))
7944 return false;
7945 }
7946
7947 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
7948 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
7949 << NonPointerExpr->getType() << DiagType
7950 << NonPointerExpr->getSourceRange();
7951 return true;
7952}
7953
7954/// Return false if the condition expression is valid, true otherwise.
7955static bool checkCondition(Sema &S, const Expr *Cond,
7956 SourceLocation QuestionLoc) {
7957 QualType CondTy = Cond->getType();
7958
7959 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
7960 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
7961 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7962 << CondTy << Cond->getSourceRange();
7963 return true;
7964 }
7965
7966 // C99 6.5.15p2
7967 if (CondTy->isScalarType()) return false;
7968
7969 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
7970 << CondTy << Cond->getSourceRange();
7971 return true;
7972}
7973
7974/// Return false if the NullExpr can be promoted to PointerTy,
7975/// true otherwise.
7977 QualType PointerTy) {
7978 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
7979 !NullExpr.get()->isNullPointerConstant(S.Context,
7981 return true;
7982
7983 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
7984 return false;
7985}
7986
7987/// Checks compatibility between two pointers and return the resulting
7988/// type.
7990 ExprResult &RHS,
7992 QualType LHSTy = LHS.get()->getType();
7993 QualType RHSTy = RHS.get()->getType();
7994
7995 if (S.Context.hasSameType(LHSTy, RHSTy)) {
7996 // Two identical pointers types are always compatible.
7997 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
7998 }
7999
8000 QualType lhptee, rhptee;
8001
8002 // Get the pointee types.
8003 bool IsBlockPointer = false;
8004 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8005 lhptee = LHSBTy->getPointeeType();
8006 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8007 IsBlockPointer = true;
8008 } else {
8009 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8010 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8011 }
8012
8013 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8014 // differently qualified versions of compatible types, the result type is
8015 // a pointer to an appropriately qualified version of the composite
8016 // type.
8017
8018 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8019 // clause doesn't make sense for our extensions. E.g. address space 2 should
8020 // be incompatible with address space 3: they may live on different devices or
8021 // anything.
8022 Qualifiers lhQual = lhptee.getQualifiers();
8023 Qualifiers rhQual = rhptee.getQualifiers();
8024
8025 LangAS ResultAddrSpace = LangAS::Default;
8026 LangAS LAddrSpace = lhQual.getAddressSpace();
8027 LangAS RAddrSpace = rhQual.getAddressSpace();
8028
8029 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8030 // spaces is disallowed.
8031 if (lhQual.isAddressSpaceSupersetOf(rhQual, S.getASTContext()))
8032 ResultAddrSpace = LAddrSpace;
8033 else if (rhQual.isAddressSpaceSupersetOf(lhQual, S.getASTContext()))
8034 ResultAddrSpace = RAddrSpace;
8035 else {
8036 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8037 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8038 << RHS.get()->getSourceRange();
8039 return QualType();
8040 }
8041
8042 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8043 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8044 lhQual.removeCVRQualifiers();
8045 rhQual.removeCVRQualifiers();
8046
8047 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8048 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8049 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8050 // qual types are compatible iff
8051 // * corresponded types are compatible
8052 // * CVR qualifiers are equal
8053 // * address spaces are equal
8054 // Thus for conditional operator we merge CVR and address space unqualified
8055 // pointees and if there is a composite type we return a pointer to it with
8056 // merged qualifiers.
8057 LHSCastKind =
8058 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8059 RHSCastKind =
8060 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8061 lhQual.removeAddressSpace();
8062 rhQual.removeAddressSpace();
8063
8064 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8065 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8066
8067 QualType CompositeTy = S.Context.mergeTypes(
8068 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8069 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8070
8071 if (CompositeTy.isNull()) {
8072 // In this situation, we assume void* type. No especially good
8073 // reason, but this is what gcc does, and we do have to pick
8074 // to get a consistent AST.
8075 QualType incompatTy;
8076 incompatTy = S.Context.getPointerType(
8077 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8078 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8079 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8080
8081 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8082 // for casts between types with incompatible address space qualifiers.
8083 // For the following code the compiler produces casts between global and
8084 // local address spaces of the corresponded innermost pointees:
8085 // local int *global *a;
8086 // global int *global *b;
8087 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8088 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8089 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8090 << RHS.get()->getSourceRange();
8091
8092 return incompatTy;
8093 }
8094
8095 // The pointer types are compatible.
8096 // In case of OpenCL ResultTy should have the address space qualifier
8097 // which is a superset of address spaces of both the 2nd and the 3rd
8098 // operands of the conditional operator.
8099 QualType ResultTy = [&, ResultAddrSpace]() {
8100 if (S.getLangOpts().OpenCL) {
8101 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8102 CompositeQuals.setAddressSpace(ResultAddrSpace);
8103 return S.Context
8104 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8105 .withCVRQualifiers(MergedCVRQual);
8106 }
8107 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8108 }();
8109 if (IsBlockPointer)
8110 ResultTy = S.Context.getBlockPointerType(ResultTy);
8111 else
8112 ResultTy = S.Context.getPointerType(ResultTy);
8113
8114 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8115 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8116 return ResultTy;
8117}
8118
8119/// Return the resulting type when the operands are both block pointers.
8121 ExprResult &LHS,
8122 ExprResult &RHS,
8124 QualType LHSTy = LHS.get()->getType();
8125 QualType RHSTy = RHS.get()->getType();
8126
8127 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8128 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8130 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8131 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8132 return destType;
8133 }
8134 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8135 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8136 << RHS.get()->getSourceRange();
8137 return QualType();
8138 }
8139
8140 // We have 2 block pointer types.
8141 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8142}
8143
8144/// Return the resulting type when the operands are both pointers.
8145static QualType
8147 ExprResult &RHS,
8149 // get the pointer types
8150 QualType LHSTy = LHS.get()->getType();
8151 QualType RHSTy = RHS.get()->getType();
8152
8153 // get the "pointed to" types
8154 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8155 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8156
8157 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8158 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8159 // Figure out necessary qualifiers (C99 6.5.15p6)
8160 QualType destPointee
8161 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8162 QualType destType = S.Context.getPointerType(destPointee);
8163 // Add qualifiers if necessary.
8164 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8165 // Promote to void*.
8166 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8167 return destType;
8168 }
8169 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8170 QualType destPointee
8171 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8172 QualType destType = S.Context.getPointerType(destPointee);
8173 // Add qualifiers if necessary.
8174 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8175 // Promote to void*.
8176 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8177 return destType;
8178 }
8179
8180 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8181}
8182
8183/// Return false if the first expression is not an integer and the second
8184/// expression is not a pointer, true otherwise.
8186 Expr* PointerExpr, SourceLocation Loc,
8187 bool IsIntFirstExpr) {
8188 if (!PointerExpr->getType()->isPointerType() ||
8189 !Int.get()->getType()->isIntegerType())
8190 return false;
8191
8192 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8193 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8194
8195 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8196 << Expr1->getType() << Expr2->getType()
8197 << Expr1->getSourceRange() << Expr2->getSourceRange();
8198 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8199 CK_IntegralToPointer);
8200 return true;
8201}
8202
8203/// Simple conversion between integer and floating point types.
8204///
8205/// Used when handling the OpenCL conditional operator where the
8206/// condition is a vector while the other operands are scalar.
8207///
8208/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8209/// types are either integer or floating type. Between the two
8210/// operands, the type with the higher rank is defined as the "result
8211/// type". The other operand needs to be promoted to the same type. No
8212/// other type promotion is allowed. We cannot use
8213/// UsualArithmeticConversions() for this purpose, since it always
8214/// promotes promotable types.
8216 ExprResult &RHS,
8217 SourceLocation QuestionLoc) {
8219 if (LHS.isInvalid())
8220 return QualType();
8222 if (RHS.isInvalid())
8223 return QualType();
8224
8225 // For conversion purposes, we ignore any qualifiers.
8226 // For example, "const float" and "float" are equivalent.
8227 QualType LHSType =
8229 QualType RHSType =
8231
8232 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8233 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8234 << LHSType << LHS.get()->getSourceRange();
8235 return QualType();
8236 }
8237
8238 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8239 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8240 << RHSType << RHS.get()->getSourceRange();
8241 return QualType();
8242 }
8243
8244 // If both types are identical, no conversion is needed.
8245 if (LHSType == RHSType)
8246 return LHSType;
8247
8248 // Now handle "real" floating types (i.e. float, double, long double).
8249 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8250 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8251 /*IsCompAssign = */ false);
8252
8253 // Finally, we have two differing integer types.
8254 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8255 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8256}
8257
8258/// Convert scalar operands to a vector that matches the
8259/// condition in length.
8260///
8261/// Used when handling the OpenCL conditional operator where the
8262/// condition is a vector while the other operands are scalar.
8263///
8264/// We first compute the "result type" for the scalar operands
8265/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8266/// into a vector of that type where the length matches the condition
8267/// vector type. s6.11.6 requires that the element types of the result
8268/// and the condition must have the same number of bits.
8269static QualType
8271 QualType CondTy, SourceLocation QuestionLoc) {
8272 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8273 if (ResTy.isNull()) return QualType();
8274
8275 const VectorType *CV = CondTy->getAs<VectorType>();
8276 assert(CV);
8277
8278 // Determine the vector result type
8279 unsigned NumElements = CV->getNumElements();
8280 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8281
8282 // Ensure that all types have the same number of bits
8284 != S.Context.getTypeSize(ResTy)) {
8285 // Since VectorTy is created internally, it does not pretty print
8286 // with an OpenCL name. Instead, we just print a description.
8287 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8288 SmallString<64> Str;
8289 llvm::raw_svector_ostream OS(Str);
8290 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8291 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8292 << CondTy << OS.str();
8293 return QualType();
8294 }
8295
8296 // Convert operands to the vector result type
8297 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8298 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8299
8300 return VectorTy;
8301}
8302
8303/// Return false if this is a valid OpenCL condition vector
8305 SourceLocation QuestionLoc) {
8306 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8307 // integral type.
8308 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8309 assert(CondTy);
8310 QualType EleTy = CondTy->getElementType();
8311 if (EleTy->isIntegerType()) return false;
8312
8313 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8314 << Cond->getType() << Cond->getSourceRange();
8315 return true;
8316}
8317
8318/// Return false if the vector condition type and the vector
8319/// result type are compatible.
8320///
8321/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8322/// number of elements, and their element types have the same number
8323/// of bits.
8324static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8325 SourceLocation QuestionLoc) {
8326 const VectorType *CV = CondTy->getAs<VectorType>();
8327 const VectorType *RV = VecResTy->getAs<VectorType>();
8328 assert(CV && RV);
8329
8330 if (CV->getNumElements() != RV->getNumElements()) {
8331 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8332 << CondTy << VecResTy;
8333 return true;
8334 }
8335
8336 QualType CVE = CV->getElementType();
8337 QualType RVE = RV->getElementType();
8338
8339 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8340 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8341 << CondTy << VecResTy;
8342 return true;
8343 }
8344
8345 return false;
8346}
8347
8348/// Return the resulting type for the conditional operator in
8349/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8350/// s6.3.i) when the condition is a vector type.
8351static QualType
8353 ExprResult &LHS, ExprResult &RHS,
8354 SourceLocation QuestionLoc) {
8356 if (Cond.isInvalid())
8357 return QualType();
8358 QualType CondTy = Cond.get()->getType();
8359
8360 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8361 return QualType();
8362
8363 // If either operand is a vector then find the vector type of the
8364 // result as specified in OpenCL v1.1 s6.3.i.
8365 if (LHS.get()->getType()->isVectorType() ||
8366 RHS.get()->getType()->isVectorType()) {
8367 bool IsBoolVecLang =
8368 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8369 QualType VecResTy =
8370 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8371 /*isCompAssign*/ false,
8372 /*AllowBothBool*/ true,
8373 /*AllowBoolConversions*/ false,
8374 /*AllowBooleanOperation*/ IsBoolVecLang,
8375 /*ReportInvalid*/ true);
8376 if (VecResTy.isNull())
8377 return QualType();
8378 // The result type must match the condition type as specified in
8379 // OpenCL v1.1 s6.11.6.
8380 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8381 return QualType();
8382 return VecResTy;
8383 }
8384
8385 // Both operands are scalar.
8386 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8387}
8388
8389/// Return true if the Expr is block type
8390static bool checkBlockType(Sema &S, const Expr *E) {
8391 if (E->getType()->isBlockPointerType()) {
8392 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8393 return true;
8394 }
8395
8396 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8397 QualType Ty = CE->getCallee()->getType();
8398 if (Ty->isBlockPointerType()) {
8399 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8400 return true;
8401 }
8402 }
8403 return false;
8404}
8405
8406/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8407/// In that case, LHS = cond.
8408/// C99 6.5.15
8410 ExprResult &RHS, ExprValueKind &VK,
8411 ExprObjectKind &OK,
8412 SourceLocation QuestionLoc) {
8413
8414 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8415 if (!LHSResult.isUsable()) return QualType();
8416 LHS = LHSResult;
8417
8418 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8419 if (!RHSResult.isUsable()) return QualType();
8420 RHS = RHSResult;
8421
8422 // C++ is sufficiently different to merit its own checker.
8423 if (getLangOpts().CPlusPlus)
8424 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8425
8426 VK = VK_PRValue;
8427 OK = OK_Ordinary;
8428
8430 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8431 RHS.get()->isTypeDependent())) {
8432 assert(!getLangOpts().CPlusPlus);
8433 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8434 RHS.get()->containsErrors()) &&
8435 "should only occur in error-recovery path.");
8436 return Context.DependentTy;
8437 }
8438
8439 // The OpenCL operator with a vector condition is sufficiently
8440 // different to merit its own checker.
8441 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8442 Cond.get()->getType()->isExtVectorType())
8443 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8444
8445 // First, check the condition.
8446 Cond = UsualUnaryConversions(Cond.get());
8447 if (Cond.isInvalid())
8448 return QualType();
8449 if (checkCondition(*this, Cond.get(), QuestionLoc))
8450 return QualType();
8451
8452 // Handle vectors.
8453 if (LHS.get()->getType()->isVectorType() ||
8454 RHS.get()->getType()->isVectorType())
8455 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8456 /*AllowBothBool*/ true,
8457 /*AllowBoolConversions*/ false,
8458 /*AllowBooleanOperation*/ false,
8459 /*ReportInvalid*/ true);
8460
8461 QualType ResTy =
8462 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8463 if (LHS.isInvalid() || RHS.isInvalid())
8464 return QualType();
8465
8466 // WebAssembly tables are not allowed as conditional LHS or RHS.
8467 QualType LHSTy = LHS.get()->getType();
8468 QualType RHSTy = RHS.get()->getType();
8469 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8470 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8471 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8472 return QualType();
8473 }
8474
8475 // Diagnose attempts to convert between __ibm128, __float128 and long double
8476 // where such conversions currently can't be handled.
8477 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8478 Diag(QuestionLoc,
8479 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8480 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8481 return QualType();
8482 }
8483
8484 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8485 // selection operator (?:).
8486 if (getLangOpts().OpenCL &&
8487 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8488 return QualType();
8489 }
8490
8491 // If both operands have arithmetic type, do the usual arithmetic conversions
8492 // to find a common type: C99 6.5.15p3,5.
8493 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8494 // Disallow invalid arithmetic conversions, such as those between bit-
8495 // precise integers types of different sizes, or between a bit-precise
8496 // integer and another type.
8497 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8498 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8499 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8500 << RHS.get()->getSourceRange();
8501 return QualType();
8502 }
8503
8504 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8505 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8506
8507 return ResTy;
8508 }
8509
8510 // If both operands are the same structure or union type, the result is that
8511 // type.
8512 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8513 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8514 if (LHSRT->getDecl() == RHSRT->getDecl())
8515 // "If both the operands have structure or union type, the result has
8516 // that type." This implies that CV qualifiers are dropped.
8518 RHSTy.getUnqualifiedType());
8519 // FIXME: Type of conditional expression must be complete in C mode.
8520 }
8521
8522 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8523 // The following || allows only one side to be void (a GCC-ism).
8524 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8525 QualType ResTy;
8526 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8527 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8528 } else if (RHSTy->isVoidType()) {
8529 ResTy = RHSTy;
8530 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8531 << RHS.get()->getSourceRange();
8532 } else {
8533 ResTy = LHSTy;
8534 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8535 << LHS.get()->getSourceRange();
8536 }
8537 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8538 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8539 return ResTy;
8540 }
8541
8542 // C23 6.5.15p7:
8543 // ... if both the second and third operands have nullptr_t type, the
8544 // result also has that type.
8545 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8546 return ResTy;
8547
8548 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8549 // the type of the other operand."
8550 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8551 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8552
8553 // All objective-c pointer type analysis is done here.
8554 QualType compositeType =
8555 ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
8556 if (LHS.isInvalid() || RHS.isInvalid())
8557 return QualType();
8558 if (!compositeType.isNull())
8559 return compositeType;
8560
8561
8562 // Handle block pointer types.
8563 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8564 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8565 QuestionLoc);
8566
8567 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8568 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8569 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8570 QuestionLoc);
8571
8572 // GCC compatibility: soften pointer/integer mismatch. Note that
8573 // null pointers have been filtered out by this point.
8574 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8575 /*IsIntFirstExpr=*/true))
8576 return RHSTy;
8577 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8578 /*IsIntFirstExpr=*/false))
8579 return LHSTy;
8580
8581 // Emit a better diagnostic if one of the expressions is a null pointer
8582 // constant and the other is not a pointer type. In this case, the user most
8583 // likely forgot to take the address of the other expression.
8584 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8585 return QualType();
8586
8587 // Finally, if the LHS and RHS types are canonically the same type, we can
8588 // use the common sugared type.
8589 if (Context.hasSameType(LHSTy, RHSTy))
8590 return Context.getCommonSugaredType(LHSTy, RHSTy);
8591
8592 // Otherwise, the operands are not compatible.
8593 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8594 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8595 << RHS.get()->getSourceRange();
8596 return QualType();
8597}
8598
8599/// SuggestParentheses - Emit a note with a fixit hint that wraps
8600/// ParenRange in parentheses.
8602 const PartialDiagnostic &Note,
8603 SourceRange ParenRange) {
8604 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8605 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8606 EndLoc.isValid()) {
8607 Self.Diag(Loc, Note)
8608 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8609 << FixItHint::CreateInsertion(EndLoc, ")");
8610 } else {
8611 // We can't display the parentheses, so just show the bare note.
8612 Self.Diag(Loc, Note) << ParenRange;
8613 }
8614}
8615
8617 return BinaryOperator::isAdditiveOp(Opc) ||
8619 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8620 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8621 // not any of the logical operators. Bitwise-xor is commonly used as a
8622 // logical-xor because there is no logical-xor operator. The logical
8623 // operators, including uses of xor, have a high false positive rate for
8624 // precedence warnings.
8625}
8626
8627/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
8628/// expression, either using a built-in or overloaded operator,
8629/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
8630/// expression.
8632 const Expr **RHSExprs) {
8633 // Don't strip parenthesis: we should not warn if E is in parenthesis.
8634 E = E->IgnoreImpCasts();
8636 E = E->IgnoreImpCasts();
8637 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
8638 E = MTE->getSubExpr();
8639 E = E->IgnoreImpCasts();
8640 }
8641
8642 // Built-in binary operator.
8643 if (const auto *OP = dyn_cast<BinaryOperator>(E);
8644 OP && IsArithmeticOp(OP->getOpcode())) {
8645 *Opcode = OP->getOpcode();
8646 *RHSExprs = OP->getRHS();
8647 return true;
8648 }
8649
8650 // Overloaded operator.
8651 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
8652 if (Call->getNumArgs() != 2)
8653 return false;
8654
8655 // Make sure this is really a binary operator that is safe to pass into
8656 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
8657 OverloadedOperatorKind OO = Call->getOperator();
8658 if (OO < OO_Plus || OO > OO_Arrow ||
8659 OO == OO_PlusPlus || OO == OO_MinusMinus)
8660 return false;
8661
8663 if (IsArithmeticOp(OpKind)) {
8664 *Opcode = OpKind;
8665 *RHSExprs = Call->getArg(1);
8666 return true;
8667 }
8668 }
8669
8670 return false;
8671}
8672
8673/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
8674/// or is a logical expression such as (x==y) which has int type, but is
8675/// commonly interpreted as boolean.
8676static bool ExprLooksBoolean(const Expr *E) {
8677 E = E->IgnoreParenImpCasts();
8678
8679 if (E->getType()->isBooleanType())
8680 return true;
8681 if (const auto *OP = dyn_cast<BinaryOperator>(E))
8682 return OP->isComparisonOp() || OP->isLogicalOp();
8683 if (const auto *OP = dyn_cast<UnaryOperator>(E))
8684 return OP->getOpcode() == UO_LNot;
8685 if (E->getType()->isPointerType())
8686 return true;
8687 // FIXME: What about overloaded operator calls returning "unspecified boolean
8688 // type"s (commonly pointer-to-members)?
8689
8690 return false;
8691}
8692
8693/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
8694/// and binary operator are mixed in a way that suggests the programmer assumed
8695/// the conditional operator has higher precedence, for example:
8696/// "int x = a + someBinaryCondition ? 1 : 2".
8698 Expr *Condition, const Expr *LHSExpr,
8699 const Expr *RHSExpr) {
8700 BinaryOperatorKind CondOpcode;
8701 const Expr *CondRHS;
8702
8703 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
8704 return;
8705 if (!ExprLooksBoolean(CondRHS))
8706 return;
8707
8708 // The condition is an arithmetic binary expression, with a right-
8709 // hand side that looks boolean, so warn.
8710
8711 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
8712 ? diag::warn_precedence_bitwise_conditional
8713 : diag::warn_precedence_conditional;
8714
8715 Self.Diag(OpLoc, DiagID)
8716 << Condition->getSourceRange()
8717 << BinaryOperator::getOpcodeStr(CondOpcode);
8718
8720 Self, OpLoc,
8721 Self.PDiag(diag::note_precedence_silence)
8722 << BinaryOperator::getOpcodeStr(CondOpcode),
8723 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
8724
8725 SuggestParentheses(Self, OpLoc,
8726 Self.PDiag(diag::note_precedence_conditional_first),
8727 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
8728}
8729
8730/// Compute the nullability of a conditional expression.
8732 QualType LHSTy, QualType RHSTy,
8733 ASTContext &Ctx) {
8734 if (!ResTy->isAnyPointerType())
8735 return ResTy;
8736
8737 auto GetNullability = [](QualType Ty) {
8738 std::optional<NullabilityKind> Kind = Ty->getNullability();
8739 if (Kind) {
8740 // For our purposes, treat _Nullable_result as _Nullable.
8743 return *Kind;
8744 }
8746 };
8747
8748 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
8749 NullabilityKind MergedKind;
8750
8751 // Compute nullability of a binary conditional expression.
8752 if (IsBin) {
8753 if (LHSKind == NullabilityKind::NonNull)
8754 MergedKind = NullabilityKind::NonNull;
8755 else
8756 MergedKind = RHSKind;
8757 // Compute nullability of a normal conditional expression.
8758 } else {
8759 if (LHSKind == NullabilityKind::Nullable ||
8760 RHSKind == NullabilityKind::Nullable)
8761 MergedKind = NullabilityKind::Nullable;
8762 else if (LHSKind == NullabilityKind::NonNull)
8763 MergedKind = RHSKind;
8764 else if (RHSKind == NullabilityKind::NonNull)
8765 MergedKind = LHSKind;
8766 else
8767 MergedKind = NullabilityKind::Unspecified;
8768 }
8769
8770 // Return if ResTy already has the correct nullability.
8771 if (GetNullability(ResTy) == MergedKind)
8772 return ResTy;
8773
8774 // Strip all nullability from ResTy.
8775 while (ResTy->getNullability())
8776 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
8777
8778 // Create a new AttributedType with the new nullability kind.
8779 return Ctx.getAttributedType(MergedKind, ResTy, ResTy);
8780}
8781
8783 SourceLocation ColonLoc,
8784 Expr *CondExpr, Expr *LHSExpr,
8785 Expr *RHSExpr) {
8787 // C cannot handle TypoExpr nodes in the condition because it
8788 // doesn't handle dependent types properly, so make sure any TypoExprs have
8789 // been dealt with before checking the operands.
8790 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
8791 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
8792 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
8793
8794 if (!CondResult.isUsable())
8795 return ExprError();
8796
8797 if (LHSExpr) {
8798 if (!LHSResult.isUsable())
8799 return ExprError();
8800 }
8801
8802 if (!RHSResult.isUsable())
8803 return ExprError();
8804
8805 CondExpr = CondResult.get();
8806 LHSExpr = LHSResult.get();
8807 RHSExpr = RHSResult.get();
8808 }
8809
8810 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
8811 // was the condition.
8812 OpaqueValueExpr *opaqueValue = nullptr;
8813 Expr *commonExpr = nullptr;
8814 if (!LHSExpr) {
8815 commonExpr = CondExpr;
8816 // Lower out placeholder types first. This is important so that we don't
8817 // try to capture a placeholder. This happens in few cases in C++; such
8818 // as Objective-C++'s dictionary subscripting syntax.
8819 if (commonExpr->hasPlaceholderType()) {
8820 ExprResult result = CheckPlaceholderExpr(commonExpr);
8821 if (!result.isUsable()) return ExprError();
8822 commonExpr = result.get();
8823 }
8824 // We usually want to apply unary conversions *before* saving, except
8825 // in the special case of a C++ l-value conditional.
8826 if (!(getLangOpts().CPlusPlus
8827 && !commonExpr->isTypeDependent()
8828 && commonExpr->getValueKind() == RHSExpr->getValueKind()
8829 && commonExpr->isGLValue()
8830 && commonExpr->isOrdinaryOrBitFieldObject()
8831 && RHSExpr->isOrdinaryOrBitFieldObject()
8832 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
8833 ExprResult commonRes = UsualUnaryConversions(commonExpr);
8834 if (commonRes.isInvalid())
8835 return ExprError();
8836 commonExpr = commonRes.get();
8837 }
8838
8839 // If the common expression is a class or array prvalue, materialize it
8840 // so that we can safely refer to it multiple times.
8841 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
8842 commonExpr->getType()->isArrayType())) {
8843 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
8844 if (MatExpr.isInvalid())
8845 return ExprError();
8846 commonExpr = MatExpr.get();
8847 }
8848
8849 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
8850 commonExpr->getType(),
8851 commonExpr->getValueKind(),
8852 commonExpr->getObjectKind(),
8853 commonExpr);
8854 LHSExpr = CondExpr = opaqueValue;
8855 }
8856
8857 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
8860 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
8861 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
8862 VK, OK, QuestionLoc);
8863 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
8864 RHS.isInvalid())
8865 return ExprError();
8866
8867 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
8868 RHS.get());
8869
8870 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
8871
8872 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
8873 Context);
8874
8875 if (!commonExpr)
8876 return new (Context)
8877 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
8878 RHS.get(), result, VK, OK);
8879
8881 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
8882 ColonLoc, result, VK, OK);
8883}
8884
8886 unsigned FromAttributes = 0, ToAttributes = 0;
8887 if (const auto *FromFn =
8888 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
8889 FromAttributes =
8890 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8891 if (const auto *ToFn =
8892 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
8893 ToAttributes =
8894 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
8895
8896 return FromAttributes != ToAttributes;
8897}
8898
8899// Check if we have a conversion between incompatible cmse function pointer
8900// types, that is, a conversion between a function pointer with the
8901// cmse_nonsecure_call attribute and one without.
8903 QualType ToType) {
8904 if (const auto *ToFn =
8905 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
8906 if (const auto *FromFn =
8907 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
8908 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
8909 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
8910
8911 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
8912 }
8913 }
8914 return false;
8915}
8916
8917// checkPointerTypesForAssignment - This is a very tricky routine (despite
8918// being closely modeled after the C99 spec:-). The odd characteristic of this
8919// routine is it effectively iqnores the qualifiers on the top level pointee.
8920// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
8921// FIXME: add a couple examples in this comment.
8925 assert(LHSType.isCanonical() && "LHS not canonicalized!");
8926 assert(RHSType.isCanonical() && "RHS not canonicalized!");
8927
8928 // get the "pointed to" type (ignoring qualifiers at the top level)
8929 const Type *lhptee, *rhptee;
8930 Qualifiers lhq, rhq;
8931 std::tie(lhptee, lhq) =
8932 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
8933 std::tie(rhptee, rhq) =
8934 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
8935
8937
8938 // C99 6.5.16.1p1: This following citation is common to constraints
8939 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
8940 // qualifiers of the type *pointed to* by the right;
8941
8942 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
8943 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
8945 // Ignore lifetime for further calculation.
8946 lhq.removeObjCLifetime();
8947 rhq.removeObjCLifetime();
8948 }
8949
8950 if (!lhq.compatiblyIncludes(rhq, S.getASTContext())) {
8951 // Treat address-space mismatches as fatal.
8952 if (!lhq.isAddressSpaceSupersetOf(rhq, S.getASTContext()))
8954
8955 // It's okay to add or remove GC or lifetime qualifiers when converting to
8956 // and from void*.
8959 S.getASTContext()) &&
8960 (lhptee->isVoidType() || rhptee->isVoidType()))
8961 ; // keep old
8962
8963 // Treat lifetime mismatches as fatal.
8964 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
8966
8967 // For GCC/MS compatibility, other qualifier mismatches are treated
8968 // as still compatible in C.
8970 }
8971
8972 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
8973 // incomplete type and the other is a pointer to a qualified or unqualified
8974 // version of void...
8975 if (lhptee->isVoidType()) {
8976 if (rhptee->isIncompleteOrObjectType())
8977 return ConvTy;
8978
8979 // As an extension, we allow cast to/from void* to function pointer.
8980 assert(rhptee->isFunctionType());
8982 }
8983
8984 if (rhptee->isVoidType()) {
8985 if (lhptee->isIncompleteOrObjectType())
8986 return ConvTy;
8987
8988 // As an extension, we allow cast to/from void* to function pointer.
8989 assert(lhptee->isFunctionType());
8991 }
8992
8993 if (!S.Diags.isIgnored(
8994 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
8995 Loc) &&
8996 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
8997 !S.IsFunctionConversion(RHSType, LHSType, RHSType))
8999
9000 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9001 // unqualified versions of compatible types, ...
9002 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9003 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9004 // Check if the pointee types are compatible ignoring the sign.
9005 // We explicitly check for char so that we catch "char" vs
9006 // "unsigned char" on systems where "char" is unsigned.
9007 if (lhptee->isCharType())
9008 ltrans = S.Context.UnsignedCharTy;
9009 else if (lhptee->hasSignedIntegerRepresentation())
9010 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9011
9012 if (rhptee->isCharType())
9013 rtrans = S.Context.UnsignedCharTy;
9014 else if (rhptee->hasSignedIntegerRepresentation())
9015 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9016
9017 if (ltrans == rtrans) {
9018 // Types are compatible ignoring the sign. Qualifier incompatibility
9019 // takes priority over sign incompatibility because the sign
9020 // warning can be disabled.
9021 if (ConvTy != Sema::Compatible)
9022 return ConvTy;
9023
9025 }
9026
9027 // If we are a multi-level pointer, it's possible that our issue is simply
9028 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9029 // the eventual target type is the same and the pointers have the same
9030 // level of indirection, this must be the issue.
9031 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9032 do {
9033 std::tie(lhptee, lhq) =
9034 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9035 std::tie(rhptee, rhq) =
9036 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9037
9038 // Inconsistent address spaces at this point is invalid, even if the
9039 // address spaces would be compatible.
9040 // FIXME: This doesn't catch address space mismatches for pointers of
9041 // different nesting levels, like:
9042 // __local int *** a;
9043 // int ** b = a;
9044 // It's not clear how to actually determine when such pointers are
9045 // invalidly incompatible.
9046 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9048
9049 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9050
9051 if (lhptee == rhptee)
9053 }
9054
9055 // General pointer incompatibility takes priority over qualifiers.
9056 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9059 }
9060 if (!S.getLangOpts().CPlusPlus &&
9061 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9063 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9065 if (S.IsInvalidSMECallConversion(rtrans, ltrans))
9067 return ConvTy;
9068}
9069
9070/// checkBlockPointerTypesForAssignment - This routine determines whether two
9071/// block pointer types are compatible or whether a block and normal pointer
9072/// are compatible. It is more restrict than comparing two function pointer
9073// types.
9076 QualType RHSType) {
9077 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9078 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9079
9080 QualType lhptee, rhptee;
9081
9082 // get the "pointed to" type (ignoring qualifiers at the top level)
9083 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9084 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9085
9086 // In C++, the types have to match exactly.
9087 if (S.getLangOpts().CPlusPlus)
9089
9091
9092 // For blocks we enforce that qualifiers are identical.
9093 Qualifiers LQuals = lhptee.getLocalQualifiers();
9094 Qualifiers RQuals = rhptee.getLocalQualifiers();
9095 if (S.getLangOpts().OpenCL) {
9096 LQuals.removeAddressSpace();
9097 RQuals.removeAddressSpace();
9098 }
9099 if (LQuals != RQuals)
9101
9102 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9103 // assignment.
9104 // The current behavior is similar to C++ lambdas. A block might be
9105 // assigned to a variable iff its return type and parameters are compatible
9106 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9107 // an assignment. Presumably it should behave in way that a function pointer
9108 // assignment does in C, so for each parameter and return type:
9109 // * CVR and address space of LHS should be a superset of CVR and address
9110 // space of RHS.
9111 // * unqualified types should be compatible.
9112 if (S.getLangOpts().OpenCL) {
9114 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9115 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9117 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9119
9120 return ConvTy;
9121}
9122
9123/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9124/// for assignment compatibility.
9127 QualType RHSType) {
9128 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9129 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9130
9131 if (LHSType->isObjCBuiltinType()) {
9132 // Class is not compatible with ObjC object pointers.
9133 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9134 !RHSType->isObjCQualifiedClassType())
9136 return Sema::Compatible;
9137 }
9138 if (RHSType->isObjCBuiltinType()) {
9139 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9140 !LHSType->isObjCQualifiedClassType())
9142 return Sema::Compatible;
9143 }
9144 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9145 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9146
9147 if (!lhptee.isAtLeastAsQualifiedAs(rhptee, S.getASTContext()) &&
9148 // make an exception for id<P>
9149 !LHSType->isObjCQualifiedIdType())
9151
9152 if (S.Context.typesAreCompatible(LHSType, RHSType))
9153 return Sema::Compatible;
9154 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9157}
9158
9161 QualType LHSType, QualType RHSType) {
9162 // Fake up an opaque expression. We don't actually care about what
9163 // cast operations are required, so if CheckAssignmentConstraints
9164 // adds casts to this they'll be wasted, but fortunately that doesn't
9165 // usually happen on valid code.
9166 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9167 ExprResult RHSPtr = &RHSExpr;
9168 CastKind K;
9169
9170 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9171}
9172
9173/// This helper function returns true if QT is a vector type that has element
9174/// type ElementType.
9175static bool isVector(QualType QT, QualType ElementType) {
9176 if (const VectorType *VT = QT->getAs<VectorType>())
9177 return VT->getElementType().getCanonicalType() == ElementType;
9178 return false;
9179}
9180
9181/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9182/// has code to accommodate several GCC extensions when type checking
9183/// pointers. Here are some objectionable examples that GCC considers warnings:
9184///
9185/// int a, *pint;
9186/// short *pshort;
9187/// struct foo *pfoo;
9188///
9189/// pint = pshort; // warning: assignment from incompatible pointer type
9190/// a = pint; // warning: assignment makes integer from pointer without a cast
9191/// pint = a; // warning: assignment makes pointer from integer without a cast
9192/// pint = pfoo; // warning: assignment from incompatible pointer type
9193///
9194/// As a result, the code for dealing with pointers is more complex than the
9195/// C99 spec dictates.
9196///
9197/// Sets 'Kind' for any result kind except Incompatible.
9200 CastKind &Kind, bool ConvertRHS) {
9201 QualType RHSType = RHS.get()->getType();
9202 QualType OrigLHSType = LHSType;
9203
9204 // Get canonical types. We're not formatting these types, just comparing
9205 // them.
9206 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9207 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9208
9209 // Common case: no conversion required.
9210 if (LHSType == RHSType) {
9211 Kind = CK_NoOp;
9212 return Compatible;
9213 }
9214
9215 // If the LHS has an __auto_type, there are no additional type constraints
9216 // to be worried about.
9217 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9218 if (AT->isGNUAutoType()) {
9219 Kind = CK_NoOp;
9220 return Compatible;
9221 }
9222 }
9223
9224 // If we have an atomic type, try a non-atomic assignment, then just add an
9225 // atomic qualification step.
9226 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9228 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9229 if (result != Compatible)
9230 return result;
9231 if (Kind != CK_NoOp && ConvertRHS)
9232 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9233 Kind = CK_NonAtomicToAtomic;
9234 return Compatible;
9235 }
9236
9237 // If the left-hand side is a reference type, then we are in a
9238 // (rare!) case where we've allowed the use of references in C,
9239 // e.g., as a parameter type in a built-in function. In this case,
9240 // just make sure that the type referenced is compatible with the
9241 // right-hand side type. The caller is responsible for adjusting
9242 // LHSType so that the resulting expression does not have reference
9243 // type.
9244 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9245 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9246 Kind = CK_LValueBitCast;
9247 return Compatible;
9248 }
9249 return Incompatible;
9250 }
9251
9252 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9253 // to the same ExtVector type.
9254 if (LHSType->isExtVectorType()) {
9255 if (RHSType->isExtVectorType())
9256 return Incompatible;
9257 if (RHSType->isArithmeticType()) {
9258 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9259 if (ConvertRHS)
9260 RHS = prepareVectorSplat(LHSType, RHS.get());
9261 Kind = CK_VectorSplat;
9262 return Compatible;
9263 }
9264 }
9265
9266 // Conversions to or from vector type.
9267 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9268 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9269 // Allow assignments of an AltiVec vector type to an equivalent GCC
9270 // vector type and vice versa
9271 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9272 Kind = CK_BitCast;
9273 return Compatible;
9274 }
9275
9276 // If we are allowing lax vector conversions, and LHS and RHS are both
9277 // vectors, the total size only needs to be the same. This is a bitcast;
9278 // no bits are changed but the result type is different.
9279 if (isLaxVectorConversion(RHSType, LHSType)) {
9280 // The default for lax vector conversions with Altivec vectors will
9281 // change, so if we are converting between vector types where
9282 // at least one is an Altivec vector, emit a warning.
9283 if (Context.getTargetInfo().getTriple().isPPC() &&
9284 anyAltivecTypes(RHSType, LHSType) &&
9285 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9286 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9287 << RHSType << LHSType;
9288 Kind = CK_BitCast;
9289 return IncompatibleVectors;
9290 }
9291 }
9292
9293 // When the RHS comes from another lax conversion (e.g. binops between
9294 // scalars and vectors) the result is canonicalized as a vector. When the
9295 // LHS is also a vector, the lax is allowed by the condition above. Handle
9296 // the case where LHS is a scalar.
9297 if (LHSType->isScalarType()) {
9298 const VectorType *VecType = RHSType->getAs<VectorType>();
9299 if (VecType && VecType->getNumElements() == 1 &&
9300 isLaxVectorConversion(RHSType, LHSType)) {
9301 if (Context.getTargetInfo().getTriple().isPPC() &&
9303 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9305 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9306 << RHSType << LHSType;
9307 ExprResult *VecExpr = &RHS;
9308 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9309 Kind = CK_BitCast;
9310 return Compatible;
9311 }
9312 }
9313
9314 // Allow assignments between fixed-length and sizeless SVE vectors.
9315 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9316 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9317 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9318 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9319 Kind = CK_BitCast;
9320 return Compatible;
9321 }
9322
9323 // Allow assignments between fixed-length and sizeless RVV vectors.
9324 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9325 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9326 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9327 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9328 Kind = CK_BitCast;
9329 return Compatible;
9330 }
9331 }
9332
9333 return Incompatible;
9334 }
9335
9336 // Diagnose attempts to convert between __ibm128, __float128 and long double
9337 // where such conversions currently can't be handled.
9338 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9339 return Incompatible;
9340
9341 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9342 // discards the imaginary part.
9343 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9344 !LHSType->getAs<ComplexType>())
9345 return Incompatible;
9346
9347 // Arithmetic conversions.
9348 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9349 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9350 if (ConvertRHS)
9351 Kind = PrepareScalarCast(RHS, LHSType);
9352 return Compatible;
9353 }
9354
9355 // Conversions to normal pointers.
9356 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9357 // U* -> T*
9358 if (isa<PointerType>(RHSType)) {
9359 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9360 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9361 if (AddrSpaceL != AddrSpaceR)
9362 Kind = CK_AddressSpaceConversion;
9363 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9364 Kind = CK_NoOp;
9365 else
9366 Kind = CK_BitCast;
9367 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9368 RHS.get()->getBeginLoc());
9369 }
9370
9371 // int -> T*
9372 if (RHSType->isIntegerType()) {
9373 Kind = CK_IntegralToPointer; // FIXME: null?
9374 return IntToPointer;
9375 }
9376
9377 // C pointers are not compatible with ObjC object pointers,
9378 // with two exceptions:
9379 if (isa<ObjCObjectPointerType>(RHSType)) {
9380 // - conversions to void*
9381 if (LHSPointer->getPointeeType()->isVoidType()) {
9382 Kind = CK_BitCast;
9383 return Compatible;
9384 }
9385
9386 // - conversions from 'Class' to the redefinition type
9387 if (RHSType->isObjCClassType() &&
9388 Context.hasSameType(LHSType,
9390 Kind = CK_BitCast;
9391 return Compatible;
9392 }
9393
9394 Kind = CK_BitCast;
9395 return IncompatiblePointer;
9396 }
9397
9398 // U^ -> void*
9399 if (RHSType->getAs<BlockPointerType>()) {
9400 if (LHSPointer->getPointeeType()->isVoidType()) {
9401 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9402 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9403 ->getPointeeType()
9404 .getAddressSpace();
9405 Kind =
9406 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9407 return Compatible;
9408 }
9409 }
9410
9411 return Incompatible;
9412 }
9413
9414 // Conversions to block pointers.
9415 if (isa<BlockPointerType>(LHSType)) {
9416 // U^ -> T^
9417 if (RHSType->isBlockPointerType()) {
9418 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9419 ->getPointeeType()
9420 .getAddressSpace();
9421 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9422 ->getPointeeType()
9423 .getAddressSpace();
9424 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9425 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9426 }
9427
9428 // int or null -> T^
9429 if (RHSType->isIntegerType()) {
9430 Kind = CK_IntegralToPointer; // FIXME: null
9431 return IntToBlockPointer;
9432 }
9433
9434 // id -> T^
9435 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9436 Kind = CK_AnyPointerToBlockPointerCast;
9437 return Compatible;
9438 }
9439
9440 // void* -> T^
9441 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9442 if (RHSPT->getPointeeType()->isVoidType()) {
9443 Kind = CK_AnyPointerToBlockPointerCast;
9444 return Compatible;
9445 }
9446
9447 return Incompatible;
9448 }
9449
9450 // Conversions to Objective-C pointers.
9451 if (isa<ObjCObjectPointerType>(LHSType)) {
9452 // A* -> B*
9453 if (RHSType->isObjCObjectPointerType()) {
9454 Kind = CK_BitCast;
9456 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9457 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9458 result == Compatible &&
9459 !ObjC().CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9460 result = IncompatibleObjCWeakRef;
9461 return result;
9462 }
9463
9464 // int or null -> A*
9465 if (RHSType->isIntegerType()) {
9466 Kind = CK_IntegralToPointer; // FIXME: null
9467 return IntToPointer;
9468 }
9469
9470 // In general, C pointers are not compatible with ObjC object pointers,
9471 // with two exceptions:
9472 if (isa<PointerType>(RHSType)) {
9473 Kind = CK_CPointerToObjCPointerCast;
9474
9475 // - conversions from 'void*'
9476 if (RHSType->isVoidPointerType()) {
9477 return Compatible;
9478 }
9479
9480 // - conversions to 'Class' from its redefinition type
9481 if (LHSType->isObjCClassType() &&
9482 Context.hasSameType(RHSType,
9484 return Compatible;
9485 }
9486
9487 return IncompatiblePointer;
9488 }
9489
9490 // Only under strict condition T^ is compatible with an Objective-C pointer.
9491 if (RHSType->isBlockPointerType() &&
9493 if (ConvertRHS)
9495 Kind = CK_BlockPointerToObjCPointerCast;
9496 return Compatible;
9497 }
9498
9499 return Incompatible;
9500 }
9501
9502 // Conversion to nullptr_t (C23 only)
9503 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9506 // null -> nullptr_t
9507 Kind = CK_NullToPointer;
9508 return Compatible;
9509 }
9510
9511 // Conversions from pointers that are not covered by the above.
9512 if (isa<PointerType>(RHSType)) {
9513 // T* -> _Bool
9514 if (LHSType == Context.BoolTy) {
9515 Kind = CK_PointerToBoolean;
9516 return Compatible;
9517 }
9518
9519 // T* -> int
9520 if (LHSType->isIntegerType()) {
9521 Kind = CK_PointerToIntegral;
9522 return PointerToInt;
9523 }
9524
9525 return Incompatible;
9526 }
9527
9528 // Conversions from Objective-C pointers that are not covered by the above.
9529 if (isa<ObjCObjectPointerType>(RHSType)) {
9530 // T* -> _Bool
9531 if (LHSType == Context.BoolTy) {
9532 Kind = CK_PointerToBoolean;
9533 return Compatible;
9534 }
9535
9536 // T* -> int
9537 if (LHSType->isIntegerType()) {
9538 Kind = CK_PointerToIntegral;
9539 return PointerToInt;
9540 }
9541
9542 return Incompatible;
9543 }
9544
9545 // struct A -> struct B
9546 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9547 if (Context.typesAreCompatible(LHSType, RHSType)) {
9548 Kind = CK_NoOp;
9549 return Compatible;
9550 }
9551 }
9552
9553 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9554 Kind = CK_IntToOCLSampler;
9555 return Compatible;
9556 }
9557
9558 return Incompatible;
9559}
9560
9561/// Constructs a transparent union from an expression that is
9562/// used to initialize the transparent union.
9564 ExprResult &EResult, QualType UnionType,
9565 FieldDecl *Field) {
9566 // Build an initializer list that designates the appropriate member
9567 // of the transparent union.
9568 Expr *E = EResult.get();
9570 E, SourceLocation());
9571 Initializer->setType(UnionType);
9572 Initializer->setInitializedFieldInUnion(Field);
9573
9574 // Build a compound literal constructing a value of the transparent
9575 // union type from this initializer list.
9576 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9577 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9578 VK_PRValue, Initializer, false);
9579}
9580
9583 ExprResult &RHS) {
9584 QualType RHSType = RHS.get()->getType();
9585
9586 // If the ArgType is a Union type, we want to handle a potential
9587 // transparent_union GCC extension.
9588 const RecordType *UT = ArgType->getAsUnionType();
9589 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9590 return Incompatible;
9591
9592 // The field to initialize within the transparent union.
9593 RecordDecl *UD = UT->getDecl();
9594 FieldDecl *InitField = nullptr;
9595 // It's compatible if the expression matches any of the fields.
9596 for (auto *it : UD->fields()) {
9597 if (it->getType()->isPointerType()) {
9598 // If the transparent union contains a pointer type, we allow:
9599 // 1) void pointer
9600 // 2) null pointer constant
9601 if (RHSType->isPointerType())
9602 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9603 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9604 InitField = it;
9605 break;
9606 }
9607
9610 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9611 CK_NullToPointer);
9612 InitField = it;
9613 break;
9614 }
9615 }
9616
9617 CastKind Kind;
9618 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9619 == Compatible) {
9620 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9621 InitField = it;
9622 break;
9623 }
9624 }
9625
9626 if (!InitField)
9627 return Incompatible;
9628
9629 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
9630 return Compatible;
9631}
9632
9635 bool Diagnose,
9636 bool DiagnoseCFAudited,
9637 bool ConvertRHS) {
9638 // We need to be able to tell the caller whether we diagnosed a problem, if
9639 // they ask us to issue diagnostics.
9640 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
9641
9642 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
9643 // we can't avoid *all* modifications at the moment, so we need some somewhere
9644 // to put the updated value.
9645 ExprResult LocalRHS = CallerRHS;
9646 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
9647
9648 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
9649 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
9650 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
9651 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
9652 Diag(RHS.get()->getExprLoc(),
9653 diag::warn_noderef_to_dereferenceable_pointer)
9654 << RHS.get()->getSourceRange();
9655 }
9656 }
9657 }
9658
9659 if (getLangOpts().CPlusPlus) {
9660 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
9661 // C++ 5.17p3: If the left operand is not of class type, the
9662 // expression is implicitly converted (C++ 4) to the
9663 // cv-unqualified type of the left operand.
9664 QualType RHSType = RHS.get()->getType();
9665 if (Diagnose) {
9666 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9668 } else {
9671 /*SuppressUserConversions=*/false,
9672 AllowedExplicit::None,
9673 /*InOverloadResolution=*/false,
9674 /*CStyle=*/false,
9675 /*AllowObjCWritebackConversion=*/false);
9676 if (ICS.isFailure())
9677 return Incompatible;
9678 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
9680 }
9681 if (RHS.isInvalid())
9682 return Incompatible;
9684 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9685 !ObjC().CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
9686 result = IncompatibleObjCWeakRef;
9687 return result;
9688 }
9689
9690 // FIXME: Currently, we fall through and treat C++ classes like C
9691 // structures.
9692 // FIXME: We also fall through for atomics; not sure what should
9693 // happen there, though.
9694 } else if (RHS.get()->getType() == Context.OverloadTy) {
9695 // As a set of extensions to C, we support overloading on functions. These
9696 // functions need to be resolved here.
9697 DeclAccessPair DAP;
9699 RHS.get(), LHSType, /*Complain=*/false, DAP))
9700 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
9701 else
9702 return Incompatible;
9703 }
9704
9705 // This check seems unnatural, however it is necessary to ensure the proper
9706 // conversion of functions/arrays. If the conversion were done for all
9707 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
9708 // expressions that suppress this implicit conversion (&, sizeof). This needs
9709 // to happen before we check for null pointer conversions because C does not
9710 // undergo the same implicit conversions as C++ does above (by the calls to
9711 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
9712 // lvalue to rvalue cast before checking for null pointer constraints. This
9713 // addresses code like: nullptr_t val; int *ptr; ptr = val;
9714 //
9715 // Suppress this for references: C++ 8.5.3p5.
9716 if (!LHSType->isReferenceType()) {
9717 // FIXME: We potentially allocate here even if ConvertRHS is false.
9719 if (RHS.isInvalid())
9720 return Incompatible;
9721 }
9722
9723 // The constraints are expressed in terms of the atomic, qualified, or
9724 // unqualified type of the LHS.
9725 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
9726
9727 // C99 6.5.16.1p1: the left operand is a pointer and the right is
9728 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
9729 if ((LHSTypeAfterConversion->isPointerType() ||
9730 LHSTypeAfterConversion->isObjCObjectPointerType() ||
9731 LHSTypeAfterConversion->isBlockPointerType()) &&
9732 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
9735 if (Diagnose || ConvertRHS) {
9736 CastKind Kind;
9738 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
9739 /*IgnoreBaseAccess=*/false, Diagnose);
9740 if (ConvertRHS)
9741 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
9742 }
9743 return Compatible;
9744 }
9745 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
9746 // unqualified bool, and the right operand is a pointer or its type is
9747 // nullptr_t.
9748 if (getLangOpts().C23 && LHSType->isBooleanType() &&
9749 RHS.get()->getType()->isNullPtrType()) {
9750 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
9751 // only handles nullptr -> _Bool due to needing an extra conversion
9752 // step.
9753 // We model this by converting from nullptr -> void * and then let the
9754 // conversion from void * -> _Bool happen naturally.
9755 if (Diagnose || ConvertRHS) {
9756 CastKind Kind;
9759 /*IgnoreBaseAccess=*/false, Diagnose);
9760 if (ConvertRHS)
9761 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
9762 &Path);
9763 }
9764 }
9765
9766 // OpenCL queue_t type assignment.
9767 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
9769 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9770 return Compatible;
9771 }
9772
9773 CastKind Kind;
9775 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
9776
9777 // C99 6.5.16.1p2: The value of the right operand is converted to the
9778 // type of the assignment expression.
9779 // CheckAssignmentConstraints allows the left-hand side to be a reference,
9780 // so that we can use references in built-in functions even in C.
9781 // The getNonReferenceType() call makes sure that the resulting expression
9782 // does not have reference type.
9783 if (result != Incompatible && RHS.get()->getType() != LHSType) {
9785 Expr *E = RHS.get();
9786
9787 // Check for various Objective-C errors. If we are not reporting
9788 // diagnostics and just checking for errors, e.g., during overload
9789 // resolution, return Incompatible to indicate the failure.
9790 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9791 ObjC().CheckObjCConversion(SourceRange(), Ty, E,
9793 DiagnoseCFAudited) != SemaObjC::ACR_okay) {
9794 if (!Diagnose)
9795 return Incompatible;
9796 }
9797 if (getLangOpts().ObjC &&
9798 (ObjC().CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
9799 E->getType(), E, Diagnose) ||
9800 ObjC().CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
9801 if (!Diagnose)
9802 return Incompatible;
9803 // Replace the expression with a corrected version and continue so we
9804 // can find further errors.
9805 RHS = E;
9806 return Compatible;
9807 }
9808
9809 if (ConvertRHS)
9810 RHS = ImpCastExprToType(E, Ty, Kind);
9811 }
9812
9813 return result;
9814}
9815
9816namespace {
9817/// The original operand to an operator, prior to the application of the usual
9818/// arithmetic conversions and converting the arguments of a builtin operator
9819/// candidate.
9820struct OriginalOperand {
9821 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
9822 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
9823 Op = MTE->getSubExpr();
9824 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
9825 Op = BTE->getSubExpr();
9826 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
9827 Orig = ICE->getSubExprAsWritten();
9828 Conversion = ICE->getConversionFunction();
9829 }
9830 }
9831
9832 QualType getType() const { return Orig->getType(); }
9833
9834 Expr *Orig;
9835 NamedDecl *Conversion;
9836};
9837}
9838
9840 ExprResult &RHS) {
9841 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
9842
9843 Diag(Loc, diag::err_typecheck_invalid_operands)
9844 << OrigLHS.getType() << OrigRHS.getType()
9845 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9846
9847 // If a user-defined conversion was applied to either of the operands prior
9848 // to applying the built-in operator rules, tell the user about it.
9849 if (OrigLHS.Conversion) {
9850 Diag(OrigLHS.Conversion->getLocation(),
9851 diag::note_typecheck_invalid_operands_converted)
9852 << 0 << LHS.get()->getType();
9853 }
9854 if (OrigRHS.Conversion) {
9855 Diag(OrigRHS.Conversion->getLocation(),
9856 diag::note_typecheck_invalid_operands_converted)
9857 << 1 << RHS.get()->getType();
9858 }
9859
9860 return QualType();
9861}
9862
9864 ExprResult &RHS) {
9865 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
9866 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
9867
9868 bool LHSNatVec = LHSType->isVectorType();
9869 bool RHSNatVec = RHSType->isVectorType();
9870
9871 if (!(LHSNatVec && RHSNatVec)) {
9872 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
9873 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
9874 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9875 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
9876 << Vector->getSourceRange();
9877 return QualType();
9878 }
9879
9880 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
9881 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
9882 << RHS.get()->getSourceRange();
9883
9884 return QualType();
9885}
9886
9887/// Try to convert a value of non-vector type to a vector type by converting
9888/// the type to the element type of the vector and then performing a splat.
9889/// If the language is OpenCL, we only use conversions that promote scalar
9890/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
9891/// for float->int.
9892///
9893/// OpenCL V2.0 6.2.6.p2:
9894/// An error shall occur if any scalar operand type has greater rank
9895/// than the type of the vector element.
9896///
9897/// \param scalar - if non-null, actually perform the conversions
9898/// \return true if the operation fails (but without diagnosing the failure)
9900 QualType scalarTy,
9901 QualType vectorEltTy,
9902 QualType vectorTy,
9903 unsigned &DiagID) {
9904 // The conversion to apply to the scalar before splatting it,
9905 // if necessary.
9906 CastKind scalarCast = CK_NoOp;
9907
9908 if (vectorEltTy->isBooleanType() && scalarTy->isIntegralType(S.Context)) {
9909 scalarCast = CK_IntegralToBoolean;
9910 } else if (vectorEltTy->isIntegralType(S.Context)) {
9911 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
9912 (scalarTy->isIntegerType() &&
9913 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
9914 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9915 return true;
9916 }
9917 if (!scalarTy->isIntegralType(S.Context))
9918 return true;
9919 scalarCast = CK_IntegralCast;
9920 } else if (vectorEltTy->isRealFloatingType()) {
9921 if (scalarTy->isRealFloatingType()) {
9922 if (S.getLangOpts().OpenCL &&
9923 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
9924 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
9925 return true;
9926 }
9927 scalarCast = CK_FloatingCast;
9928 }
9929 else if (scalarTy->isIntegralType(S.Context))
9930 scalarCast = CK_IntegralToFloating;
9931 else
9932 return true;
9933 } else {
9934 return true;
9935 }
9936
9937 // Adjust scalar if desired.
9938 if (scalar) {
9939 if (scalarCast != CK_NoOp)
9940 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
9941 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
9942 }
9943 return false;
9944}
9945
9946/// Convert vector E to a vector with the same number of elements but different
9947/// element type.
9948static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
9949 const auto *VecTy = E->getType()->getAs<VectorType>();
9950 assert(VecTy && "Expression E must be a vector");
9951 QualType NewVecTy =
9952 VecTy->isExtVectorType()
9953 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
9954 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
9955 VecTy->getVectorKind());
9956
9957 // Look through the implicit cast. Return the subexpression if its type is
9958 // NewVecTy.
9959 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9960 if (ICE->getSubExpr()->getType() == NewVecTy)
9961 return ICE->getSubExpr();
9962
9963 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
9964 return S.ImpCastExprToType(E, NewVecTy, Cast);
9965}
9966
9967/// Test if a (constant) integer Int can be casted to another integer type
9968/// IntTy without losing precision.
9970 QualType OtherIntTy) {
9971 if (Int->get()->containsErrors())
9972 return false;
9973
9974 QualType IntTy = Int->get()->getType().getUnqualifiedType();
9975
9976 // Reject cases where the value of the Int is unknown as that would
9977 // possibly cause truncation, but accept cases where the scalar can be
9978 // demoted without loss of precision.
9979 Expr::EvalResult EVResult;
9980 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
9981 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
9982 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
9983 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
9984
9985 if (CstInt) {
9986 // If the scalar is constant and is of a higher order and has more active
9987 // bits that the vector element type, reject it.
9988 llvm::APSInt Result = EVResult.Val.getInt();
9989 unsigned NumBits = IntSigned
9990 ? (Result.isNegative() ? Result.getSignificantBits()
9991 : Result.getActiveBits())
9992 : Result.getActiveBits();
9993 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
9994 return true;
9995
9996 // If the signedness of the scalar type and the vector element type
9997 // differs and the number of bits is greater than that of the vector
9998 // element reject it.
9999 return (IntSigned != OtherIntSigned &&
10000 NumBits > S.Context.getIntWidth(OtherIntTy));
10001 }
10002
10003 // Reject cases where the value of the scalar is not constant and it's
10004 // order is greater than that of the vector element type.
10005 return (Order < 0);
10006}
10007
10008/// Test if a (constant) integer Int can be casted to floating point type
10009/// FloatTy without losing precision.
10011 QualType FloatTy) {
10012 if (Int->get()->containsErrors())
10013 return false;
10014
10015 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10016
10017 // Determine if the integer constant can be expressed as a floating point
10018 // number of the appropriate type.
10019 Expr::EvalResult EVResult;
10020 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10021
10022 uint64_t Bits = 0;
10023 if (CstInt) {
10024 // Reject constants that would be truncated if they were converted to
10025 // the floating point type. Test by simple to/from conversion.
10026 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10027 // could be avoided if there was a convertFromAPInt method
10028 // which could signal back if implicit truncation occurred.
10029 llvm::APSInt Result = EVResult.Val.getInt();
10030 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10031 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10032 llvm::APFloat::rmTowardZero);
10033 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10035 bool Ignored = false;
10036 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10037 &Ignored);
10038 if (Result != ConvertBack)
10039 return true;
10040 } else {
10041 // Reject types that cannot be fully encoded into the mantissa of
10042 // the float.
10043 Bits = S.Context.getTypeSize(IntTy);
10044 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10045 S.Context.getFloatTypeSemantics(FloatTy));
10046 if (Bits > FloatPrec)
10047 return true;
10048 }
10049
10050 return false;
10051}
10052
10053/// Attempt to convert and splat Scalar into a vector whose types matches
10054/// Vector following GCC conversion rules. The rule is that implicit
10055/// conversion can occur when Scalar can be casted to match Vector's element
10056/// type without causing truncation of Scalar.
10058 ExprResult *Vector) {
10059 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10060 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10061 QualType VectorEltTy;
10062
10063 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10064 assert(!isa<ExtVectorType>(VT) &&
10065 "ExtVectorTypes should not be handled here!");
10066 VectorEltTy = VT->getElementType();
10067 } else if (VectorTy->isSveVLSBuiltinType()) {
10068 VectorEltTy =
10069 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10070 } else {
10071 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10072 }
10073
10074 // Reject cases where the vector element type or the scalar element type are
10075 // not integral or floating point types.
10076 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10077 return true;
10078
10079 // The conversion to apply to the scalar before splatting it,
10080 // if necessary.
10081 CastKind ScalarCast = CK_NoOp;
10082
10083 // Accept cases where the vector elements are integers and the scalar is
10084 // an integer.
10085 // FIXME: Notionally if the scalar was a floating point value with a precise
10086 // integral representation, we could cast it to an appropriate integer
10087 // type and then perform the rest of the checks here. GCC will perform
10088 // this conversion in some cases as determined by the input language.
10089 // We should accept it on a language independent basis.
10090 if (VectorEltTy->isIntegralType(S.Context) &&
10091 ScalarTy->isIntegralType(S.Context) &&
10092 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10093
10094 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10095 return true;
10096
10097 ScalarCast = CK_IntegralCast;
10098 } else if (VectorEltTy->isIntegralType(S.Context) &&
10099 ScalarTy->isRealFloatingType()) {
10100 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10101 ScalarCast = CK_FloatingToIntegral;
10102 else
10103 return true;
10104 } else if (VectorEltTy->isRealFloatingType()) {
10105 if (ScalarTy->isRealFloatingType()) {
10106
10107 // Reject cases where the scalar type is not a constant and has a higher
10108 // Order than the vector element type.
10109 llvm::APFloat Result(0.0);
10110
10111 // Determine whether this is a constant scalar. In the event that the
10112 // value is dependent (and thus cannot be evaluated by the constant
10113 // evaluator), skip the evaluation. This will then diagnose once the
10114 // expression is instantiated.
10115 bool CstScalar = Scalar->get()->isValueDependent() ||
10116 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10117 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10118 if (!CstScalar && Order < 0)
10119 return true;
10120
10121 // If the scalar cannot be safely casted to the vector element type,
10122 // reject it.
10123 if (CstScalar) {
10124 bool Truncated = false;
10125 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10126 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10127 if (Truncated)
10128 return true;
10129 }
10130
10131 ScalarCast = CK_FloatingCast;
10132 } else if (ScalarTy->isIntegralType(S.Context)) {
10133 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10134 return true;
10135
10136 ScalarCast = CK_IntegralToFloating;
10137 } else
10138 return true;
10139 } else if (ScalarTy->isEnumeralType())
10140 return true;
10141
10142 // Adjust scalar if desired.
10143 if (ScalarCast != CK_NoOp)
10144 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10145 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10146 return false;
10147}
10148
10150 SourceLocation Loc, bool IsCompAssign,
10151 bool AllowBothBool,
10152 bool AllowBoolConversions,
10153 bool AllowBoolOperation,
10154 bool ReportInvalid) {
10155 if (!IsCompAssign) {
10157 if (LHS.isInvalid())
10158 return QualType();
10159 }
10161 if (RHS.isInvalid())
10162 return QualType();
10163
10164 // For conversion purposes, we ignore any qualifiers.
10165 // For example, "const float" and "float" are equivalent.
10166 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10167 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10168
10169 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10170 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10171 assert(LHSVecType || RHSVecType);
10172
10173 if (getLangOpts().HLSL)
10174 return HLSL().handleVectorBinOpConversion(LHS, RHS, LHSType, RHSType,
10175 IsCompAssign);
10176
10177 // Any operation with MFloat8 type is only possible with C intrinsics
10178 if ((LHSVecType && LHSVecType->getElementType()->isMFloat8Type()) ||
10179 (RHSVecType && RHSVecType->getElementType()->isMFloat8Type()))
10180 return InvalidOperands(Loc, LHS, RHS);
10181
10182 // AltiVec-style "vector bool op vector bool" combinations are allowed
10183 // for some operators but not others.
10184 if (!AllowBothBool && LHSVecType &&
10185 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10186 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10187 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10188
10189 // This operation may not be performed on boolean vectors.
10190 if (!AllowBoolOperation &&
10191 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10192 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10193
10194 // If the vector types are identical, return.
10195 if (Context.hasSameType(LHSType, RHSType))
10196 return Context.getCommonSugaredType(LHSType, RHSType);
10197
10198 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10199 if (LHSVecType && RHSVecType &&
10200 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10201 if (isa<ExtVectorType>(LHSVecType)) {
10202 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10203 return LHSType;
10204 }
10205
10206 if (!IsCompAssign)
10207 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10208 return RHSType;
10209 }
10210
10211 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10212 // can be mixed, with the result being the non-bool type. The non-bool
10213 // operand must have integer element type.
10214 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10215 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10216 (Context.getTypeSize(LHSVecType->getElementType()) ==
10217 Context.getTypeSize(RHSVecType->getElementType()))) {
10218 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10219 LHSVecType->getElementType()->isIntegerType() &&
10220 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10221 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10222 return LHSType;
10223 }
10224 if (!IsCompAssign &&
10225 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10226 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10227 RHSVecType->getElementType()->isIntegerType()) {
10228 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10229 return RHSType;
10230 }
10231 }
10232
10233 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10234 // invalid since the ambiguity can affect the ABI.
10235 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10236 unsigned &SVEorRVV) {
10237 const VectorType *VecType = SecondType->getAs<VectorType>();
10238 SVEorRVV = 0;
10239 if (FirstType->isSizelessBuiltinType() && VecType) {
10242 return true;
10248 SVEorRVV = 1;
10249 return true;
10250 }
10251 }
10252
10253 return false;
10254 };
10255
10256 unsigned SVEorRVV;
10257 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10258 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10259 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10260 << SVEorRVV << LHSType << RHSType;
10261 return QualType();
10262 }
10263
10264 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10265 // invalid since the ambiguity can affect the ABI.
10266 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10267 unsigned &SVEorRVV) {
10268 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10269 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10270
10271 SVEorRVV = 0;
10272 if (FirstVecType && SecondVecType) {
10273 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10274 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10275 SecondVecType->getVectorKind() ==
10277 return true;
10278 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10279 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask ||
10280 SecondVecType->getVectorKind() ==
10282 SecondVecType->getVectorKind() ==
10284 SecondVecType->getVectorKind() ==
10286 SVEorRVV = 1;
10287 return true;
10288 }
10289 }
10290 return false;
10291 }
10292
10293 if (SecondVecType &&
10294 SecondVecType->getVectorKind() == VectorKind::Generic) {
10295 if (FirstType->isSVESizelessBuiltinType())
10296 return true;
10297 if (FirstType->isRVVSizelessBuiltinType()) {
10298 SVEorRVV = 1;
10299 return true;
10300 }
10301 }
10302
10303 return false;
10304 };
10305
10306 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10307 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10308 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10309 << SVEorRVV << LHSType << RHSType;
10310 return QualType();
10311 }
10312
10313 // If there's a vector type and a scalar, try to convert the scalar to
10314 // the vector element type and splat.
10315 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10316 if (!RHSVecType) {
10317 if (isa<ExtVectorType>(LHSVecType)) {
10318 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10319 LHSVecType->getElementType(), LHSType,
10320 DiagID))
10321 return LHSType;
10322 } else {
10323 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10324 return LHSType;
10325 }
10326 }
10327 if (!LHSVecType) {
10328 if (isa<ExtVectorType>(RHSVecType)) {
10329 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10330 LHSType, RHSVecType->getElementType(),
10331 RHSType, DiagID))
10332 return RHSType;
10333 } else {
10334 if (LHS.get()->isLValue() ||
10335 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10336 return RHSType;
10337 }
10338 }
10339
10340 // FIXME: The code below also handles conversion between vectors and
10341 // non-scalars, we should break this down into fine grained specific checks
10342 // and emit proper diagnostics.
10343 QualType VecType = LHSVecType ? LHSType : RHSType;
10344 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10345 QualType OtherType = LHSVecType ? RHSType : LHSType;
10346 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10347 if (isLaxVectorConversion(OtherType, VecType)) {
10348 if (Context.getTargetInfo().getTriple().isPPC() &&
10349 anyAltivecTypes(RHSType, LHSType) &&
10350 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10351 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10352 // If we're allowing lax vector conversions, only the total (data) size
10353 // needs to be the same. For non compound assignment, if one of the types is
10354 // scalar, the result is always the vector type.
10355 if (!IsCompAssign) {
10356 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10357 return VecType;
10358 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10359 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10360 // type. Note that this is already done by non-compound assignments in
10361 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10362 // <1 x T> -> T. The result is also a vector type.
10363 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10364 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10365 ExprResult *RHSExpr = &RHS;
10366 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10367 return VecType;
10368 }
10369 }
10370
10371 // Okay, the expression is invalid.
10372
10373 // If there's a non-vector, non-real operand, diagnose that.
10374 if ((!RHSVecType && !RHSType->isRealType()) ||
10375 (!LHSVecType && !LHSType->isRealType())) {
10376 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10377 << LHSType << RHSType
10378 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10379 return QualType();
10380 }
10381
10382 // OpenCL V1.1 6.2.6.p1:
10383 // If the operands are of more than one vector type, then an error shall
10384 // occur. Implicit conversions between vector types are not permitted, per
10385 // section 6.2.1.
10386 if (getLangOpts().OpenCL &&
10387 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10388 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10389 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10390 << RHSType;
10391 return QualType();
10392 }
10393
10394
10395 // If there is a vector type that is not a ExtVector and a scalar, we reach
10396 // this point if scalar could not be converted to the vector's element type
10397 // without truncation.
10398 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10399 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10400 QualType Scalar = LHSVecType ? RHSType : LHSType;
10401 QualType Vector = LHSVecType ? LHSType : RHSType;
10402 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10403 Diag(Loc,
10404 diag::err_typecheck_vector_not_convertable_implict_truncation)
10405 << ScalarOrVector << Scalar << Vector;
10406
10407 return QualType();
10408 }
10409
10410 // Otherwise, use the generic diagnostic.
10411 Diag(Loc, DiagID)
10412 << LHSType << RHSType
10413 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10414 return QualType();
10415}
10416
10419 bool IsCompAssign,
10420 ArithConvKind OperationKind) {
10421 if (!IsCompAssign) {
10423 if (LHS.isInvalid())
10424 return QualType();
10425 }
10427 if (RHS.isInvalid())
10428 return QualType();
10429
10430 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10431 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10432
10433 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10434 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10435
10436 unsigned DiagID = diag::err_typecheck_invalid_operands;
10437 if ((OperationKind == ACK_Arithmetic) &&
10438 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10439 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10440 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10441 << RHS.get()->getSourceRange();
10442 return QualType();
10443 }
10444
10445 if (Context.hasSameType(LHSType, RHSType))
10446 return LHSType;
10447
10448 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10449 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10450 return LHSType;
10451 }
10452 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10453 if (LHS.get()->isLValue() ||
10454 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10455 return RHSType;
10456 }
10457
10458 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10459 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10460 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10461 << LHSType << RHSType << LHS.get()->getSourceRange()
10462 << RHS.get()->getSourceRange();
10463 return QualType();
10464 }
10465
10466 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10467 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10468 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10469 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10470 << LHSType << RHSType << LHS.get()->getSourceRange()
10471 << RHS.get()->getSourceRange();
10472 return QualType();
10473 }
10474
10475 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10476 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10477 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10478 bool ScalarOrVector =
10479 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10480
10481 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10482 << ScalarOrVector << Scalar << Vector;
10483
10484 return QualType();
10485 }
10486
10487 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10488 << RHS.get()->getSourceRange();
10489 return QualType();
10490}
10491
10492// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10493// expression. These are mainly cases where the null pointer is used as an
10494// integer instead of a pointer.
10496 SourceLocation Loc, bool IsCompare) {
10497 // The canonical way to check for a GNU null is with isNullPointerConstant,
10498 // but we use a bit of a hack here for speed; this is a relatively
10499 // hot path, and isNullPointerConstant is slow.
10500 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10501 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10502
10503 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10504
10505 // Avoid analyzing cases where the result will either be invalid (and
10506 // diagnosed as such) or entirely valid and not something to warn about.
10507 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10508 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10509 return;
10510
10511 // Comparison operations would not make sense with a null pointer no matter
10512 // what the other expression is.
10513 if (!IsCompare) {
10514 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10515 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10516 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10517 return;
10518 }
10519
10520 // The rest of the operations only make sense with a null pointer
10521 // if the other expression is a pointer.
10522 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10523 NonNullType->canDecayToPointerType())
10524 return;
10525
10526 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10527 << LHSNull /* LHS is NULL */ << NonNullType
10528 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10529}
10530
10533 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10534 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10535 if (!LUE || !RUE)
10536 return;
10537 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10538 RUE->getKind() != UETT_SizeOf)
10539 return;
10540
10541 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10542 QualType LHSTy = LHSArg->getType();
10543 QualType RHSTy;
10544
10545 if (RUE->isArgumentType())
10546 RHSTy = RUE->getArgumentType().getNonReferenceType();
10547 else
10548 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10549
10550 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10551 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10552 return;
10553
10554 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10555 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10556 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10557 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10558 << LHSArgDecl;
10559 }
10560 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10561 QualType ArrayElemTy = ArrayTy->getElementType();
10562 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10563 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10564 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10565 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10566 return;
10567 S.Diag(Loc, diag::warn_division_sizeof_array)
10568 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10569 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10570 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10571 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10572 << LHSArgDecl;
10573 }
10574
10575 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10576 }
10577}
10578
10580 ExprResult &RHS,
10581 SourceLocation Loc, bool IsDiv) {
10582 // Check for division/remainder by zero.
10583 Expr::EvalResult RHSValue;
10584 if (!RHS.get()->isValueDependent() &&
10585 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10586 RHSValue.Val.getInt() == 0)
10587 S.DiagRuntimeBehavior(Loc, RHS.get(),
10588 S.PDiag(diag::warn_remainder_division_by_zero)
10589 << IsDiv << RHS.get()->getSourceRange());
10590}
10591
10594 bool IsCompAssign, bool IsDiv) {
10595 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10596
10597 QualType LHSTy = LHS.get()->getType();
10598 QualType RHSTy = RHS.get()->getType();
10599 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10600 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10601 /*AllowBothBool*/ getLangOpts().AltiVec,
10602 /*AllowBoolConversions*/ false,
10603 /*AllowBooleanOperation*/ false,
10604 /*ReportInvalid*/ true);
10605 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10606 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10608 if (!IsDiv &&
10609 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10610 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10611 // For division, only matrix-by-scalar is supported. Other combinations with
10612 // matrix types are invalid.
10613 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10614 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10615
10617 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10618 if (LHS.isInvalid() || RHS.isInvalid())
10619 return QualType();
10620
10621
10622 if (compType.isNull() || !compType->isArithmeticType())
10623 return InvalidOperands(Loc, LHS, RHS);
10624 if (IsDiv) {
10625 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10626 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10627 }
10628 return compType;
10629}
10630
10632 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10633 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10634
10635 if (LHS.get()->getType()->isVectorType() ||
10636 RHS.get()->getType()->isVectorType()) {
10637 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10639 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10640 /*AllowBothBool*/ getLangOpts().AltiVec,
10641 /*AllowBoolConversions*/ false,
10642 /*AllowBooleanOperation*/ false,
10643 /*ReportInvalid*/ true);
10644 return InvalidOperands(Loc, LHS, RHS);
10645 }
10646
10647 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10648 RHS.get()->getType()->isSveVLSBuiltinType()) {
10649 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10651 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10653
10654 return InvalidOperands(Loc, LHS, RHS);
10655 }
10656
10658 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10659 if (LHS.isInvalid() || RHS.isInvalid())
10660 return QualType();
10661
10662 if (compType.isNull() || !compType->isIntegerType())
10663 return InvalidOperands(Loc, LHS, RHS);
10664 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
10665 return compType;
10666}
10667
10668/// Diagnose invalid arithmetic on two void pointers.
10670 Expr *LHSExpr, Expr *RHSExpr) {
10671 S.Diag(Loc, S.getLangOpts().CPlusPlus
10672 ? diag::err_typecheck_pointer_arith_void_type
10673 : diag::ext_gnu_void_ptr)
10674 << 1 /* two pointers */ << LHSExpr->getSourceRange()
10675 << RHSExpr->getSourceRange();
10676}
10677
10678/// Diagnose invalid arithmetic on a void pointer.
10680 Expr *Pointer) {
10681 S.Diag(Loc, S.getLangOpts().CPlusPlus
10682 ? diag::err_typecheck_pointer_arith_void_type
10683 : diag::ext_gnu_void_ptr)
10684 << 0 /* one pointer */ << Pointer->getSourceRange();
10685}
10686
10687/// Diagnose invalid arithmetic on a null pointer.
10688///
10689/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
10690/// idiom, which we recognize as a GNU extension.
10691///
10693 Expr *Pointer, bool IsGNUIdiom) {
10694 if (IsGNUIdiom)
10695 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
10696 << Pointer->getSourceRange();
10697 else
10698 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
10699 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
10700}
10701
10702/// Diagnose invalid subraction on a null pointer.
10703///
10705 Expr *Pointer, bool BothNull) {
10706 // Null - null is valid in C++ [expr.add]p7
10707 if (BothNull && S.getLangOpts().CPlusPlus)
10708 return;
10709
10710 // Is this s a macro from a system header?
10712 return;
10713
10715 S.PDiag(diag::warn_pointer_sub_null_ptr)
10716 << S.getLangOpts().CPlusPlus
10717 << Pointer->getSourceRange());
10718}
10719
10720/// Diagnose invalid arithmetic on two function pointers.
10722 Expr *LHS, Expr *RHS) {
10723 assert(LHS->getType()->isAnyPointerType());
10724 assert(RHS->getType()->isAnyPointerType());
10725 S.Diag(Loc, S.getLangOpts().CPlusPlus
10726 ? diag::err_typecheck_pointer_arith_function_type
10727 : diag::ext_gnu_ptr_func_arith)
10728 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
10729 // We only show the second type if it differs from the first.
10731 RHS->getType())
10732 << RHS->getType()->getPointeeType()
10733 << LHS->getSourceRange() << RHS->getSourceRange();
10734}
10735
10736/// Diagnose invalid arithmetic on a function pointer.
10738 Expr *Pointer) {
10739 assert(Pointer->getType()->isAnyPointerType());
10740 S.Diag(Loc, S.getLangOpts().CPlusPlus
10741 ? diag::err_typecheck_pointer_arith_function_type
10742 : diag::ext_gnu_ptr_func_arith)
10743 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
10744 << 0 /* one pointer, so only one type */
10745 << Pointer->getSourceRange();
10746}
10747
10748/// Emit error if Operand is incomplete pointer type
10749///
10750/// \returns True if pointer has incomplete type
10752 Expr *Operand) {
10753 QualType ResType = Operand->getType();
10754 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10755 ResType = ResAtomicType->getValueType();
10756
10757 assert(ResType->isAnyPointerType());
10758 QualType PointeeTy = ResType->getPointeeType();
10759 return S.RequireCompleteSizedType(
10760 Loc, PointeeTy,
10761 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
10762 Operand->getSourceRange());
10763}
10764
10765/// Check the validity of an arithmetic pointer operand.
10766///
10767/// If the operand has pointer type, this code will check for pointer types
10768/// which are invalid in arithmetic operations. These will be diagnosed
10769/// appropriately, including whether or not the use is supported as an
10770/// extension.
10771///
10772/// \returns True when the operand is valid to use (even if as an extension).
10774 Expr *Operand) {
10775 QualType ResType = Operand->getType();
10776 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10777 ResType = ResAtomicType->getValueType();
10778
10779 if (!ResType->isAnyPointerType()) return true;
10780
10781 QualType PointeeTy = ResType->getPointeeType();
10782 if (PointeeTy->isVoidType()) {
10784 return !S.getLangOpts().CPlusPlus;
10785 }
10786 if (PointeeTy->isFunctionType()) {
10788 return !S.getLangOpts().CPlusPlus;
10789 }
10790
10791 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
10792
10793 return true;
10794}
10795
10796/// Check the validity of a binary arithmetic operation w.r.t. pointer
10797/// operands.
10798///
10799/// This routine will diagnose any invalid arithmetic on pointer operands much
10800/// like \see checkArithmeticOpPointerOperand. However, it has special logic
10801/// for emitting a single diagnostic even for operations where both LHS and RHS
10802/// are (potentially problematic) pointers.
10803///
10804/// \returns True when the operand is valid to use (even if as an extension).
10806 Expr *LHSExpr, Expr *RHSExpr) {
10807 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
10808 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
10809 if (!isLHSPointer && !isRHSPointer) return true;
10810
10811 QualType LHSPointeeTy, RHSPointeeTy;
10812 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
10813 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
10814
10815 // if both are pointers check if operation is valid wrt address spaces
10816 if (isLHSPointer && isRHSPointer) {
10817 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy,
10818 S.getASTContext())) {
10819 S.Diag(Loc,
10820 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10821 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
10822 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10823 return false;
10824 }
10825 }
10826
10827 // Check for arithmetic on pointers to incomplete types.
10828 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
10829 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
10830 if (isLHSVoidPtr || isRHSVoidPtr) {
10831 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
10832 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
10833 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
10834
10835 return !S.getLangOpts().CPlusPlus;
10836 }
10837
10838 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
10839 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
10840 if (isLHSFuncPtr || isRHSFuncPtr) {
10841 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
10842 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
10843 RHSExpr);
10844 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
10845
10846 return !S.getLangOpts().CPlusPlus;
10847 }
10848
10849 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
10850 return false;
10851 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
10852 return false;
10853
10854 return true;
10855}
10856
10857/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
10858/// literal.
10860 Expr *LHSExpr, Expr *RHSExpr) {
10861 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
10862 Expr* IndexExpr = RHSExpr;
10863 if (!StrExpr) {
10864 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
10865 IndexExpr = LHSExpr;
10866 }
10867
10868 bool IsStringPlusInt = StrExpr &&
10870 if (!IsStringPlusInt || IndexExpr->isValueDependent())
10871 return;
10872
10873 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10874 Self.Diag(OpLoc, diag::warn_string_plus_int)
10875 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
10876
10877 // Only print a fixit for "str" + int, not for int + "str".
10878 if (IndexExpr == RHSExpr) {
10879 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10880 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10881 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10883 << FixItHint::CreateInsertion(EndLoc, "]");
10884 } else
10885 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10886}
10887
10888/// Emit a warning when adding a char literal to a string.
10890 Expr *LHSExpr, Expr *RHSExpr) {
10891 const Expr *StringRefExpr = LHSExpr;
10892 const CharacterLiteral *CharExpr =
10893 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
10894
10895 if (!CharExpr) {
10896 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
10897 StringRefExpr = RHSExpr;
10898 }
10899
10900 if (!CharExpr || !StringRefExpr)
10901 return;
10902
10903 const QualType StringType = StringRefExpr->getType();
10904
10905 // Return if not a PointerType.
10906 if (!StringType->isAnyPointerType())
10907 return;
10908
10909 // Return if not a CharacterType.
10910 if (!StringType->getPointeeType()->isAnyCharacterType())
10911 return;
10912
10913 ASTContext &Ctx = Self.getASTContext();
10914 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
10915
10916 const QualType CharType = CharExpr->getType();
10917 if (!CharType->isAnyCharacterType() &&
10918 CharType->isIntegerType() &&
10919 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
10920 Self.Diag(OpLoc, diag::warn_string_plus_char)
10921 << DiagRange << Ctx.CharTy;
10922 } else {
10923 Self.Diag(OpLoc, diag::warn_string_plus_char)
10924 << DiagRange << CharExpr->getType();
10925 }
10926
10927 // Only print a fixit for str + char, not for char + str.
10928 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
10929 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
10930 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
10931 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
10933 << FixItHint::CreateInsertion(EndLoc, "]");
10934 } else {
10935 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
10936 }
10937}
10938
10939/// Emit error when two pointers are incompatible.
10941 Expr *LHSExpr, Expr *RHSExpr) {
10942 assert(LHSExpr->getType()->isAnyPointerType());
10943 assert(RHSExpr->getType()->isAnyPointerType());
10944 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
10945 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
10946 << RHSExpr->getSourceRange();
10947}
10948
10949// C99 6.5.6
10952 QualType* CompLHSTy) {
10953 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10954
10955 if (LHS.get()->getType()->isVectorType() ||
10956 RHS.get()->getType()->isVectorType()) {
10957 QualType compType =
10958 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
10959 /*AllowBothBool*/ getLangOpts().AltiVec,
10960 /*AllowBoolConversions*/ getLangOpts().ZVector,
10961 /*AllowBooleanOperation*/ false,
10962 /*ReportInvalid*/ true);
10963 if (CompLHSTy) *CompLHSTy = compType;
10964 return compType;
10965 }
10966
10967 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
10968 RHS.get()->getType()->isSveVLSBuiltinType()) {
10969 QualType compType =
10970 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
10971 if (CompLHSTy)
10972 *CompLHSTy = compType;
10973 return compType;
10974 }
10975
10976 if (LHS.get()->getType()->isConstantMatrixType() ||
10977 RHS.get()->getType()->isConstantMatrixType()) {
10978 QualType compType =
10979 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
10980 if (CompLHSTy)
10981 *CompLHSTy = compType;
10982 return compType;
10983 }
10984
10986 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
10987 if (LHS.isInvalid() || RHS.isInvalid())
10988 return QualType();
10989
10990 // Diagnose "string literal" '+' int and string '+' "char literal".
10991 if (Opc == BO_Add) {
10992 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
10993 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
10994 }
10995
10996 // handle the common case first (both operands are arithmetic).
10997 if (!compType.isNull() && compType->isArithmeticType()) {
10998 if (CompLHSTy) *CompLHSTy = compType;
10999 return compType;
11000 }
11001
11002 // Type-checking. Ultimately the pointer's going to be in PExp;
11003 // note that we bias towards the LHS being the pointer.
11004 Expr *PExp = LHS.get(), *IExp = RHS.get();
11005
11006 bool isObjCPointer;
11007 if (PExp->getType()->isPointerType()) {
11008 isObjCPointer = false;
11009 } else if (PExp->getType()->isObjCObjectPointerType()) {
11010 isObjCPointer = true;
11011 } else {
11012 std::swap(PExp, IExp);
11013 if (PExp->getType()->isPointerType()) {
11014 isObjCPointer = false;
11015 } else if (PExp->getType()->isObjCObjectPointerType()) {
11016 isObjCPointer = true;
11017 } else {
11018 return InvalidOperands(Loc, LHS, RHS);
11019 }
11020 }
11021 assert(PExp->getType()->isAnyPointerType());
11022
11023 if (!IExp->getType()->isIntegerType())
11024 return InvalidOperands(Loc, LHS, RHS);
11025
11026 // Adding to a null pointer results in undefined behavior.
11029 // In C++ adding zero to a null pointer is defined.
11030 Expr::EvalResult KnownVal;
11031 if (!getLangOpts().CPlusPlus ||
11032 (!IExp->isValueDependent() &&
11033 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11034 KnownVal.Val.getInt() != 0))) {
11035 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11037 Context, BO_Add, PExp, IExp);
11038 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11039 }
11040 }
11041
11042 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11043 return QualType();
11044
11045 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11046 return QualType();
11047
11048 // Arithmetic on label addresses is normally allowed, except when we add
11049 // a ptrauth signature to the addresses.
11050 if (isa<AddrLabelExpr>(PExp) && getLangOpts().PointerAuthIndirectGotos) {
11051 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11052 << /*addition*/ 1;
11053 return QualType();
11054 }
11055
11056 // Check array bounds for pointer arithemtic
11057 CheckArrayAccess(PExp, IExp);
11058
11059 if (CompLHSTy) {
11061 if (LHSTy.isNull()) {
11062 LHSTy = LHS.get()->getType();
11064 LHSTy = Context.getPromotedIntegerType(LHSTy);
11065 }
11066 *CompLHSTy = LHSTy;
11067 }
11068
11069 return PExp->getType();
11070}
11071
11072// C99 6.5.6
11075 QualType* CompLHSTy) {
11076 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11077
11078 if (LHS.get()->getType()->isVectorType() ||
11079 RHS.get()->getType()->isVectorType()) {
11080 QualType compType =
11081 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11082 /*AllowBothBool*/ getLangOpts().AltiVec,
11083 /*AllowBoolConversions*/ getLangOpts().ZVector,
11084 /*AllowBooleanOperation*/ false,
11085 /*ReportInvalid*/ true);
11086 if (CompLHSTy) *CompLHSTy = compType;
11087 return compType;
11088 }
11089
11090 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11091 RHS.get()->getType()->isSveVLSBuiltinType()) {
11092 QualType compType =
11093 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11094 if (CompLHSTy)
11095 *CompLHSTy = compType;
11096 return compType;
11097 }
11098
11099 if (LHS.get()->getType()->isConstantMatrixType() ||
11100 RHS.get()->getType()->isConstantMatrixType()) {
11101 QualType compType =
11102 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11103 if (CompLHSTy)
11104 *CompLHSTy = compType;
11105 return compType;
11106 }
11107
11109 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11110 if (LHS.isInvalid() || RHS.isInvalid())
11111 return QualType();
11112
11113 // Enforce type constraints: C99 6.5.6p3.
11114
11115 // Handle the common case first (both operands are arithmetic).
11116 if (!compType.isNull() && compType->isArithmeticType()) {
11117 if (CompLHSTy) *CompLHSTy = compType;
11118 return compType;
11119 }
11120
11121 // Either ptr - int or ptr - ptr.
11122 if (LHS.get()->getType()->isAnyPointerType()) {
11123 QualType lpointee = LHS.get()->getType()->getPointeeType();
11124
11125 // Diagnose bad cases where we step over interface counts.
11126 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11127 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11128 return QualType();
11129
11130 // Arithmetic on label addresses is normally allowed, except when we add
11131 // a ptrauth signature to the addresses.
11132 if (isa<AddrLabelExpr>(LHS.get()) &&
11133 getLangOpts().PointerAuthIndirectGotos) {
11134 Diag(Loc, diag::err_ptrauth_indirect_goto_addrlabel_arithmetic)
11135 << /*subtraction*/ 0;
11136 return QualType();
11137 }
11138
11139 // The result type of a pointer-int computation is the pointer type.
11140 if (RHS.get()->getType()->isIntegerType()) {
11141 // Subtracting from a null pointer should produce a warning.
11142 // The last argument to the diagnose call says this doesn't match the
11143 // GNU int-to-pointer idiom.
11146 // In C++ adding zero to a null pointer is defined.
11147 Expr::EvalResult KnownVal;
11148 if (!getLangOpts().CPlusPlus ||
11149 (!RHS.get()->isValueDependent() &&
11150 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11151 KnownVal.Val.getInt() != 0))) {
11152 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11153 }
11154 }
11155
11156 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11157 return QualType();
11158
11159 // Check array bounds for pointer arithemtic
11160 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11161 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11162
11163 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11164 return LHS.get()->getType();
11165 }
11166
11167 // Handle pointer-pointer subtractions.
11168 if (const PointerType *RHSPTy
11169 = RHS.get()->getType()->getAs<PointerType>()) {
11170 QualType rpointee = RHSPTy->getPointeeType();
11171
11172 if (getLangOpts().CPlusPlus) {
11173 // Pointee types must be the same: C++ [expr.add]
11174 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11175 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11176 }
11177 } else {
11178 // Pointee types must be compatible C99 6.5.6p3
11182 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11183 return QualType();
11184 }
11185 }
11186
11188 LHS.get(), RHS.get()))
11189 return QualType();
11190
11191 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11193 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11195
11196 // Subtracting nullptr or from nullptr is suspect
11197 if (LHSIsNullPtr)
11198 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11199 if (RHSIsNullPtr)
11200 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11201
11202 // The pointee type may have zero size. As an extension, a structure or
11203 // union may have zero size or an array may have zero length. In this
11204 // case subtraction does not make sense.
11205 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11206 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11207 if (ElementSize.isZero()) {
11208 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11209 << rpointee.getUnqualifiedType()
11210 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11211 }
11212 }
11213
11214 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11215 return Context.getPointerDiffType();
11216 }
11217 }
11218
11219 return InvalidOperands(Loc, LHS, RHS);
11220}
11221
11223 if (const EnumType *ET = T->getAs<EnumType>())
11224 return ET->getDecl()->isScoped();
11225 return false;
11226}
11227
11230 QualType LHSType) {
11231 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11232 // so skip remaining warnings as we don't want to modify values within Sema.
11233 if (S.getLangOpts().OpenCL)
11234 return;
11235
11236 // Check right/shifter operand
11237 Expr::EvalResult RHSResult;
11238 if (RHS.get()->isValueDependent() ||
11239 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11240 return;
11241 llvm::APSInt Right = RHSResult.Val.getInt();
11242
11243 if (Right.isNegative()) {
11244 S.DiagRuntimeBehavior(Loc, RHS.get(),
11245 S.PDiag(diag::warn_shift_negative)
11246 << RHS.get()->getSourceRange());
11247 return;
11248 }
11249
11250 QualType LHSExprType = LHS.get()->getType();
11251 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11252 if (LHSExprType->isBitIntType())
11253 LeftSize = S.Context.getIntWidth(LHSExprType);
11254 else if (LHSExprType->isFixedPointType()) {
11255 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11256 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11257 }
11258 if (Right.uge(LeftSize)) {
11259 S.DiagRuntimeBehavior(Loc, RHS.get(),
11260 S.PDiag(diag::warn_shift_gt_typewidth)
11261 << RHS.get()->getSourceRange());
11262 return;
11263 }
11264
11265 // FIXME: We probably need to handle fixed point types specially here.
11266 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11267 return;
11268
11269 // When left shifting an ICE which is signed, we can check for overflow which
11270 // according to C++ standards prior to C++2a has undefined behavior
11271 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11272 // more than the maximum value representable in the result type, so never
11273 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11274 // expression is still probably a bug.)
11275 Expr::EvalResult LHSResult;
11276 if (LHS.get()->isValueDependent() ||
11278 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11279 return;
11280 llvm::APSInt Left = LHSResult.Val.getInt();
11281
11282 // Don't warn if signed overflow is defined, then all the rest of the
11283 // diagnostics will not be triggered because the behavior is defined.
11284 // Also don't warn in C++20 mode (and newer), as signed left shifts
11285 // always wrap and never overflow.
11286 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11287 return;
11288
11289 // If LHS does not have a non-negative value then, the
11290 // behavior is undefined before C++2a. Warn about it.
11291 if (Left.isNegative()) {
11292 S.DiagRuntimeBehavior(Loc, LHS.get(),
11293 S.PDiag(diag::warn_shift_lhs_negative)
11294 << LHS.get()->getSourceRange());
11295 return;
11296 }
11297
11298 llvm::APInt ResultBits =
11299 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11300 if (ResultBits.ule(LeftSize))
11301 return;
11302 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11303 Result = Result.shl(Right);
11304
11305 // Print the bit representation of the signed integer as an unsigned
11306 // hexadecimal number.
11307 SmallString<40> HexResult;
11308 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11309
11310 // If we are only missing a sign bit, this is less likely to result in actual
11311 // bugs -- if the result is cast back to an unsigned type, it will have the
11312 // expected value. Thus we place this behind a different warning that can be
11313 // turned off separately if needed.
11314 if (ResultBits - 1 == LeftSize) {
11315 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11316 << HexResult << LHSType
11317 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11318 return;
11319 }
11320
11321 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11322 << HexResult.str() << Result.getSignificantBits() << LHSType
11323 << Left.getBitWidth() << LHS.get()->getSourceRange()
11324 << RHS.get()->getSourceRange();
11325}
11326
11327/// Return the resulting type when a vector is shifted
11328/// by a scalar or vector shift amount.
11330 SourceLocation Loc, bool IsCompAssign) {
11331 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11332 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11333 !LHS.get()->getType()->isVectorType()) {
11334 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11335 << RHS.get()->getType() << LHS.get()->getType()
11336 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11337 return QualType();
11338 }
11339
11340 if (!IsCompAssign) {
11341 LHS = S.UsualUnaryConversions(LHS.get());
11342 if (LHS.isInvalid()) return QualType();
11343 }
11344
11345 RHS = S.UsualUnaryConversions(RHS.get());
11346 if (RHS.isInvalid()) return QualType();
11347
11348 QualType LHSType = LHS.get()->getType();
11349 // Note that LHS might be a scalar because the routine calls not only in
11350 // OpenCL case.
11351 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11352 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11353
11354 // Note that RHS might not be a vector.
11355 QualType RHSType = RHS.get()->getType();
11356 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11357 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11358
11359 // Do not allow shifts for boolean vectors.
11360 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11361 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11362 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11363 << LHS.get()->getType() << RHS.get()->getType()
11364 << LHS.get()->getSourceRange();
11365 return QualType();
11366 }
11367
11368 // The operands need to be integers.
11369 if (!LHSEleType->isIntegerType()) {
11370 S.Diag(Loc, diag::err_typecheck_expect_int)
11371 << LHS.get()->getType() << LHS.get()->getSourceRange();
11372 return QualType();
11373 }
11374
11375 if (!RHSEleType->isIntegerType()) {
11376 S.Diag(Loc, diag::err_typecheck_expect_int)
11377 << RHS.get()->getType() << RHS.get()->getSourceRange();
11378 return QualType();
11379 }
11380
11381 if (!LHSVecTy) {
11382 assert(RHSVecTy);
11383 if (IsCompAssign)
11384 return RHSType;
11385 if (LHSEleType != RHSEleType) {
11386 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11387 LHSEleType = RHSEleType;
11388 }
11389 QualType VecTy =
11390 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11391 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11392 LHSType = VecTy;
11393 } else if (RHSVecTy) {
11394 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11395 // are applied component-wise. So if RHS is a vector, then ensure
11396 // that the number of elements is the same as LHS...
11397 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11398 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11399 << LHS.get()->getType() << RHS.get()->getType()
11400 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11401 return QualType();
11402 }
11403 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11404 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11405 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11406 if (LHSBT != RHSBT &&
11407 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11408 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11409 << LHS.get()->getType() << RHS.get()->getType()
11410 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11411 }
11412 }
11413 } else {
11414 // ...else expand RHS to match the number of elements in LHS.
11415 QualType VecTy =
11416 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11417 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11418 }
11419
11420 return LHSType;
11421}
11422
11425 bool IsCompAssign) {
11426 if (!IsCompAssign) {
11427 LHS = S.UsualUnaryConversions(LHS.get());
11428 if (LHS.isInvalid())
11429 return QualType();
11430 }
11431
11432 RHS = S.UsualUnaryConversions(RHS.get());
11433 if (RHS.isInvalid())
11434 return QualType();
11435
11436 QualType LHSType = LHS.get()->getType();
11437 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11438 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11439 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11440 : LHSType;
11441
11442 // Note that RHS might not be a vector
11443 QualType RHSType = RHS.get()->getType();
11444 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11445 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11446 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11447 : RHSType;
11448
11449 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11450 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11451 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11452 << LHSType << RHSType << LHS.get()->getSourceRange();
11453 return QualType();
11454 }
11455
11456 if (!LHSEleType->isIntegerType()) {
11457 S.Diag(Loc, diag::err_typecheck_expect_int)
11458 << LHS.get()->getType() << LHS.get()->getSourceRange();
11459 return QualType();
11460 }
11461
11462 if (!RHSEleType->isIntegerType()) {
11463 S.Diag(Loc, diag::err_typecheck_expect_int)
11464 << RHS.get()->getType() << RHS.get()->getSourceRange();
11465 return QualType();
11466 }
11467
11468 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11469 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11470 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11471 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11472 << LHSType << RHSType << LHS.get()->getSourceRange()
11473 << RHS.get()->getSourceRange();
11474 return QualType();
11475 }
11476
11477 if (!LHSType->isSveVLSBuiltinType()) {
11478 assert(RHSType->isSveVLSBuiltinType());
11479 if (IsCompAssign)
11480 return RHSType;
11481 if (LHSEleType != RHSEleType) {
11482 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11483 LHSEleType = RHSEleType;
11484 }
11485 const llvm::ElementCount VecSize =
11486 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11487 QualType VecTy =
11488 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11489 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11490 LHSType = VecTy;
11491 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11492 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11493 S.Context.getTypeSize(LHSBuiltinTy)) {
11494 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11495 << LHSType << RHSType << LHS.get()->getSourceRange()
11496 << RHS.get()->getSourceRange();
11497 return QualType();
11498 }
11499 } else {
11500 const llvm::ElementCount VecSize =
11501 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11502 if (LHSEleType != RHSEleType) {
11503 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11504 RHSEleType = LHSEleType;
11505 }
11506 QualType VecTy =
11507 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11508 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11509 }
11510
11511 return LHSType;
11512}
11513
11514// C99 6.5.7
11517 bool IsCompAssign) {
11518 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11519
11520 // Vector shifts promote their scalar inputs to vector type.
11521 if (LHS.get()->getType()->isVectorType() ||
11522 RHS.get()->getType()->isVectorType()) {
11523 if (LangOpts.ZVector) {
11524 // The shift operators for the z vector extensions work basically
11525 // like general shifts, except that neither the LHS nor the RHS is
11526 // allowed to be a "vector bool".
11527 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11528 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11529 return InvalidOperands(Loc, LHS, RHS);
11530 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11531 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11532 return InvalidOperands(Loc, LHS, RHS);
11533 }
11534 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11535 }
11536
11537 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11538 RHS.get()->getType()->isSveVLSBuiltinType())
11539 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11540
11541 // Shifts don't perform usual arithmetic conversions, they just do integer
11542 // promotions on each operand. C99 6.5.7p3
11543
11544 // For the LHS, do usual unary conversions, but then reset them away
11545 // if this is a compound assignment.
11546 ExprResult OldLHS = LHS;
11547 LHS = UsualUnaryConversions(LHS.get());
11548 if (LHS.isInvalid())
11549 return QualType();
11550 QualType LHSType = LHS.get()->getType();
11551 if (IsCompAssign) LHS = OldLHS;
11552
11553 // The RHS is simpler.
11554 RHS = UsualUnaryConversions(RHS.get());
11555 if (RHS.isInvalid())
11556 return QualType();
11557 QualType RHSType = RHS.get()->getType();
11558
11559 // C99 6.5.7p2: Each of the operands shall have integer type.
11560 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11561 if ((!LHSType->isFixedPointOrIntegerType() &&
11562 !LHSType->hasIntegerRepresentation()) ||
11563 !RHSType->hasIntegerRepresentation())
11564 return InvalidOperands(Loc, LHS, RHS);
11565
11566 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11567 // hasIntegerRepresentation() above instead of this.
11568 if (isScopedEnumerationType(LHSType) ||
11569 isScopedEnumerationType(RHSType)) {
11570 return InvalidOperands(Loc, LHS, RHS);
11571 }
11572 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11573
11574 // "The type of the result is that of the promoted left operand."
11575 return LHSType;
11576}
11577
11578/// Diagnose bad pointer comparisons.
11580 ExprResult &LHS, ExprResult &RHS,
11581 bool IsError) {
11582 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11583 : diag::ext_typecheck_comparison_of_distinct_pointers)
11584 << LHS.get()->getType() << RHS.get()->getType()
11585 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11586}
11587
11588/// Returns false if the pointers are converted to a composite type,
11589/// true otherwise.
11591 ExprResult &LHS, ExprResult &RHS) {
11592 // C++ [expr.rel]p2:
11593 // [...] Pointer conversions (4.10) and qualification
11594 // conversions (4.4) are performed on pointer operands (or on
11595 // a pointer operand and a null pointer constant) to bring
11596 // them to their composite pointer type. [...]
11597 //
11598 // C++ [expr.eq]p1 uses the same notion for (in)equality
11599 // comparisons of pointers.
11600
11601 QualType LHSType = LHS.get()->getType();
11602 QualType RHSType = RHS.get()->getType();
11603 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11604 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11605
11606 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11607 if (T.isNull()) {
11608 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11609 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11610 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11611 else
11612 S.InvalidOperands(Loc, LHS, RHS);
11613 return true;
11614 }
11615
11616 return false;
11617}
11618
11620 ExprResult &LHS,
11621 ExprResult &RHS,
11622 bool IsError) {
11623 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11624 : diag::ext_typecheck_comparison_of_fptr_to_void)
11625 << LHS.get()->getType() << RHS.get()->getType()
11626 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11627}
11628
11630 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11631 case Stmt::ObjCArrayLiteralClass:
11632 case Stmt::ObjCDictionaryLiteralClass:
11633 case Stmt::ObjCStringLiteralClass:
11634 case Stmt::ObjCBoxedExprClass:
11635 return true;
11636 default:
11637 // Note that ObjCBoolLiteral is NOT an object literal!
11638 return false;
11639 }
11640}
11641
11642static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11645
11646 // If this is not actually an Objective-C object, bail out.
11647 if (!Type)
11648 return false;
11649
11650 // Get the LHS object's interface type.
11651 QualType InterfaceType = Type->getPointeeType();
11652
11653 // If the RHS isn't an Objective-C object, bail out.
11654 if (!RHS->getType()->isObjCObjectPointerType())
11655 return false;
11656
11657 // Try to find the -isEqual: method.
11658 Selector IsEqualSel = S.ObjC().NSAPIObj->getIsEqualSelector();
11659 ObjCMethodDecl *Method =
11660 S.ObjC().LookupMethodInObjectType(IsEqualSel, InterfaceType,
11661 /*IsInstance=*/true);
11662 if (!Method) {
11663 if (Type->isObjCIdType()) {
11664 // For 'id', just check the global pool.
11665 Method =
11667 /*receiverId=*/true);
11668 } else {
11669 // Check protocols.
11670 Method = S.ObjC().LookupMethodInQualifiedType(IsEqualSel, Type,
11671 /*IsInstance=*/true);
11672 }
11673 }
11674
11675 if (!Method)
11676 return false;
11677
11678 QualType T = Method->parameters()[0]->getType();
11679 if (!T->isObjCObjectPointerType())
11680 return false;
11681
11682 QualType R = Method->getReturnType();
11683 if (!R->isScalarType())
11684 return false;
11685
11686 return true;
11687}
11688
11690 ExprResult &LHS, ExprResult &RHS,
11692 Expr *Literal;
11693 Expr *Other;
11694 if (isObjCObjectLiteral(LHS)) {
11695 Literal = LHS.get();
11696 Other = RHS.get();
11697 } else {
11698 Literal = RHS.get();
11699 Other = LHS.get();
11700 }
11701
11702 // Don't warn on comparisons against nil.
11703 Other = Other->IgnoreParenCasts();
11704 if (Other->isNullPointerConstant(S.getASTContext(),
11706 return;
11707
11708 // This should be kept in sync with warn_objc_literal_comparison.
11709 // LK_String should always be after the other literals, since it has its own
11710 // warning flag.
11711 SemaObjC::ObjCLiteralKind LiteralKind = S.ObjC().CheckLiteralKind(Literal);
11712 assert(LiteralKind != SemaObjC::LK_Block);
11713 if (LiteralKind == SemaObjC::LK_None) {
11714 llvm_unreachable("Unknown Objective-C object literal kind");
11715 }
11716
11717 if (LiteralKind == SemaObjC::LK_String)
11718 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
11719 << Literal->getSourceRange();
11720 else
11721 S.Diag(Loc, diag::warn_objc_literal_comparison)
11722 << LiteralKind << Literal->getSourceRange();
11723
11725 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
11726 SourceLocation Start = LHS.get()->getBeginLoc();
11728 CharSourceRange OpRange =
11730
11731 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
11732 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
11733 << FixItHint::CreateReplacement(OpRange, " isEqual:")
11734 << FixItHint::CreateInsertion(End, "]");
11735 }
11736}
11737
11738/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
11741 BinaryOperatorKind Opc) {
11742 // Check that left hand side is !something.
11743 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
11744 if (!UO || UO->getOpcode() != UO_LNot) return;
11745
11746 // Only check if the right hand side is non-bool arithmetic type.
11747 if (RHS.get()->isKnownToHaveBooleanValue()) return;
11748
11749 // Make sure that the something in !something is not bool.
11750 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
11751 if (SubExpr->isKnownToHaveBooleanValue()) return;
11752
11753 // Emit warning.
11754 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
11755 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
11756 << Loc << IsBitwiseOp;
11757
11758 // First note suggest !(x < y)
11759 SourceLocation FirstOpen = SubExpr->getBeginLoc();
11760 SourceLocation FirstClose = RHS.get()->getEndLoc();
11761 FirstClose = S.getLocForEndOfToken(FirstClose);
11762 if (FirstClose.isInvalid())
11763 FirstOpen = SourceLocation();
11764 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
11765 << IsBitwiseOp
11766 << FixItHint::CreateInsertion(FirstOpen, "(")
11767 << FixItHint::CreateInsertion(FirstClose, ")");
11768
11769 // Second note suggests (!x) < y
11770 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
11771 SourceLocation SecondClose = LHS.get()->getEndLoc();
11772 SecondClose = S.getLocForEndOfToken(SecondClose);
11773 if (SecondClose.isInvalid())
11774 SecondOpen = SourceLocation();
11775 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
11776 << FixItHint::CreateInsertion(SecondOpen, "(")
11777 << FixItHint::CreateInsertion(SecondClose, ")");
11778}
11779
11780// Returns true if E refers to a non-weak array.
11781static bool checkForArray(const Expr *E) {
11782 const ValueDecl *D = nullptr;
11783 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
11784 D = DR->getDecl();
11785 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
11786 if (Mem->isImplicitAccess())
11787 D = Mem->getMemberDecl();
11788 }
11789 if (!D)
11790 return false;
11791 return D->getType()->isArrayType() && !D->isWeak();
11792}
11793
11794/// Detect patterns ptr + size >= ptr and ptr + size < ptr, where ptr is a
11795/// pointer and size is an unsigned integer. Return whether the result is
11796/// always true/false.
11797static std::optional<bool> isTautologicalBoundsCheck(Sema &S, const Expr *LHS,
11798 const Expr *RHS,
11799 BinaryOperatorKind Opc) {
11800 if (!LHS->getType()->isPointerType() ||
11802 return std::nullopt;
11803
11804 // Canonicalize to >= or < predicate.
11805 switch (Opc) {
11806 case BO_GE:
11807 case BO_LT:
11808 break;
11809 case BO_GT:
11810 std::swap(LHS, RHS);
11811 Opc = BO_LT;
11812 break;
11813 case BO_LE:
11814 std::swap(LHS, RHS);
11815 Opc = BO_GE;
11816 break;
11817 default:
11818 return std::nullopt;
11819 }
11820
11821 auto *BO = dyn_cast<BinaryOperator>(LHS);
11822 if (!BO || BO->getOpcode() != BO_Add)
11823 return std::nullopt;
11824
11825 Expr *Other;
11826 if (Expr::isSameComparisonOperand(BO->getLHS(), RHS))
11827 Other = BO->getRHS();
11828 else if (Expr::isSameComparisonOperand(BO->getRHS(), RHS))
11829 Other = BO->getLHS();
11830 else
11831 return std::nullopt;
11832
11833 if (!Other->getType()->isUnsignedIntegerType())
11834 return std::nullopt;
11835
11836 return Opc == BO_GE;
11837}
11838
11839/// Diagnose some forms of syntactically-obvious tautological comparison.
11841 Expr *LHS, Expr *RHS,
11842 BinaryOperatorKind Opc) {
11843 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
11844 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
11845
11846 QualType LHSType = LHS->getType();
11847 QualType RHSType = RHS->getType();
11848 if (LHSType->hasFloatingRepresentation() ||
11849 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
11851 return;
11852
11853 // WebAssembly Tables cannot be compared, therefore shouldn't emit
11854 // Tautological diagnostics.
11855 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
11856 return;
11857
11858 // Comparisons between two array types are ill-formed for operator<=>, so
11859 // we shouldn't emit any additional warnings about it.
11860 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
11861 return;
11862
11863 // For non-floating point types, check for self-comparisons of the form
11864 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
11865 // often indicate logic errors in the program.
11866 //
11867 // NOTE: Don't warn about comparison expressions resulting from macro
11868 // expansion. Also don't warn about comparisons which are only self
11869 // comparisons within a template instantiation. The warnings should catch
11870 // obvious cases in the definition of the template anyways. The idea is to
11871 // warn when the typed comparison operator will always evaluate to the same
11872 // result.
11873
11874 // Used for indexing into %select in warn_comparison_always
11875 enum {
11876 AlwaysConstant,
11877 AlwaysTrue,
11878 AlwaysFalse,
11879 AlwaysEqual, // std::strong_ordering::equal from operator<=>
11880 };
11881
11882 // C++1a [array.comp]:
11883 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11884 // operands of array type.
11885 // C++2a [depr.array.comp]:
11886 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
11887 // operands of array type are deprecated.
11888 if (S.getLangOpts().CPlusPlus && LHSStripped->getType()->isArrayType() &&
11889 RHSStripped->getType()->isArrayType()) {
11890 auto IsDeprArrayComparionIgnored =
11891 S.getDiagnostics().isIgnored(diag::warn_depr_array_comparison, Loc);
11892 auto DiagID = S.getLangOpts().CPlusPlus26
11893 ? diag::warn_array_comparison_cxx26
11894 : !S.getLangOpts().CPlusPlus20 || IsDeprArrayComparionIgnored
11895 ? diag::warn_array_comparison
11896 : diag::warn_depr_array_comparison;
11897 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
11898 << LHSStripped->getType() << RHSStripped->getType();
11899 // Carry on to produce the tautological comparison warning, if this
11900 // expression is potentially-evaluated, we can resolve the array to a
11901 // non-weak declaration, and so on.
11902 }
11903
11904 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
11905 if (Expr::isSameComparisonOperand(LHS, RHS)) {
11906 unsigned Result;
11907 switch (Opc) {
11908 case BO_EQ:
11909 case BO_LE:
11910 case BO_GE:
11911 Result = AlwaysTrue;
11912 break;
11913 case BO_NE:
11914 case BO_LT:
11915 case BO_GT:
11916 Result = AlwaysFalse;
11917 break;
11918 case BO_Cmp:
11919 Result = AlwaysEqual;
11920 break;
11921 default:
11922 Result = AlwaysConstant;
11923 break;
11924 }
11925 S.DiagRuntimeBehavior(Loc, nullptr,
11926 S.PDiag(diag::warn_comparison_always)
11927 << 0 /*self-comparison*/
11928 << Result);
11929 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
11930 // What is it always going to evaluate to?
11931 unsigned Result;
11932 switch (Opc) {
11933 case BO_EQ: // e.g. array1 == array2
11934 Result = AlwaysFalse;
11935 break;
11936 case BO_NE: // e.g. array1 != array2
11937 Result = AlwaysTrue;
11938 break;
11939 default: // e.g. array1 <= array2
11940 // The best we can say is 'a constant'
11941 Result = AlwaysConstant;
11942 break;
11943 }
11944 S.DiagRuntimeBehavior(Loc, nullptr,
11945 S.PDiag(diag::warn_comparison_always)
11946 << 1 /*array comparison*/
11947 << Result);
11948 } else if (std::optional<bool> Res =
11949 isTautologicalBoundsCheck(S, LHS, RHS, Opc)) {
11950 S.DiagRuntimeBehavior(Loc, nullptr,
11951 S.PDiag(diag::warn_comparison_always)
11952 << 2 /*pointer comparison*/
11953 << (*Res ? AlwaysTrue : AlwaysFalse));
11954 }
11955 }
11956
11957 if (isa<CastExpr>(LHSStripped))
11958 LHSStripped = LHSStripped->IgnoreParenCasts();
11959 if (isa<CastExpr>(RHSStripped))
11960 RHSStripped = RHSStripped->IgnoreParenCasts();
11961
11962 // Warn about comparisons against a string constant (unless the other
11963 // operand is null); the user probably wants string comparison function.
11964 Expr *LiteralString = nullptr;
11965 Expr *LiteralStringStripped = nullptr;
11966 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
11967 !RHSStripped->isNullPointerConstant(S.Context,
11969 LiteralString = LHS;
11970 LiteralStringStripped = LHSStripped;
11971 } else if ((isa<StringLiteral>(RHSStripped) ||
11972 isa<ObjCEncodeExpr>(RHSStripped)) &&
11973 !LHSStripped->isNullPointerConstant(S.Context,
11975 LiteralString = RHS;
11976 LiteralStringStripped = RHSStripped;
11977 }
11978
11979 if (LiteralString) {
11980 S.DiagRuntimeBehavior(Loc, nullptr,
11981 S.PDiag(diag::warn_stringcompare)
11982 << isa<ObjCEncodeExpr>(LiteralStringStripped)
11983 << LiteralString->getSourceRange());
11984 }
11985}
11986
11988 switch (CK) {
11989 default: {
11990#ifndef NDEBUG
11991 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
11992 << "\n";
11993#endif
11994 llvm_unreachable("unhandled cast kind");
11995 }
11996 case CK_UserDefinedConversion:
11997 return ICK_Identity;
11998 case CK_LValueToRValue:
11999 return ICK_Lvalue_To_Rvalue;
12000 case CK_ArrayToPointerDecay:
12001 return ICK_Array_To_Pointer;
12002 case CK_FunctionToPointerDecay:
12004 case CK_IntegralCast:
12006 case CK_FloatingCast:
12008 case CK_IntegralToFloating:
12009 case CK_FloatingToIntegral:
12010 return ICK_Floating_Integral;
12011 case CK_IntegralComplexCast:
12012 case CK_FloatingComplexCast:
12013 case CK_FloatingComplexToIntegralComplex:
12014 case CK_IntegralComplexToFloatingComplex:
12016 case CK_FloatingComplexToReal:
12017 case CK_FloatingRealToComplex:
12018 case CK_IntegralComplexToReal:
12019 case CK_IntegralRealToComplex:
12020 return ICK_Complex_Real;
12021 case CK_HLSLArrayRValue:
12022 return ICK_HLSL_Array_RValue;
12023 }
12024}
12025
12027 QualType FromType,
12029 // Check for a narrowing implicit conversion.
12032 SCS.setToType(0, FromType);
12033 SCS.setToType(1, ToType);
12034 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12035 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12036
12037 APValue PreNarrowingValue;
12038 QualType PreNarrowingType;
12039 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12040 PreNarrowingType,
12041 /*IgnoreFloatToIntegralConversion*/ true)) {
12043 // Implicit conversion to a narrower type, but the expression is
12044 // value-dependent so we can't tell whether it's actually narrowing.
12045 case NK_Not_Narrowing:
12046 return false;
12047
12049 // Implicit conversion to a narrower type, and the value is not a constant
12050 // expression.
12051 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12052 << /*Constant*/ 1
12053 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12054 return true;
12055
12057 // Implicit conversion to a narrower type, and the value is not a constant
12058 // expression.
12059 case NK_Type_Narrowing:
12060 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12061 << /*Constant*/ 0 << FromType << ToType;
12062 // TODO: It's not a constant expression, but what if the user intended it
12063 // to be? Can we produce notes to help them figure out why it isn't?
12064 return true;
12065 }
12066 llvm_unreachable("unhandled case in switch");
12067}
12068
12070 ExprResult &LHS,
12071 ExprResult &RHS,
12073 QualType LHSType = LHS.get()->getType();
12074 QualType RHSType = RHS.get()->getType();
12075 // Dig out the original argument type and expression before implicit casts
12076 // were applied. These are the types/expressions we need to check the
12077 // [expr.spaceship] requirements against.
12078 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12079 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12080 QualType LHSStrippedType = LHSStripped.get()->getType();
12081 QualType RHSStrippedType = RHSStripped.get()->getType();
12082
12083 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12084 // other is not, the program is ill-formed.
12085 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12086 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12087 return QualType();
12088 }
12089
12090 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12091 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12092 RHSStrippedType->isEnumeralType();
12093 if (NumEnumArgs == 1) {
12094 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12095 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12096 if (OtherTy->hasFloatingRepresentation()) {
12097 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12098 return QualType();
12099 }
12100 }
12101 if (NumEnumArgs == 2) {
12102 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12103 // type E, the operator yields the result of converting the operands
12104 // to the underlying type of E and applying <=> to the converted operands.
12105 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12106 S.InvalidOperands(Loc, LHS, RHS);
12107 return QualType();
12108 }
12109 QualType IntType =
12110 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12111 assert(IntType->isArithmeticType());
12112
12113 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12114 // promote the boolean type, and all other promotable integer types, to
12115 // avoid this.
12116 if (S.Context.isPromotableIntegerType(IntType))
12117 IntType = S.Context.getPromotedIntegerType(IntType);
12118
12119 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12120 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12121 LHSType = RHSType = IntType;
12122 }
12123
12124 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12125 // usual arithmetic conversions are applied to the operands.
12126 QualType Type =
12128 if (LHS.isInvalid() || RHS.isInvalid())
12129 return QualType();
12130 if (Type.isNull())
12131 return S.InvalidOperands(Loc, LHS, RHS);
12132
12133 std::optional<ComparisonCategoryType> CCT =
12135 if (!CCT)
12136 return S.InvalidOperands(Loc, LHS, RHS);
12137
12138 bool HasNarrowing = checkThreeWayNarrowingConversion(
12139 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12140 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12141 RHS.get()->getBeginLoc());
12142 if (HasNarrowing)
12143 return QualType();
12144
12145 assert(!Type.isNull() && "composite type for <=> has not been set");
12146
12149}
12150
12152 ExprResult &RHS,
12154 BinaryOperatorKind Opc) {
12155 if (Opc == BO_Cmp)
12156 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12157
12158 // C99 6.5.8p3 / C99 6.5.9p4
12159 QualType Type =
12161 if (LHS.isInvalid() || RHS.isInvalid())
12162 return QualType();
12163 if (Type.isNull())
12164 return S.InvalidOperands(Loc, LHS, RHS);
12165 assert(Type->isArithmeticType() || Type->isEnumeralType());
12166
12168 return S.InvalidOperands(Loc, LHS, RHS);
12169
12170 // Check for comparisons of floating point operands using != and ==.
12172 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12173
12174 // The result of comparisons is 'bool' in C++, 'int' in C.
12176}
12177
12179 if (!NullE.get()->getType()->isAnyPointerType())
12180 return;
12181 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12182 if (!E.get()->getType()->isAnyPointerType() &&
12186 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12187 if (CL->getValue() == 0)
12188 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12189 << NullValue
12191 NullValue ? "NULL" : "(void *)0");
12192 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12193 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12195 if (T == Context.CharTy)
12196 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12197 << NullValue
12199 NullValue ? "NULL" : "(void *)0");
12200 }
12201 }
12202}
12203
12204// C99 6.5.8, C++ [expr.rel]
12207 BinaryOperatorKind Opc) {
12208 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12209 bool IsThreeWay = Opc == BO_Cmp;
12210 bool IsOrdered = IsRelational || IsThreeWay;
12211 auto IsAnyPointerType = [](ExprResult E) {
12212 QualType Ty = E.get()->getType();
12213 return Ty->isPointerType() || Ty->isMemberPointerType();
12214 };
12215
12216 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12217 // type, array-to-pointer, ..., conversions are performed on both operands to
12218 // bring them to their composite type.
12219 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12220 // any type-related checks.
12221 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12223 if (LHS.isInvalid())
12224 return QualType();
12226 if (RHS.isInvalid())
12227 return QualType();
12228 } else {
12229 LHS = DefaultLvalueConversion(LHS.get());
12230 if (LHS.isInvalid())
12231 return QualType();
12232 RHS = DefaultLvalueConversion(RHS.get());
12233 if (RHS.isInvalid())
12234 return QualType();
12235 }
12236
12237 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12241 }
12242
12243 // Handle vector comparisons separately.
12244 if (LHS.get()->getType()->isVectorType() ||
12245 RHS.get()->getType()->isVectorType())
12246 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12247
12248 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12249 RHS.get()->getType()->isSveVLSBuiltinType())
12250 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12251
12252 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12253 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12254
12255 QualType LHSType = LHS.get()->getType();
12256 QualType RHSType = RHS.get()->getType();
12257 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12258 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12259 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12260
12261 if ((LHSType->isPointerType() &&
12263 (RHSType->isPointerType() &&
12265 return InvalidOperands(Loc, LHS, RHS);
12266
12267 const Expr::NullPointerConstantKind LHSNullKind =
12269 const Expr::NullPointerConstantKind RHSNullKind =
12271 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12272 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12273
12274 auto computeResultTy = [&]() {
12275 if (Opc != BO_Cmp)
12277 assert(getLangOpts().CPlusPlus);
12278 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12279
12280 QualType CompositeTy = LHS.get()->getType();
12281 assert(!CompositeTy->isReferenceType());
12282
12283 std::optional<ComparisonCategoryType> CCT =
12285 if (!CCT)
12286 return InvalidOperands(Loc, LHS, RHS);
12287
12288 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12289 // P0946R0: Comparisons between a null pointer constant and an object
12290 // pointer result in std::strong_equality, which is ill-formed under
12291 // P1959R0.
12292 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12293 << (LHSIsNull ? LHS.get()->getSourceRange()
12294 : RHS.get()->getSourceRange());
12295 return QualType();
12296 }
12297
12300 };
12301
12302 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12303 bool IsEquality = Opc == BO_EQ;
12304 if (RHSIsNull)
12305 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12306 RHS.get()->getSourceRange());
12307 else
12308 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12309 LHS.get()->getSourceRange());
12310 }
12311
12312 if (IsOrdered && LHSType->isFunctionPointerType() &&
12313 RHSType->isFunctionPointerType()) {
12314 // Valid unless a relational comparison of function pointers
12315 bool IsError = Opc == BO_Cmp;
12316 auto DiagID =
12317 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12318 : getLangOpts().CPlusPlus
12319 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12320 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12321 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12322 << RHS.get()->getSourceRange();
12323 if (IsError)
12324 return QualType();
12325 }
12326
12327 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12328 (RHSType->isIntegerType() && !RHSIsNull)) {
12329 // Skip normal pointer conversion checks in this case; we have better
12330 // diagnostics for this below.
12331 } else if (getLangOpts().CPlusPlus) {
12332 // Equality comparison of a function pointer to a void pointer is invalid,
12333 // but we allow it as an extension.
12334 // FIXME: If we really want to allow this, should it be part of composite
12335 // pointer type computation so it works in conditionals too?
12336 if (!IsOrdered &&
12337 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12338 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12339 // This is a gcc extension compatibility comparison.
12340 // In a SFINAE context, we treat this as a hard error to maintain
12341 // conformance with the C++ standard.
12343 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12344
12345 if (isSFINAEContext())
12346 return QualType();
12347
12348 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12349 return computeResultTy();
12350 }
12351
12352 // C++ [expr.eq]p2:
12353 // If at least one operand is a pointer [...] bring them to their
12354 // composite pointer type.
12355 // C++ [expr.spaceship]p6
12356 // If at least one of the operands is of pointer type, [...] bring them
12357 // to their composite pointer type.
12358 // C++ [expr.rel]p2:
12359 // If both operands are pointers, [...] bring them to their composite
12360 // pointer type.
12361 // For <=>, the only valid non-pointer types are arrays and functions, and
12362 // we already decayed those, so this is really the same as the relational
12363 // comparison rule.
12364 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12365 (IsOrdered ? 2 : 1) &&
12366 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12367 RHSType->isObjCObjectPointerType()))) {
12368 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12369 return QualType();
12370 return computeResultTy();
12371 }
12372 } else if (LHSType->isPointerType() &&
12373 RHSType->isPointerType()) { // C99 6.5.8p2
12374 // All of the following pointer-related warnings are GCC extensions, except
12375 // when handling null pointer constants.
12376 QualType LCanPointeeTy =
12378 QualType RCanPointeeTy =
12380
12381 // C99 6.5.9p2 and C99 6.5.8p2
12382 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12383 RCanPointeeTy.getUnqualifiedType())) {
12384 if (IsRelational) {
12385 // Pointers both need to point to complete or incomplete types
12386 if ((LCanPointeeTy->isIncompleteType() !=
12387 RCanPointeeTy->isIncompleteType()) &&
12388 !getLangOpts().C11) {
12389 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12390 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12391 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12392 << RCanPointeeTy->isIncompleteType();
12393 }
12394 }
12395 } else if (!IsRelational &&
12396 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12397 // Valid unless comparison between non-null pointer and function pointer
12398 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12399 && !LHSIsNull && !RHSIsNull)
12401 /*isError*/false);
12402 } else {
12403 // Invalid
12404 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12405 }
12406 if (LCanPointeeTy != RCanPointeeTy) {
12407 // Treat NULL constant as a special case in OpenCL.
12408 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12409 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy,
12410 getASTContext())) {
12411 Diag(Loc,
12412 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12413 << LHSType << RHSType << 0 /* comparison */
12414 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12415 }
12416 }
12417 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12418 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12419 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12420 : CK_BitCast;
12421 if (LHSIsNull && !RHSIsNull)
12422 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12423 else
12424 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12425 }
12426 return computeResultTy();
12427 }
12428
12429
12430 // C++ [expr.eq]p4:
12431 // Two operands of type std::nullptr_t or one operand of type
12432 // std::nullptr_t and the other a null pointer constant compare
12433 // equal.
12434 // C23 6.5.9p5:
12435 // If both operands have type nullptr_t or one operand has type nullptr_t
12436 // and the other is a null pointer constant, they compare equal if the
12437 // former is a null pointer.
12438 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12439 if (LHSType->isNullPtrType()) {
12440 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12441 return computeResultTy();
12442 }
12443 if (RHSType->isNullPtrType()) {
12444 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12445 return computeResultTy();
12446 }
12447 }
12448
12449 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12450 // C23 6.5.9p6:
12451 // Otherwise, at least one operand is a pointer. If one is a pointer and
12452 // the other is a null pointer constant or has type nullptr_t, they
12453 // compare equal
12454 if (LHSIsNull && RHSType->isPointerType()) {
12455 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12456 return computeResultTy();
12457 }
12458 if (RHSIsNull && LHSType->isPointerType()) {
12459 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12460 return computeResultTy();
12461 }
12462 }
12463
12464 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12465 // These aren't covered by the composite pointer type rules.
12466 if (!IsOrdered && RHSType->isNullPtrType() &&
12467 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12468 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12469 return computeResultTy();
12470 }
12471 if (!IsOrdered && LHSType->isNullPtrType() &&
12472 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12473 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12474 return computeResultTy();
12475 }
12476
12477 if (getLangOpts().CPlusPlus) {
12478 if (IsRelational &&
12479 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12480 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12481 // HACK: Relational comparison of nullptr_t against a pointer type is
12482 // invalid per DR583, but we allow it within std::less<> and friends,
12483 // since otherwise common uses of it break.
12484 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12485 // friends to have std::nullptr_t overload candidates.
12486 DeclContext *DC = CurContext;
12487 if (isa<FunctionDecl>(DC))
12488 DC = DC->getParent();
12489 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12490 if (CTSD->isInStdNamespace() &&
12491 llvm::StringSwitch<bool>(CTSD->getName())
12492 .Cases("less", "less_equal", "greater", "greater_equal", true)
12493 .Default(false)) {
12494 if (RHSType->isNullPtrType())
12495 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12496 else
12497 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12498 return computeResultTy();
12499 }
12500 }
12501 }
12502
12503 // C++ [expr.eq]p2:
12504 // If at least one operand is a pointer to member, [...] bring them to
12505 // their composite pointer type.
12506 if (!IsOrdered &&
12507 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12508 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12509 return QualType();
12510 else
12511 return computeResultTy();
12512 }
12513 }
12514
12515 // Handle block pointer types.
12516 if (!IsOrdered && LHSType->isBlockPointerType() &&
12517 RHSType->isBlockPointerType()) {
12518 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12519 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12520
12521 if (!LHSIsNull && !RHSIsNull &&
12522 !Context.typesAreCompatible(lpointee, rpointee)) {
12523 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12524 << LHSType << RHSType << LHS.get()->getSourceRange()
12525 << RHS.get()->getSourceRange();
12526 }
12527 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12528 return computeResultTy();
12529 }
12530
12531 // Allow block pointers to be compared with null pointer constants.
12532 if (!IsOrdered
12533 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12534 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12535 if (!LHSIsNull && !RHSIsNull) {
12536 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12538 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12539 ->getPointeeType()->isVoidType())))
12540 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12541 << LHSType << RHSType << LHS.get()->getSourceRange()
12542 << RHS.get()->getSourceRange();
12543 }
12544 if (LHSIsNull && !RHSIsNull)
12545 LHS = ImpCastExprToType(LHS.get(), RHSType,
12546 RHSType->isPointerType() ? CK_BitCast
12547 : CK_AnyPointerToBlockPointerCast);
12548 else
12549 RHS = ImpCastExprToType(RHS.get(), LHSType,
12550 LHSType->isPointerType() ? CK_BitCast
12551 : CK_AnyPointerToBlockPointerCast);
12552 return computeResultTy();
12553 }
12554
12555 if (LHSType->isObjCObjectPointerType() ||
12556 RHSType->isObjCObjectPointerType()) {
12557 const PointerType *LPT = LHSType->getAs<PointerType>();
12558 const PointerType *RPT = RHSType->getAs<PointerType>();
12559 if (LPT || RPT) {
12560 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12561 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12562
12563 if (!LPtrToVoid && !RPtrToVoid &&
12564 !Context.typesAreCompatible(LHSType, RHSType)) {
12565 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12566 /*isError*/false);
12567 }
12568 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12569 // the RHS, but we have test coverage for this behavior.
12570 // FIXME: Consider using convertPointersToCompositeType in C++.
12571 if (LHSIsNull && !RHSIsNull) {
12572 Expr *E = LHS.get();
12573 if (getLangOpts().ObjCAutoRefCount)
12574 ObjC().CheckObjCConversion(SourceRange(), RHSType, E,
12576 LHS = ImpCastExprToType(E, RHSType,
12577 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12578 }
12579 else {
12580 Expr *E = RHS.get();
12581 if (getLangOpts().ObjCAutoRefCount)
12582 ObjC().CheckObjCConversion(SourceRange(), LHSType, E,
12584 /*Diagnose=*/true,
12585 /*DiagnoseCFAudited=*/false, Opc);
12586 RHS = ImpCastExprToType(E, LHSType,
12587 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12588 }
12589 return computeResultTy();
12590 }
12591 if (LHSType->isObjCObjectPointerType() &&
12592 RHSType->isObjCObjectPointerType()) {
12593 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12594 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12595 /*isError*/false);
12597 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12598
12599 if (LHSIsNull && !RHSIsNull)
12600 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12601 else
12602 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12603 return computeResultTy();
12604 }
12605
12606 if (!IsOrdered && LHSType->isBlockPointerType() &&
12608 LHS = ImpCastExprToType(LHS.get(), RHSType,
12609 CK_BlockPointerToObjCPointerCast);
12610 return computeResultTy();
12611 } else if (!IsOrdered &&
12613 RHSType->isBlockPointerType()) {
12614 RHS = ImpCastExprToType(RHS.get(), LHSType,
12615 CK_BlockPointerToObjCPointerCast);
12616 return computeResultTy();
12617 }
12618 }
12619 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12620 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12621 unsigned DiagID = 0;
12622 bool isError = false;
12623 if (LangOpts.DebuggerSupport) {
12624 // Under a debugger, allow the comparison of pointers to integers,
12625 // since users tend to want to compare addresses.
12626 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12627 (RHSIsNull && RHSType->isIntegerType())) {
12628 if (IsOrdered) {
12629 isError = getLangOpts().CPlusPlus;
12630 DiagID =
12631 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12632 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12633 }
12634 } else if (getLangOpts().CPlusPlus) {
12635 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12636 isError = true;
12637 } else if (IsOrdered)
12638 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12639 else
12640 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12641
12642 if (DiagID) {
12643 Diag(Loc, DiagID)
12644 << LHSType << RHSType << LHS.get()->getSourceRange()
12645 << RHS.get()->getSourceRange();
12646 if (isError)
12647 return QualType();
12648 }
12649
12650 if (LHSType->isIntegerType())
12651 LHS = ImpCastExprToType(LHS.get(), RHSType,
12652 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12653 else
12654 RHS = ImpCastExprToType(RHS.get(), LHSType,
12655 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12656 return computeResultTy();
12657 }
12658
12659 // Handle block pointers.
12660 if (!IsOrdered && RHSIsNull
12661 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12662 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12663 return computeResultTy();
12664 }
12665 if (!IsOrdered && LHSIsNull
12666 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12667 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12668 return computeResultTy();
12669 }
12670
12671 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12672 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12673 return computeResultTy();
12674 }
12675
12676 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12677 return computeResultTy();
12678 }
12679
12680 if (LHSIsNull && RHSType->isQueueT()) {
12681 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12682 return computeResultTy();
12683 }
12684
12685 if (LHSType->isQueueT() && RHSIsNull) {
12686 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12687 return computeResultTy();
12688 }
12689 }
12690
12691 return InvalidOperands(Loc, LHS, RHS);
12692}
12693
12695 const VectorType *VTy = V->castAs<VectorType>();
12696 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
12697
12698 if (isa<ExtVectorType>(VTy)) {
12699 if (VTy->isExtVectorBoolType())
12701 if (TypeSize == Context.getTypeSize(Context.CharTy))
12703 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12705 if (TypeSize == Context.getTypeSize(Context.IntTy))
12707 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12709 if (TypeSize == Context.getTypeSize(Context.LongTy))
12711 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
12712 "Unhandled vector element size in vector compare");
12714 }
12715
12716 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
12719 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
12722 if (TypeSize == Context.getTypeSize(Context.LongTy))
12725 if (TypeSize == Context.getTypeSize(Context.IntTy))
12728 if (TypeSize == Context.getTypeSize(Context.ShortTy))
12731 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
12732 "Unhandled vector element size in vector compare");
12735}
12736
12738 const BuiltinType *VTy = V->castAs<BuiltinType>();
12739 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
12740
12741 const QualType ETy = V->getSveEltType(Context);
12742 const auto TypeSize = Context.getTypeSize(ETy);
12743
12744 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
12745 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
12746 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
12747}
12748
12751 BinaryOperatorKind Opc) {
12752 if (Opc == BO_Cmp) {
12753 Diag(Loc, diag::err_three_way_vector_comparison);
12754 return QualType();
12755 }
12756
12757 // Check to make sure we're operating on vectors of the same type and width,
12758 // Allowing one side to be a scalar of element type.
12759 QualType vType =
12760 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
12761 /*AllowBothBool*/ true,
12762 /*AllowBoolConversions*/ getLangOpts().ZVector,
12763 /*AllowBooleanOperation*/ true,
12764 /*ReportInvalid*/ true);
12765 if (vType.isNull())
12766 return vType;
12767
12768 QualType LHSType = LHS.get()->getType();
12769
12770 // Determine the return type of a vector compare. By default clang will return
12771 // a scalar for all vector compares except vector bool and vector pixel.
12772 // With the gcc compiler we will always return a vector type and with the xl
12773 // compiler we will always return a scalar type. This switch allows choosing
12774 // which behavior is prefered.
12775 if (getLangOpts().AltiVec) {
12776 switch (getLangOpts().getAltivecSrcCompat()) {
12778 // If AltiVec, the comparison results in a numeric type, i.e.
12779 // bool for C++, int for C
12780 if (vType->castAs<VectorType>()->getVectorKind() ==
12783 else
12784 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
12785 break;
12787 // For GCC we always return the vector type.
12788 break;
12791 break;
12792 }
12793 }
12794
12795 // For non-floating point types, check for self-comparisons of the form
12796 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12797 // often indicate logic errors in the program.
12798 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12799
12800 // Check for comparisons of floating point operands using != and ==.
12801 if (LHSType->hasFloatingRepresentation()) {
12802 assert(RHS.get()->getType()->hasFloatingRepresentation());
12803 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12804 }
12805
12806 // Return a signed type for the vector.
12807 return GetSignedVectorType(vType);
12808}
12809
12811 ExprResult &RHS,
12813 BinaryOperatorKind Opc) {
12814 if (Opc == BO_Cmp) {
12815 Diag(Loc, diag::err_three_way_vector_comparison);
12816 return QualType();
12817 }
12818
12819 // Check to make sure we're operating on vectors of the same type and width,
12820 // Allowing one side to be a scalar of element type.
12822 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
12823
12824 if (vType.isNull())
12825 return vType;
12826
12827 QualType LHSType = LHS.get()->getType();
12828
12829 // For non-floating point types, check for self-comparisons of the form
12830 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12831 // often indicate logic errors in the program.
12832 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12833
12834 // Check for comparisons of floating point operands using != and ==.
12835 if (LHSType->hasFloatingRepresentation()) {
12836 assert(RHS.get()->getType()->hasFloatingRepresentation());
12837 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12838 }
12839
12840 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
12841 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
12842
12843 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
12844 RHSBuiltinTy->isSVEBool())
12845 return LHSType;
12846
12847 // Return a signed type for the vector.
12848 return GetSignedSizelessVectorType(vType);
12849}
12850
12851static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
12852 const ExprResult &XorRHS,
12853 const SourceLocation Loc) {
12854 // Do not diagnose macros.
12855 if (Loc.isMacroID())
12856 return;
12857
12858 // Do not diagnose if both LHS and RHS are macros.
12859 if (XorLHS.get()->getExprLoc().isMacroID() &&
12860 XorRHS.get()->getExprLoc().isMacroID())
12861 return;
12862
12863 bool Negative = false;
12864 bool ExplicitPlus = false;
12865 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
12866 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
12867
12868 if (!LHSInt)
12869 return;
12870 if (!RHSInt) {
12871 // Check negative literals.
12872 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
12873 UnaryOperatorKind Opc = UO->getOpcode();
12874 if (Opc != UO_Minus && Opc != UO_Plus)
12875 return;
12876 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
12877 if (!RHSInt)
12878 return;
12879 Negative = (Opc == UO_Minus);
12880 ExplicitPlus = !Negative;
12881 } else {
12882 return;
12883 }
12884 }
12885
12886 const llvm::APInt &LeftSideValue = LHSInt->getValue();
12887 llvm::APInt RightSideValue = RHSInt->getValue();
12888 if (LeftSideValue != 2 && LeftSideValue != 10)
12889 return;
12890
12891 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
12892 return;
12893
12895 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
12896 llvm::StringRef ExprStr =
12898
12899 CharSourceRange XorRange =
12901 llvm::StringRef XorStr =
12903 // Do not diagnose if xor keyword/macro is used.
12904 if (XorStr == "xor")
12905 return;
12906
12907 std::string LHSStr = std::string(Lexer::getSourceText(
12908 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
12909 S.getSourceManager(), S.getLangOpts()));
12910 std::string RHSStr = std::string(Lexer::getSourceText(
12911 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
12912 S.getSourceManager(), S.getLangOpts()));
12913
12914 if (Negative) {
12915 RightSideValue = -RightSideValue;
12916 RHSStr = "-" + RHSStr;
12917 } else if (ExplicitPlus) {
12918 RHSStr = "+" + RHSStr;
12919 }
12920
12921 StringRef LHSStrRef = LHSStr;
12922 StringRef RHSStrRef = RHSStr;
12923 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
12924 // literals.
12925 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
12926 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
12927 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
12928 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
12929 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
12930 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
12931 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
12932 return;
12933
12934 bool SuggestXor =
12935 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
12936 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
12937 int64_t RightSideIntValue = RightSideValue.getSExtValue();
12938 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
12939 std::string SuggestedExpr = "1 << " + RHSStr;
12940 bool Overflow = false;
12941 llvm::APInt One = (LeftSideValue - 1);
12942 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
12943 if (Overflow) {
12944 if (RightSideIntValue < 64)
12945 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12946 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
12947 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
12948 else if (RightSideIntValue == 64)
12949 S.Diag(Loc, diag::warn_xor_used_as_pow)
12950 << ExprStr << toString(XorValue, 10, true);
12951 else
12952 return;
12953 } else {
12954 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
12955 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
12956 << toString(PowValue, 10, true)
12958 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
12959 }
12960
12961 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12962 << ("0x2 ^ " + RHSStr) << SuggestXor;
12963 } else if (LeftSideValue == 10) {
12964 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
12965 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
12966 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
12967 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
12968 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
12969 << ("0xA ^ " + RHSStr) << SuggestXor;
12970 }
12971}
12972
12975 BinaryOperatorKind Opc) {
12976 // Ensure that either both operands are of the same vector type, or
12977 // one operand is of a vector type and the other is of its element type.
12978 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
12979 /*AllowBothBool*/ true,
12980 /*AllowBoolConversions*/ false,
12981 /*AllowBooleanOperation*/ false,
12982 /*ReportInvalid*/ false);
12983 if (vType.isNull())
12984 return InvalidOperands(Loc, LHS, RHS);
12985 if (getLangOpts().OpenCL &&
12986 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
12988 return InvalidOperands(Loc, LHS, RHS);
12989 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
12990 // usage of the logical operators && and || with vectors in C. This
12991 // check could be notionally dropped.
12992 if (!getLangOpts().CPlusPlus &&
12993 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
12994 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
12995 // Beginning with HLSL 2021, HLSL disallows logical operators on vector
12996 // operands and instead requires the use of the `and`, `or`, `any`, `all`, and
12997 // `select` functions.
12998 if (getLangOpts().HLSL &&
12999 getLangOpts().getHLSLVersion() >= LangOptionsBase::HLSL_2021) {
13000 (void)InvalidOperands(Loc, LHS, RHS);
13001 HLSL().emitLogicalOperatorFixIt(LHS.get(), RHS.get(), Opc);
13002 return QualType();
13003 }
13004
13005 return GetSignedVectorType(LHS.get()->getType());
13006}
13007
13010 bool IsCompAssign) {
13011 if (!IsCompAssign) {
13013 if (LHS.isInvalid())
13014 return QualType();
13015 }
13017 if (RHS.isInvalid())
13018 return QualType();
13019
13020 // For conversion purposes, we ignore any qualifiers.
13021 // For example, "const float" and "float" are equivalent.
13022 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13023 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13024
13025 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13026 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13027 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13028
13029 if (Context.hasSameType(LHSType, RHSType))
13030 return Context.getCommonSugaredType(LHSType, RHSType);
13031
13032 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13033 // case we have to return InvalidOperands.
13034 ExprResult OriginalLHS = LHS;
13035 ExprResult OriginalRHS = RHS;
13036 if (LHSMatType && !RHSMatType) {
13037 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13038 if (!RHS.isInvalid())
13039 return LHSType;
13040
13041 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13042 }
13043
13044 if (!LHSMatType && RHSMatType) {
13045 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13046 if (!LHS.isInvalid())
13047 return RHSType;
13048 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13049 }
13050
13051 return InvalidOperands(Loc, LHS, RHS);
13052}
13053
13056 bool IsCompAssign) {
13057 if (!IsCompAssign) {
13059 if (LHS.isInvalid())
13060 return QualType();
13061 }
13063 if (RHS.isInvalid())
13064 return QualType();
13065
13066 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13067 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13068 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13069
13070 if (LHSMatType && RHSMatType) {
13071 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13072 return InvalidOperands(Loc, LHS, RHS);
13073
13074 if (Context.hasSameType(LHSMatType, RHSMatType))
13076 LHS.get()->getType().getUnqualifiedType(),
13077 RHS.get()->getType().getUnqualifiedType());
13078
13079 QualType LHSELTy = LHSMatType->getElementType(),
13080 RHSELTy = RHSMatType->getElementType();
13081 if (!Context.hasSameType(LHSELTy, RHSELTy))
13082 return InvalidOperands(Loc, LHS, RHS);
13083
13085 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13086 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13087 }
13088 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13089}
13090
13092 switch (Opc) {
13093 default:
13094 return false;
13095 case BO_And:
13096 case BO_AndAssign:
13097 case BO_Or:
13098 case BO_OrAssign:
13099 case BO_Xor:
13100 case BO_XorAssign:
13101 return true;
13102 }
13103}
13104
13107 BinaryOperatorKind Opc) {
13108 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13109
13110 bool IsCompAssign =
13111 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13112
13113 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13114
13115 if (LHS.get()->getType()->isVectorType() ||
13116 RHS.get()->getType()->isVectorType()) {
13117 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13119 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13120 /*AllowBothBool*/ true,
13121 /*AllowBoolConversions*/ getLangOpts().ZVector,
13122 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13123 /*ReportInvalid*/ true);
13124 return InvalidOperands(Loc, LHS, RHS);
13125 }
13126
13127 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13128 RHS.get()->getType()->isSveVLSBuiltinType()) {
13129 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13131 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13133 return InvalidOperands(Loc, LHS, RHS);
13134 }
13135
13136 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13137 RHS.get()->getType()->isSveVLSBuiltinType()) {
13138 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13140 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13142 return InvalidOperands(Loc, LHS, RHS);
13143 }
13144
13145 if (Opc == BO_And)
13146 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13147
13148 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13150 return InvalidOperands(Loc, LHS, RHS);
13151
13152 ExprResult LHSResult = LHS, RHSResult = RHS;
13154 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13155 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13156 return QualType();
13157 LHS = LHSResult.get();
13158 RHS = RHSResult.get();
13159
13160 if (Opc == BO_Xor)
13161 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13162
13163 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13164 return compType;
13165 return InvalidOperands(Loc, LHS, RHS);
13166}
13167
13168// C99 6.5.[13,14]
13171 BinaryOperatorKind Opc) {
13172 // Check vector operands differently.
13173 if (LHS.get()->getType()->isVectorType() ||
13174 RHS.get()->getType()->isVectorType())
13175 return CheckVectorLogicalOperands(LHS, RHS, Loc, Opc);
13176
13177 bool EnumConstantInBoolContext = false;
13178 for (const ExprResult &HS : {LHS, RHS}) {
13179 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13180 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13181 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13182 EnumConstantInBoolContext = true;
13183 }
13184 }
13185
13186 if (EnumConstantInBoolContext)
13187 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13188
13189 // WebAssembly tables can't be used with logical operators.
13190 QualType LHSTy = LHS.get()->getType();
13191 QualType RHSTy = RHS.get()->getType();
13192 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13193 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13194 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13195 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13196 return InvalidOperands(Loc, LHS, RHS);
13197 }
13198
13199 // Diagnose cases where the user write a logical and/or but probably meant a
13200 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13201 // is a constant.
13202 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13203 !LHS.get()->getType()->isBooleanType() &&
13204 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13205 // Don't warn in macros or template instantiations.
13207 // If the RHS can be constant folded, and if it constant folds to something
13208 // that isn't 0 or 1 (which indicate a potential logical operation that
13209 // happened to fold to true/false) then warn.
13210 // Parens on the RHS are ignored.
13211 Expr::EvalResult EVResult;
13212 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13213 llvm::APSInt Result = EVResult.Val.getInt();
13214 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13215 !RHS.get()->getExprLoc().isMacroID()) ||
13216 (Result != 0 && Result != 1)) {
13217 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13218 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13219 // Suggest replacing the logical operator with the bitwise version
13220 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13221 << (Opc == BO_LAnd ? "&" : "|")
13224 Opc == BO_LAnd ? "&" : "|");
13225 if (Opc == BO_LAnd)
13226 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13227 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13230 RHS.get()->getEndLoc()));
13231 }
13232 }
13233 }
13234
13235 if (!Context.getLangOpts().CPlusPlus) {
13236 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13237 // not operate on the built-in scalar and vector float types.
13238 if (Context.getLangOpts().OpenCL &&
13239 Context.getLangOpts().OpenCLVersion < 120) {
13240 if (LHS.get()->getType()->isFloatingType() ||
13241 RHS.get()->getType()->isFloatingType())
13242 return InvalidOperands(Loc, LHS, RHS);
13243 }
13244
13245 LHS = UsualUnaryConversions(LHS.get());
13246 if (LHS.isInvalid())
13247 return QualType();
13248
13249 RHS = UsualUnaryConversions(RHS.get());
13250 if (RHS.isInvalid())
13251 return QualType();
13252
13253 if (!LHS.get()->getType()->isScalarType() ||
13254 !RHS.get()->getType()->isScalarType())
13255 return InvalidOperands(Loc, LHS, RHS);
13256
13257 return Context.IntTy;
13258 }
13259
13260 // The following is safe because we only use this method for
13261 // non-overloadable operands.
13262
13263 // C++ [expr.log.and]p1
13264 // C++ [expr.log.or]p1
13265 // The operands are both contextually converted to type bool.
13267 if (LHSRes.isInvalid())
13268 return InvalidOperands(Loc, LHS, RHS);
13269 LHS = LHSRes;
13270
13272 if (RHSRes.isInvalid())
13273 return InvalidOperands(Loc, LHS, RHS);
13274 RHS = RHSRes;
13275
13276 // C++ [expr.log.and]p2
13277 // C++ [expr.log.or]p2
13278 // The result is a bool.
13279 return Context.BoolTy;
13280}
13281
13282static bool IsReadonlyMessage(Expr *E, Sema &S) {
13283 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13284 if (!ME) return false;
13285 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13286 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13288 if (!Base) return false;
13289 return Base->getMethodDecl() != nullptr;
13290}
13291
13292/// Is the given expression (which must be 'const') a reference to a
13293/// variable which was originally non-const, but which has become
13294/// 'const' due to being captured within a block?
13297 assert(E->isLValue() && E->getType().isConstQualified());
13298 E = E->IgnoreParens();
13299
13300 // Must be a reference to a declaration from an enclosing scope.
13301 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13302 if (!DRE) return NCCK_None;
13304
13305 ValueDecl *Value = dyn_cast<ValueDecl>(DRE->getDecl());
13306
13307 // The declaration must be a value which is not declared 'const'.
13308 if (!Value || Value->getType().isConstQualified())
13309 return NCCK_None;
13310
13311 BindingDecl *Binding = dyn_cast<BindingDecl>(Value);
13312 if (Binding) {
13313 assert(S.getLangOpts().CPlusPlus && "BindingDecl outside of C++?");
13314 assert(!isa<BlockDecl>(Binding->getDeclContext()));
13315 return NCCK_Lambda;
13316 }
13317
13318 VarDecl *Var = dyn_cast<VarDecl>(Value);
13319 if (!Var)
13320 return NCCK_None;
13321
13322 assert(Var->hasLocalStorage() && "capture added 'const' to non-local?");
13323
13324 // Decide whether the first capture was for a block or a lambda.
13325 DeclContext *DC = S.CurContext, *Prev = nullptr;
13326 // Decide whether the first capture was for a block or a lambda.
13327 while (DC) {
13328 // For init-capture, it is possible that the variable belongs to the
13329 // template pattern of the current context.
13330 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13331 if (Var->isInitCapture() &&
13332 FD->getTemplateInstantiationPattern() == Var->getDeclContext())
13333 break;
13334 if (DC == Var->getDeclContext())
13335 break;
13336 Prev = DC;
13337 DC = DC->getParent();
13338 }
13339 // Unless we have an init-capture, we've gone one step too far.
13340 if (!Var->isInitCapture())
13341 DC = Prev;
13342 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13343}
13344
13345static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13346 Ty = Ty.getNonReferenceType();
13347 if (IsDereference && Ty->isPointerType())
13348 Ty = Ty->getPointeeType();
13349 return !Ty.isConstQualified();
13350}
13351
13352// Update err_typecheck_assign_const and note_typecheck_assign_const
13353// when this enum is changed.
13354enum {
13360 ConstUnknown, // Keep as last element
13361};
13362
13363/// Emit the "read-only variable not assignable" error and print notes to give
13364/// more information about why the variable is not assignable, such as pointing
13365/// to the declaration of a const variable, showing that a method is const, or
13366/// that the function is returning a const reference.
13367static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13369 SourceRange ExprRange = E->getSourceRange();
13370
13371 // Only emit one error on the first const found. All other consts will emit
13372 // a note to the error.
13373 bool DiagnosticEmitted = false;
13374
13375 // Track if the current expression is the result of a dereference, and if the
13376 // next checked expression is the result of a dereference.
13377 bool IsDereference = false;
13378 bool NextIsDereference = false;
13379
13380 // Loop to process MemberExpr chains.
13381 while (true) {
13382 IsDereference = NextIsDereference;
13383
13385 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13386 NextIsDereference = ME->isArrow();
13387 const ValueDecl *VD = ME->getMemberDecl();
13388 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13389 // Mutable fields can be modified even if the class is const.
13390 if (Field->isMutable()) {
13391 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13392 break;
13393 }
13394
13395 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13396 if (!DiagnosticEmitted) {
13397 S.Diag(Loc, diag::err_typecheck_assign_const)
13398 << ExprRange << ConstMember << false /*static*/ << Field
13399 << Field->getType();
13400 DiagnosticEmitted = true;
13401 }
13402 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13403 << ConstMember << false /*static*/ << Field << Field->getType()
13404 << Field->getSourceRange();
13405 }
13406 E = ME->getBase();
13407 continue;
13408 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13409 if (VDecl->getType().isConstQualified()) {
13410 if (!DiagnosticEmitted) {
13411 S.Diag(Loc, diag::err_typecheck_assign_const)
13412 << ExprRange << ConstMember << true /*static*/ << VDecl
13413 << VDecl->getType();
13414 DiagnosticEmitted = true;
13415 }
13416 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13417 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13418 << VDecl->getSourceRange();
13419 }
13420 // Static fields do not inherit constness from parents.
13421 break;
13422 }
13423 break; // End MemberExpr
13424 } else if (const ArraySubscriptExpr *ASE =
13425 dyn_cast<ArraySubscriptExpr>(E)) {
13426 E = ASE->getBase()->IgnoreParenImpCasts();
13427 continue;
13428 } else if (const ExtVectorElementExpr *EVE =
13429 dyn_cast<ExtVectorElementExpr>(E)) {
13430 E = EVE->getBase()->IgnoreParenImpCasts();
13431 continue;
13432 }
13433 break;
13434 }
13435
13436 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13437 // Function calls
13438 const FunctionDecl *FD = CE->getDirectCallee();
13439 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13440 if (!DiagnosticEmitted) {
13441 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13442 << ConstFunction << FD;
13443 DiagnosticEmitted = true;
13444 }
13446 diag::note_typecheck_assign_const)
13447 << ConstFunction << FD << FD->getReturnType()
13448 << FD->getReturnTypeSourceRange();
13449 }
13450 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13451 // Point to variable declaration.
13452 if (const ValueDecl *VD = DRE->getDecl()) {
13453 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13454 if (!DiagnosticEmitted) {
13455 S.Diag(Loc, diag::err_typecheck_assign_const)
13456 << ExprRange << ConstVariable << VD << VD->getType();
13457 DiagnosticEmitted = true;
13458 }
13459 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13460 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13461 }
13462 }
13463 } else if (isa<CXXThisExpr>(E)) {
13464 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13465 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13466 if (MD->isConst()) {
13467 if (!DiagnosticEmitted) {
13468 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13469 << ConstMethod << MD;
13470 DiagnosticEmitted = true;
13471 }
13472 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13473 << ConstMethod << MD << MD->getSourceRange();
13474 }
13475 }
13476 }
13477 }
13478
13479 if (DiagnosticEmitted)
13480 return;
13481
13482 // Can't determine a more specific message, so display the generic error.
13483 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13484}
13485
13491
13493 const RecordType *Ty,
13495 OriginalExprKind OEK,
13496 bool &DiagnosticEmitted) {
13497 std::vector<const RecordType *> RecordTypeList;
13498 RecordTypeList.push_back(Ty);
13499 unsigned NextToCheckIndex = 0;
13500 // We walk the record hierarchy breadth-first to ensure that we print
13501 // diagnostics in field nesting order.
13502 while (RecordTypeList.size() > NextToCheckIndex) {
13503 bool IsNested = NextToCheckIndex > 0;
13504 for (const FieldDecl *Field :
13505 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13506 // First, check every field for constness.
13507 QualType FieldTy = Field->getType();
13508 if (FieldTy.isConstQualified()) {
13509 if (!DiagnosticEmitted) {
13510 S.Diag(Loc, diag::err_typecheck_assign_const)
13511 << Range << NestedConstMember << OEK << VD
13512 << IsNested << Field;
13513 DiagnosticEmitted = true;
13514 }
13515 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13516 << NestedConstMember << IsNested << Field
13517 << FieldTy << Field->getSourceRange();
13518 }
13519
13520 // Then we append it to the list to check next in order.
13521 FieldTy = FieldTy.getCanonicalType();
13522 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13523 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13524 RecordTypeList.push_back(FieldRecTy);
13525 }
13526 }
13527 ++NextToCheckIndex;
13528 }
13529}
13530
13531/// Emit an error for the case where a record we are trying to assign to has a
13532/// const-qualified field somewhere in its hierarchy.
13535 QualType Ty = E->getType();
13536 assert(Ty->isRecordType() && "lvalue was not record?");
13538 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13539 bool DiagEmitted = false;
13540
13541 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13542 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13543 Range, OEK_Member, DiagEmitted);
13544 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13545 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13546 Range, OEK_Variable, DiagEmitted);
13547 else
13548 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13549 Range, OEK_LValue, DiagEmitted);
13550 if (!DiagEmitted)
13552}
13553
13554/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13555/// emit an error and return true. If so, return false.
13557 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13558
13560
13561 SourceLocation OrigLoc = Loc;
13563 &Loc);
13564 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13566 if (IsLV == Expr::MLV_Valid)
13567 return false;
13568
13569 unsigned DiagID = 0;
13570 bool NeedType = false;
13571 switch (IsLV) { // C99 6.5.16p2
13573 // Use a specialized diagnostic when we're assigning to an object
13574 // from an enclosing function or block.
13576 if (NCCK == NCCK_Block)
13577 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13578 else
13579 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13580 break;
13581 }
13582
13583 // In ARC, use some specialized diagnostics for occasions where we
13584 // infer 'const'. These are always pseudo-strong variables.
13585 if (S.getLangOpts().ObjCAutoRefCount) {
13586 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13587 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13588 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13589
13590 // Use the normal diagnostic if it's pseudo-__strong but the
13591 // user actually wrote 'const'.
13592 if (var->isARCPseudoStrong() &&
13593 (!var->getTypeSourceInfo() ||
13594 !var->getTypeSourceInfo()->getType().isConstQualified())) {
13595 // There are three pseudo-strong cases:
13596 // - self
13597 ObjCMethodDecl *method = S.getCurMethodDecl();
13598 if (method && var == method->getSelfDecl()) {
13599 DiagID = method->isClassMethod()
13600 ? diag::err_typecheck_arc_assign_self_class_method
13601 : diag::err_typecheck_arc_assign_self;
13602
13603 // - Objective-C externally_retained attribute.
13604 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13605 isa<ParmVarDecl>(var)) {
13606 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13607
13608 // - fast enumeration variables
13609 } else {
13610 DiagID = diag::err_typecheck_arr_assign_enumeration;
13611 }
13612
13613 SourceRange Assign;
13614 if (Loc != OrigLoc)
13615 Assign = SourceRange(OrigLoc, OrigLoc);
13616 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13617 // We need to preserve the AST regardless, so migration tool
13618 // can do its job.
13619 return false;
13620 }
13621 }
13622 }
13623
13624 // If none of the special cases above are triggered, then this is a
13625 // simple const assignment.
13626 if (DiagID == 0) {
13628 return true;
13629 }
13630
13631 break;
13634 return true;
13637 return true;
13640 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13641 NeedType = true;
13642 break;
13644 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13645 NeedType = true;
13646 break;
13648 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13649 break;
13650 case Expr::MLV_Valid:
13651 llvm_unreachable("did not take early return for MLV_Valid");
13655 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13656 break;
13659 return S.RequireCompleteType(Loc, E->getType(),
13660 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13662 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13663 break;
13665 llvm_unreachable("readonly properties should be processed differently");
13667 DiagID = diag::err_readonly_message_assignment;
13668 break;
13670 DiagID = diag::err_no_subobject_property_setting;
13671 break;
13672 }
13673
13674 SourceRange Assign;
13675 if (Loc != OrigLoc)
13676 Assign = SourceRange(OrigLoc, OrigLoc);
13677 if (NeedType)
13678 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13679 else
13680 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13681 return true;
13682}
13683
13684static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13686 Sema &Sema) {
13688 return;
13690 return;
13691 if (Loc.isInvalid() || Loc.isMacroID())
13692 return;
13693 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13694 return;
13695
13696 // C / C++ fields
13697 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
13698 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
13699 if (ML && MR) {
13700 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
13701 return;
13702 const ValueDecl *LHSDecl =
13703 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
13704 const ValueDecl *RHSDecl =
13705 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
13706 if (LHSDecl != RHSDecl)
13707 return;
13708 if (LHSDecl->getType().isVolatileQualified())
13709 return;
13710 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
13711 if (RefTy->getPointeeType().isVolatileQualified())
13712 return;
13713
13714 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
13715 }
13716
13717 // Objective-C instance variables
13718 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
13719 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
13720 if (OL && OR && OL->getDecl() == OR->getDecl()) {
13721 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
13722 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
13723 if (RL && RR && RL->getDecl() == RR->getDecl())
13724 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
13725 }
13726}
13727
13728// C99 6.5.16.1
13731 QualType CompoundType,
13732 BinaryOperatorKind Opc) {
13733 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
13734
13735 // Verify that LHS is a modifiable lvalue, and emit error if not.
13736 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
13737 return QualType();
13738
13739 QualType LHSType = LHSExpr->getType();
13740 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
13741 CompoundType;
13742 // OpenCL v1.2 s6.1.1.1 p2:
13743 // The half data type can only be used to declare a pointer to a buffer that
13744 // contains half values
13745 if (getLangOpts().OpenCL &&
13746 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
13747 LHSType->isHalfType()) {
13748 Diag(Loc, diag::err_opencl_half_load_store) << 1
13749 << LHSType.getUnqualifiedType();
13750 return QualType();
13751 }
13752
13753 // WebAssembly tables can't be used on RHS of an assignment expression.
13754 if (RHSType->isWebAssemblyTableType()) {
13755 Diag(Loc, diag::err_wasm_table_art) << 0;
13756 return QualType();
13757 }
13758
13759 AssignConvertType ConvTy;
13760 if (CompoundType.isNull()) {
13761 Expr *RHSCheck = RHS.get();
13762
13763 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
13764
13765 QualType LHSTy(LHSType);
13766 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
13767 if (RHS.isInvalid())
13768 return QualType();
13769 // Special case of NSObject attributes on c-style pointer types.
13770 if (ConvTy == IncompatiblePointer &&
13771 ((Context.isObjCNSObjectType(LHSType) &&
13772 RHSType->isObjCObjectPointerType()) ||
13773 (Context.isObjCNSObjectType(RHSType) &&
13774 LHSType->isObjCObjectPointerType())))
13775 ConvTy = Compatible;
13776
13777 if (ConvTy == Compatible &&
13778 LHSType->isObjCObjectType())
13779 Diag(Loc, diag::err_objc_object_assignment)
13780 << LHSType;
13781
13782 // If the RHS is a unary plus or minus, check to see if they = and + are
13783 // right next to each other. If so, the user may have typo'd "x =+ 4"
13784 // instead of "x += 4".
13785 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
13786 RHSCheck = ICE->getSubExpr();
13787 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
13788 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
13789 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
13790 // Only if the two operators are exactly adjacent.
13791 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
13792 // And there is a space or other character before the subexpr of the
13793 // unary +/-. We don't want to warn on "x=-1".
13794 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
13795 UO->getSubExpr()->getBeginLoc().isFileID()) {
13796 Diag(Loc, diag::warn_not_compound_assign)
13797 << (UO->getOpcode() == UO_Plus ? "+" : "-")
13798 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
13799 }
13800 }
13801
13802 if (ConvTy == Compatible) {
13803 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
13804 // Warn about retain cycles where a block captures the LHS, but
13805 // not if the LHS is a simple variable into which the block is
13806 // being stored...unless that variable can be captured by reference!
13807 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
13808 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
13809 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
13810 ObjC().checkRetainCycles(LHSExpr, RHS.get());
13811 }
13812
13813 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
13815 // It is safe to assign a weak reference into a strong variable.
13816 // Although this code can still have problems:
13817 // id x = self.weakProp;
13818 // id y = self.weakProp;
13819 // we do not warn to warn spuriously when 'x' and 'y' are on separate
13820 // paths through the function. This should be revisited if
13821 // -Wrepeated-use-of-weak is made flow-sensitive.
13822 // For ObjCWeak only, we do not warn if the assign is to a non-weak
13823 // variable, which will be valid for the current autorelease scope.
13824 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
13825 RHS.get()->getBeginLoc()))
13827
13828 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
13829 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
13830 }
13831 }
13832 } else {
13833 // Compound assignment "x += y"
13834 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
13835 }
13836
13837 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType, RHS.get(),
13839 return QualType();
13840
13841 CheckForNullPointerDereference(*this, LHSExpr);
13842
13843 AssignedEntity AE{LHSExpr};
13844 checkAssignmentLifetime(*this, AE, RHS.get());
13845
13846 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
13847 if (CompoundType.isNull()) {
13848 // C++2a [expr.ass]p5:
13849 // A simple-assignment whose left operand is of a volatile-qualified
13850 // type is deprecated unless the assignment is either a discarded-value
13851 // expression or an unevaluated operand
13852 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
13853 }
13854 }
13855
13856 // C11 6.5.16p3: The type of an assignment expression is the type of the
13857 // left operand would have after lvalue conversion.
13858 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
13859 // qualified type, the value has the unqualified version of the type of the
13860 // lvalue; additionally, if the lvalue has atomic type, the value has the
13861 // non-atomic version of the type of the lvalue.
13862 // C++ 5.17p1: the type of the assignment expression is that of its left
13863 // operand.
13864 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
13865}
13866
13867// Scenarios to ignore if expression E is:
13868// 1. an explicit cast expression into void
13869// 2. a function call expression that returns void
13870static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
13871 E = E->IgnoreParens();
13872
13873 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
13874 if (CE->getCastKind() == CK_ToVoid) {
13875 return true;
13876 }
13877
13878 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
13879 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
13880 CE->getSubExpr()->getType()->isDependentType()) {
13881 return true;
13882 }
13883 }
13884
13885 if (const auto *CE = dyn_cast<CallExpr>(E))
13886 return CE->getCallReturnType(Context)->isVoidType();
13887 return false;
13888}
13889
13891 // No warnings in macros
13892 if (Loc.isMacroID())
13893 return;
13894
13895 // Don't warn in template instantiations.
13897 return;
13898
13899 // Scope isn't fine-grained enough to explicitly list the specific cases, so
13900 // instead, skip more than needed, then call back into here with the
13901 // CommaVisitor in SemaStmt.cpp.
13902 // The listed locations are the initialization and increment portions
13903 // of a for loop. The additional checks are on the condition of
13904 // if statements, do/while loops, and for loops.
13905 // Differences in scope flags for C89 mode requires the extra logic.
13906 const unsigned ForIncrementFlags =
13907 getLangOpts().C99 || getLangOpts().CPlusPlus
13910 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
13911 const unsigned ScopeFlags = getCurScope()->getFlags();
13912 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
13913 (ScopeFlags & ForInitFlags) == ForInitFlags)
13914 return;
13915
13916 // If there are multiple comma operators used together, get the RHS of the
13917 // of the comma operator as the LHS.
13918 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
13919 if (BO->getOpcode() != BO_Comma)
13920 break;
13921 LHS = BO->getRHS();
13922 }
13923
13924 // Only allow some expressions on LHS to not warn.
13925 if (IgnoreCommaOperand(LHS, Context))
13926 return;
13927
13928 Diag(Loc, diag::warn_comma_operator);
13929 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
13930 << LHS->getSourceRange()
13932 LangOpts.CPlusPlus ? "static_cast<void>("
13933 : "(void)(")
13935 ")");
13936}
13937
13938// C99 6.5.17
13941 LHS = S.CheckPlaceholderExpr(LHS.get());
13942 RHS = S.CheckPlaceholderExpr(RHS.get());
13943 if (LHS.isInvalid() || RHS.isInvalid())
13944 return QualType();
13945
13946 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
13947 // operands, but not unary promotions.
13948 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
13949
13950 // So we treat the LHS as a ignored value, and in C++ we allow the
13951 // containing site to determine what should be done with the RHS.
13952 LHS = S.IgnoredValueConversions(LHS.get());
13953 if (LHS.isInvalid())
13954 return QualType();
13955
13956 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
13957
13958 if (!S.getLangOpts().CPlusPlus) {
13960 if (RHS.isInvalid())
13961 return QualType();
13962 if (!RHS.get()->getType()->isVoidType())
13963 S.RequireCompleteType(Loc, RHS.get()->getType(),
13964 diag::err_incomplete_type);
13965 }
13966
13967 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
13968 S.DiagnoseCommaOperator(LHS.get(), Loc);
13969
13970 return RHS.get()->getType();
13971}
13972
13973/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
13974/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
13976 ExprValueKind &VK,
13977 ExprObjectKind &OK,
13978 SourceLocation OpLoc, bool IsInc,
13979 bool IsPrefix) {
13980 QualType ResType = Op->getType();
13981 // Atomic types can be used for increment / decrement where the non-atomic
13982 // versions can, so ignore the _Atomic() specifier for the purpose of
13983 // checking.
13984 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
13985 ResType = ResAtomicType->getValueType();
13986
13987 assert(!ResType.isNull() && "no type for increment/decrement expression");
13988
13989 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
13990 // Decrement of bool is not allowed.
13991 if (!IsInc) {
13992 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
13993 return QualType();
13994 }
13995 // Increment of bool sets it to true, but is deprecated.
13996 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
13997 : diag::warn_increment_bool)
13998 << Op->getSourceRange();
13999 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14000 // Error on enum increments and decrements in C++ mode
14001 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14002 return QualType();
14003 } else if (ResType->isRealType()) {
14004 // OK!
14005 } else if (ResType->isPointerType()) {
14006 // C99 6.5.2.4p2, 6.5.6p2
14007 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14008 return QualType();
14009 } else if (ResType->isObjCObjectPointerType()) {
14010 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14011 // Otherwise, we just need a complete type.
14012 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14013 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14014 return QualType();
14015 } else if (ResType->isAnyComplexType()) {
14016 // C99 does not support ++/-- on complex types, we allow as an extension.
14017 S.Diag(OpLoc, S.getLangOpts().C2y ? diag::warn_c2y_compat_increment_complex
14018 : diag::ext_c2y_increment_complex)
14019 << IsInc << Op->getSourceRange();
14020 } else if (ResType->isPlaceholderType()) {
14022 if (PR.isInvalid()) return QualType();
14023 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14024 IsInc, IsPrefix);
14025 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14026 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14027 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14028 (ResType->castAs<VectorType>()->getVectorKind() !=
14030 // The z vector extensions allow ++ and -- for non-bool vectors.
14031 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14032 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14033 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14034 } else {
14035 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14036 << ResType << int(IsInc) << Op->getSourceRange();
14037 return QualType();
14038 }
14039 // At this point, we know we have a real, complex or pointer type.
14040 // Now make sure the operand is a modifiable lvalue.
14041 if (CheckForModifiableLvalue(Op, OpLoc, S))
14042 return QualType();
14043 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14044 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14045 // An operand with volatile-qualified type is deprecated
14046 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14047 << IsInc << ResType;
14048 }
14049 // In C++, a prefix increment is the same type as the operand. Otherwise
14050 // (in C or with postfix), the increment is the unqualified type of the
14051 // operand.
14052 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14053 VK = VK_LValue;
14054 OK = Op->getObjectKind();
14055 return ResType;
14056 } else {
14057 VK = VK_PRValue;
14058 return ResType.getUnqualifiedType();
14059 }
14060}
14061
14062/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14063/// This routine allows us to typecheck complex/recursive expressions
14064/// where the declaration is needed for type checking. We only need to
14065/// handle cases when the expression references a function designator
14066/// or is an lvalue. Here are some examples:
14067/// - &(x) => x
14068/// - &*****f => f for f a function designator.
14069/// - &s.xx => s
14070/// - &s.zz[1].yy -> s, if zz is an array
14071/// - *(x + 1) -> x, if x is an array
14072/// - &"123"[2] -> 0
14073/// - & __real__ x -> x
14074///
14075/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14076/// members.
14078 switch (E->getStmtClass()) {
14079 case Stmt::DeclRefExprClass:
14080 return cast<DeclRefExpr>(E)->getDecl();
14081 case Stmt::MemberExprClass:
14082 // If this is an arrow operator, the address is an offset from
14083 // the base's value, so the object the base refers to is
14084 // irrelevant.
14085 if (cast<MemberExpr>(E)->isArrow())
14086 return nullptr;
14087 // Otherwise, the expression refers to a part of the base
14088 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14089 case Stmt::ArraySubscriptExprClass: {
14090 // FIXME: This code shouldn't be necessary! We should catch the implicit
14091 // promotion of register arrays earlier.
14092 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14093 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14094 if (ICE->getSubExpr()->getType()->isArrayType())
14095 return getPrimaryDecl(ICE->getSubExpr());
14096 }
14097 return nullptr;
14098 }
14099 case Stmt::UnaryOperatorClass: {
14100 UnaryOperator *UO = cast<UnaryOperator>(E);
14101
14102 switch(UO->getOpcode()) {
14103 case UO_Real:
14104 case UO_Imag:
14105 case UO_Extension:
14106 return getPrimaryDecl(UO->getSubExpr());
14107 default:
14108 return nullptr;
14109 }
14110 }
14111 case Stmt::ParenExprClass:
14112 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14113 case Stmt::ImplicitCastExprClass:
14114 // If the result of an implicit cast is an l-value, we care about
14115 // the sub-expression; otherwise, the result here doesn't matter.
14116 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14117 case Stmt::CXXUuidofExprClass:
14118 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14119 default:
14120 return nullptr;
14121 }
14122}
14123
14124namespace {
14125enum {
14126 AO_Bit_Field = 0,
14127 AO_Vector_Element = 1,
14128 AO_Property_Expansion = 2,
14129 AO_Register_Variable = 3,
14130 AO_Matrix_Element = 4,
14131 AO_No_Error = 5
14132};
14133}
14134/// Diagnose invalid operand for address of operations.
14135///
14136/// \param Type The type of operand which cannot have its address taken.
14138 Expr *E, unsigned Type) {
14139 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14140}
14141
14143 const Expr *Op,
14144 const CXXMethodDecl *MD) {
14145 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14146
14147 if (Op != DRE)
14148 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14149 << Op->getSourceRange();
14150
14151 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14152 if (isa<CXXDestructorDecl>(MD))
14153 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14154 << DRE->getSourceRange();
14155
14156 if (DRE->getQualifier())
14157 return false;
14158
14159 if (MD->getParent()->getName().empty())
14160 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14161 << DRE->getSourceRange();
14162
14163 SmallString<32> Str;
14164 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14165 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14166 << DRE->getSourceRange()
14167 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14168}
14169
14171 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14172 if (PTy->getKind() == BuiltinType::Overload) {
14173 Expr *E = OrigOp.get()->IgnoreParens();
14174 if (!isa<OverloadExpr>(E)) {
14175 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14176 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14177 << OrigOp.get()->getSourceRange();
14178 return QualType();
14179 }
14180
14181 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14182 if (isa<UnresolvedMemberExpr>(Ovl))
14184 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14185 << OrigOp.get()->getSourceRange();
14186 return QualType();
14187 }
14188
14189 return Context.OverloadTy;
14190 }
14191
14192 if (PTy->getKind() == BuiltinType::UnknownAny)
14193 return Context.UnknownAnyTy;
14194
14195 if (PTy->getKind() == BuiltinType::BoundMember) {
14196 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14197 << OrigOp.get()->getSourceRange();
14198 return QualType();
14199 }
14200
14201 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14202 if (OrigOp.isInvalid()) return QualType();
14203 }
14204
14205 if (OrigOp.get()->isTypeDependent())
14206 return Context.DependentTy;
14207
14208 assert(!OrigOp.get()->hasPlaceholderType());
14209
14210 // Make sure to ignore parentheses in subsequent checks
14211 Expr *op = OrigOp.get()->IgnoreParens();
14212
14213 // In OpenCL captures for blocks called as lambda functions
14214 // are located in the private address space. Blocks used in
14215 // enqueue_kernel can be located in a different address space
14216 // depending on a vendor implementation. Thus preventing
14217 // taking an address of the capture to avoid invalid AS casts.
14218 if (LangOpts.OpenCL) {
14219 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14220 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14221 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14222 return QualType();
14223 }
14224 }
14225
14226 if (getLangOpts().C99) {
14227 // Implement C99-only parts of addressof rules.
14228 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14229 if (uOp->getOpcode() == UO_Deref)
14230 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14231 // (assuming the deref expression is valid).
14232 return uOp->getSubExpr()->getType();
14233 }
14234 // Technically, there should be a check for array subscript
14235 // expressions here, but the result of one is always an lvalue anyway.
14236 }
14237 ValueDecl *dcl = getPrimaryDecl(op);
14238
14239 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14240 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14241 op->getBeginLoc()))
14242 return QualType();
14243
14245 unsigned AddressOfError = AO_No_Error;
14246
14247 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14248 bool sfinae = (bool)isSFINAEContext();
14249 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14250 : diag::ext_typecheck_addrof_temporary)
14251 << op->getType() << op->getSourceRange();
14252 if (sfinae)
14253 return QualType();
14254 // Materialize the temporary as an lvalue so that we can take its address.
14255 OrigOp = op =
14256 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14257 } else if (isa<ObjCSelectorExpr>(op)) {
14258 return Context.getPointerType(op->getType());
14259 } else if (lval == Expr::LV_MemberFunction) {
14260 // If it's an instance method, make a member pointer.
14261 // The expression must have exactly the form &A::foo.
14262
14263 // If the underlying expression isn't a decl ref, give up.
14264 if (!isa<DeclRefExpr>(op)) {
14265 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14266 << OrigOp.get()->getSourceRange();
14267 return QualType();
14268 }
14269 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14270 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14271
14272 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14273
14276
14277 if (getLangOpts().PointerAuthCalls && MD->isVirtual() &&
14278 !isUnevaluatedContext() && !MPTy->isDependentType()) {
14279 // When pointer authentication is enabled, argument and return types of
14280 // vitual member functions must be complete. This is because vitrual
14281 // member function pointers are implemented using virtual dispatch
14282 // thunks and the thunks cannot be emitted if the argument or return
14283 // types are incomplete.
14284 auto ReturnOrParamTypeIsIncomplete = [&](QualType T,
14285 SourceLocation DeclRefLoc,
14286 SourceLocation RetArgTypeLoc) {
14287 if (RequireCompleteType(DeclRefLoc, T, diag::err_incomplete_type)) {
14288 Diag(DeclRefLoc,
14289 diag::note_ptrauth_virtual_function_pointer_incomplete_arg_ret);
14290 Diag(RetArgTypeLoc,
14291 diag::note_ptrauth_virtual_function_incomplete_arg_ret_type)
14292 << T;
14293 return true;
14294 }
14295 return false;
14296 };
14297 QualType RetTy = MD->getReturnType();
14298 bool IsIncomplete =
14299 !RetTy->isVoidType() &&
14300 ReturnOrParamTypeIsIncomplete(
14301 RetTy, OpLoc, MD->getReturnTypeSourceRange().getBegin());
14302 for (auto *PVD : MD->parameters())
14303 IsIncomplete |= ReturnOrParamTypeIsIncomplete(PVD->getType(), OpLoc,
14304 PVD->getBeginLoc());
14305 if (IsIncomplete)
14306 return QualType();
14307 }
14308
14309 // Under the MS ABI, lock down the inheritance model now.
14311 (void)isCompleteType(OpLoc, MPTy);
14312 return MPTy;
14313 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14314 // C99 6.5.3.2p1
14315 // The operand must be either an l-value or a function designator
14316 if (!op->getType()->isFunctionType()) {
14317 // Use a special diagnostic for loads from property references.
14318 if (isa<PseudoObjectExpr>(op)) {
14319 AddressOfError = AO_Property_Expansion;
14320 } else {
14321 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14322 << op->getType() << op->getSourceRange();
14323 return QualType();
14324 }
14325 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14326 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14327 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14328 }
14329
14330 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14331 // The operand cannot be a bit-field
14332 AddressOfError = AO_Bit_Field;
14333 } else if (op->getObjectKind() == OK_VectorComponent) {
14334 // The operand cannot be an element of a vector
14335 AddressOfError = AO_Vector_Element;
14336 } else if (op->getObjectKind() == OK_MatrixComponent) {
14337 // The operand cannot be an element of a matrix.
14338 AddressOfError = AO_Matrix_Element;
14339 } else if (dcl) { // C99 6.5.3.2p1
14340 // We have an lvalue with a decl. Make sure the decl is not declared
14341 // with the register storage-class specifier.
14342 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14343 // in C++ it is not error to take address of a register
14344 // variable (c++03 7.1.1P3)
14345 if (vd->getStorageClass() == SC_Register &&
14347 AddressOfError = AO_Register_Variable;
14348 }
14349 } else if (isa<MSPropertyDecl>(dcl)) {
14350 AddressOfError = AO_Property_Expansion;
14351 } else if (isa<FunctionTemplateDecl>(dcl)) {
14352 return Context.OverloadTy;
14353 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14354 // Okay: we can take the address of a field.
14355 // Could be a pointer to member, though, if there is an explicit
14356 // scope qualifier for the class.
14357
14358 // [C++26] [expr.prim.id.general]
14359 // If an id-expression E denotes a non-static non-type member
14360 // of some class C [...] and if E is a qualified-id, E is
14361 // not the un-parenthesized operand of the unary & operator [...]
14362 // the id-expression is transformed into a class member access expression.
14363 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
14364 !isa<ParenExpr>(OrigOp.get())) {
14365 DeclContext *Ctx = dcl->getDeclContext();
14366 if (Ctx && Ctx->isRecord()) {
14367 if (dcl->getType()->isReferenceType()) {
14368 Diag(OpLoc,
14369 diag::err_cannot_form_pointer_to_member_of_reference_type)
14370 << dcl->getDeclName() << dcl->getType();
14371 return QualType();
14372 }
14373
14374 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14375 Ctx = Ctx->getParent();
14376
14378 op->getType(),
14379 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14380 // Under the MS ABI, lock down the inheritance model now.
14382 (void)isCompleteType(OpLoc, MPTy);
14383 return MPTy;
14384 }
14385 }
14388 llvm_unreachable("Unknown/unexpected decl type");
14389 }
14390
14391 if (AddressOfError != AO_No_Error) {
14392 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14393 return QualType();
14394 }
14395
14396 if (lval == Expr::LV_IncompleteVoidType) {
14397 // Taking the address of a void variable is technically illegal, but we
14398 // allow it in cases which are otherwise valid.
14399 // Example: "extern void x; void* y = &x;".
14400 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14401 }
14402
14403 // If the operand has type "type", the result has type "pointer to type".
14404 if (op->getType()->isObjCObjectType())
14406
14407 // Cannot take the address of WebAssembly references or tables.
14408 if (Context.getTargetInfo().getTriple().isWasm()) {
14409 QualType OpTy = op->getType();
14410 if (OpTy.isWebAssemblyReferenceType()) {
14411 Diag(OpLoc, diag::err_wasm_ca_reference)
14412 << 1 << OrigOp.get()->getSourceRange();
14413 return QualType();
14414 }
14415 if (OpTy->isWebAssemblyTableType()) {
14416 Diag(OpLoc, diag::err_wasm_table_pr)
14417 << 1 << OrigOp.get()->getSourceRange();
14418 return QualType();
14419 }
14420 }
14421
14422 CheckAddressOfPackedMember(op);
14423
14424 return Context.getPointerType(op->getType());
14425}
14426
14427static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14428 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14429 if (!DRE)
14430 return;
14431 const Decl *D = DRE->getDecl();
14432 if (!D)
14433 return;
14434 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14435 if (!Param)
14436 return;
14437 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14438 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14439 return;
14440 if (FunctionScopeInfo *FD = S.getCurFunction())
14441 FD->ModifiedNonNullParams.insert(Param);
14442}
14443
14444/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14446 SourceLocation OpLoc,
14447 bool IsAfterAmp = false) {
14448 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14449 if (ConvResult.isInvalid())
14450 return QualType();
14451 Op = ConvResult.get();
14452 QualType OpTy = Op->getType();
14454
14455 if (isa<CXXReinterpretCastExpr>(Op)) {
14456 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14457 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14458 Op->getSourceRange());
14459 }
14460
14461 if (const PointerType *PT = OpTy->getAs<PointerType>())
14462 {
14463 Result = PT->getPointeeType();
14464 }
14465 else if (const ObjCObjectPointerType *OPT =
14467 Result = OPT->getPointeeType();
14468 else {
14470 if (PR.isInvalid()) return QualType();
14471 if (PR.get() != Op)
14472 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14473 }
14474
14475 if (Result.isNull()) {
14476 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14477 << OpTy << Op->getSourceRange();
14478 return QualType();
14479 }
14480
14481 if (Result->isVoidType()) {
14482 // C++ [expr.unary.op]p1:
14483 // [...] the expression to which [the unary * operator] is applied shall
14484 // be a pointer to an object type, or a pointer to a function type
14485 LangOptions LO = S.getLangOpts();
14486 if (LO.CPlusPlus)
14487 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
14488 << OpTy << Op->getSourceRange();
14489 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14490 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14491 << OpTy << Op->getSourceRange();
14492 }
14493
14494 // Dereferences are usually l-values...
14495 VK = VK_LValue;
14496
14497 // ...except that certain expressions are never l-values in C.
14498 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14499 VK = VK_PRValue;
14500
14501 return Result;
14502}
14503
14504BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14506 switch (Kind) {
14507 default: llvm_unreachable("Unknown binop!");
14508 case tok::periodstar: Opc = BO_PtrMemD; break;
14509 case tok::arrowstar: Opc = BO_PtrMemI; break;
14510 case tok::star: Opc = BO_Mul; break;
14511 case tok::slash: Opc = BO_Div; break;
14512 case tok::percent: Opc = BO_Rem; break;
14513 case tok::plus: Opc = BO_Add; break;
14514 case tok::minus: Opc = BO_Sub; break;
14515 case tok::lessless: Opc = BO_Shl; break;
14516 case tok::greatergreater: Opc = BO_Shr; break;
14517 case tok::lessequal: Opc = BO_LE; break;
14518 case tok::less: Opc = BO_LT; break;
14519 case tok::greaterequal: Opc = BO_GE; break;
14520 case tok::greater: Opc = BO_GT; break;
14521 case tok::exclaimequal: Opc = BO_NE; break;
14522 case tok::equalequal: Opc = BO_EQ; break;
14523 case tok::spaceship: Opc = BO_Cmp; break;
14524 case tok::amp: Opc = BO_And; break;
14525 case tok::caret: Opc = BO_Xor; break;
14526 case tok::pipe: Opc = BO_Or; break;
14527 case tok::ampamp: Opc = BO_LAnd; break;
14528 case tok::pipepipe: Opc = BO_LOr; break;
14529 case tok::equal: Opc = BO_Assign; break;
14530 case tok::starequal: Opc = BO_MulAssign; break;
14531 case tok::slashequal: Opc = BO_DivAssign; break;
14532 case tok::percentequal: Opc = BO_RemAssign; break;
14533 case tok::plusequal: Opc = BO_AddAssign; break;
14534 case tok::minusequal: Opc = BO_SubAssign; break;
14535 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14536 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14537 case tok::ampequal: Opc = BO_AndAssign; break;
14538 case tok::caretequal: Opc = BO_XorAssign; break;
14539 case tok::pipeequal: Opc = BO_OrAssign; break;
14540 case tok::comma: Opc = BO_Comma; break;
14541 }
14542 return Opc;
14543}
14544
14546 tok::TokenKind Kind) {
14548 switch (Kind) {
14549 default: llvm_unreachable("Unknown unary op!");
14550 case tok::plusplus: Opc = UO_PreInc; break;
14551 case tok::minusminus: Opc = UO_PreDec; break;
14552 case tok::amp: Opc = UO_AddrOf; break;
14553 case tok::star: Opc = UO_Deref; break;
14554 case tok::plus: Opc = UO_Plus; break;
14555 case tok::minus: Opc = UO_Minus; break;
14556 case tok::tilde: Opc = UO_Not; break;
14557 case tok::exclaim: Opc = UO_LNot; break;
14558 case tok::kw___real: Opc = UO_Real; break;
14559 case tok::kw___imag: Opc = UO_Imag; break;
14560 case tok::kw___extension__: Opc = UO_Extension; break;
14561 }
14562 return Opc;
14563}
14564
14565const FieldDecl *
14567 // Explore the case for adding 'this->' to the LHS of a self assignment, very
14568 // common for setters.
14569 // struct A {
14570 // int X;
14571 // -void setX(int X) { X = X; }
14572 // +void setX(int X) { this->X = X; }
14573 // };
14574
14575 // Only consider parameters for self assignment fixes.
14576 if (!isa<ParmVarDecl>(SelfAssigned))
14577 return nullptr;
14578 const auto *Method =
14579 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14580 if (!Method)
14581 return nullptr;
14582
14583 const CXXRecordDecl *Parent = Method->getParent();
14584 // In theory this is fixable if the lambda explicitly captures this, but
14585 // that's added complexity that's rarely going to be used.
14586 if (Parent->isLambda())
14587 return nullptr;
14588
14589 // FIXME: Use an actual Lookup operation instead of just traversing fields
14590 // in order to get base class fields.
14591 auto Field =
14592 llvm::find_if(Parent->fields(),
14593 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14594 return F->getDeclName() == Name;
14595 });
14596 return (Field != Parent->field_end()) ? *Field : nullptr;
14597}
14598
14599/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14600/// This warning suppressed in the event of macro expansions.
14601static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14602 SourceLocation OpLoc, bool IsBuiltin) {
14604 return;
14605 if (S.isUnevaluatedContext())
14606 return;
14607 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14608 return;
14609 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14610 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14611 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14612 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14613 if (!LHSDeclRef || !RHSDeclRef ||
14614 LHSDeclRef->getLocation().isMacroID() ||
14615 RHSDeclRef->getLocation().isMacroID())
14616 return;
14617 const ValueDecl *LHSDecl =
14618 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14619 const ValueDecl *RHSDecl =
14620 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14621 if (LHSDecl != RHSDecl)
14622 return;
14623 if (LHSDecl->getType().isVolatileQualified())
14624 return;
14625 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14626 if (RefTy->getPointeeType().isVolatileQualified())
14627 return;
14628
14629 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14630 : diag::warn_self_assignment_overloaded)
14631 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14632 << RHSExpr->getSourceRange();
14633 if (const FieldDecl *SelfAssignField =
14635 Diag << 1 << SelfAssignField
14636 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14637 else
14638 Diag << 0;
14639}
14640
14641/// Check if a bitwise-& is performed on an Objective-C pointer. This
14642/// is usually indicative of introspection within the Objective-C pointer.
14644 SourceLocation OpLoc) {
14645 if (!S.getLangOpts().ObjC)
14646 return;
14647
14648 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14649 const Expr *LHS = L.get();
14650 const Expr *RHS = R.get();
14651
14653 ObjCPointerExpr = LHS;
14654 OtherExpr = RHS;
14655 }
14656 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14657 ObjCPointerExpr = RHS;
14658 OtherExpr = LHS;
14659 }
14660
14661 // This warning is deliberately made very specific to reduce false
14662 // positives with logic that uses '&' for hashing. This logic mainly
14663 // looks for code trying to introspect into tagged pointers, which
14664 // code should generally never do.
14665 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14666 unsigned Diag = diag::warn_objc_pointer_masking;
14667 // Determine if we are introspecting the result of performSelectorXXX.
14668 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14669 // Special case messages to -performSelector and friends, which
14670 // can return non-pointer values boxed in a pointer value.
14671 // Some clients may wish to silence warnings in this subcase.
14672 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14673 Selector S = ME->getSelector();
14674 StringRef SelArg0 = S.getNameForSlot(0);
14675 if (SelArg0.starts_with("performSelector"))
14676 Diag = diag::warn_objc_pointer_masking_performSelector;
14677 }
14678
14679 S.Diag(OpLoc, Diag)
14680 << ObjCPointerExpr->getSourceRange();
14681 }
14682}
14683
14685 if (!E)
14686 return nullptr;
14687 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14688 return DRE->getDecl();
14689 if (auto *ME = dyn_cast<MemberExpr>(E))
14690 return ME->getMemberDecl();
14691 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14692 return IRE->getDecl();
14693 return nullptr;
14694}
14695
14696// This helper function promotes a binary operator's operands (which are of a
14697// half vector type) to a vector of floats and then truncates the result to
14698// a vector of either half or short.
14700 BinaryOperatorKind Opc, QualType ResultTy,
14702 bool IsCompAssign, SourceLocation OpLoc,
14703 FPOptionsOverride FPFeatures) {
14704 auto &Context = S.getASTContext();
14705 assert((isVector(ResultTy, Context.HalfTy) ||
14706 isVector(ResultTy, Context.ShortTy)) &&
14707 "Result must be a vector of half or short");
14708 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14709 isVector(RHS.get()->getType(), Context.HalfTy) &&
14710 "both operands expected to be a half vector");
14711
14712 RHS = convertVector(RHS.get(), Context.FloatTy, S);
14713 QualType BinOpResTy = RHS.get()->getType();
14714
14715 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14716 // change BinOpResTy to a vector of ints.
14717 if (isVector(ResultTy, Context.ShortTy))
14718 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14719
14720 if (IsCompAssign)
14721 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14722 ResultTy, VK, OK, OpLoc, FPFeatures,
14723 BinOpResTy, BinOpResTy);
14724
14725 LHS = convertVector(LHS.get(), Context.FloatTy, S);
14726 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14727 BinOpResTy, VK, OK, OpLoc, FPFeatures);
14728 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
14729}
14730
14731static std::pair<ExprResult, ExprResult>
14733 Expr *RHSExpr) {
14734 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14735 if (!S.Context.isDependenceAllowed()) {
14736 // C cannot handle TypoExpr nodes on either side of a binop because it
14737 // doesn't handle dependent types properly, so make sure any TypoExprs have
14738 // been dealt with before checking the operands.
14739 LHS = S.CorrectDelayedTyposInExpr(LHS);
14741 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
14742 [Opc, LHS](Expr *E) {
14743 if (Opc != BO_Assign)
14744 return ExprResult(E);
14745 // Avoid correcting the RHS to the same Expr as the LHS.
14746 Decl *D = getDeclFromExpr(E);
14747 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
14748 });
14749 }
14750 return std::make_pair(LHS, RHS);
14751}
14752
14753/// Returns true if conversion between vectors of halfs and vectors of floats
14754/// is needed.
14755static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
14756 Expr *E0, Expr *E1 = nullptr) {
14757 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
14759 return false;
14760
14761 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
14762 QualType Ty = E->IgnoreImplicit()->getType();
14763
14764 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
14765 // to vectors of floats. Although the element type of the vectors is __fp16,
14766 // the vectors shouldn't be treated as storage-only types. See the
14767 // discussion here: https://reviews.llvm.org/rG825235c140e7
14768 if (const VectorType *VT = Ty->getAs<VectorType>()) {
14769 if (VT->getVectorKind() == VectorKind::Neon)
14770 return false;
14771 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
14772 }
14773 return false;
14774 };
14775
14776 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
14777}
14778
14781 Expr *LHSExpr, Expr *RHSExpr) {
14782 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
14783 // The syntax only allows initializer lists on the RHS of assignment,
14784 // so we don't need to worry about accepting invalid code for
14785 // non-assignment operators.
14786 // C++11 5.17p9:
14787 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
14788 // of x = {} is x = T().
14790 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14791 InitializedEntity Entity =
14793 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
14794 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
14795 if (Init.isInvalid())
14796 return Init;
14797 RHSExpr = Init.get();
14798 }
14799
14800 ExprResult LHS = LHSExpr, RHS = RHSExpr;
14801 QualType ResultTy; // Result type of the binary operator.
14802 // The following two variables are used for compound assignment operators
14803 QualType CompLHSTy; // Type of LHS after promotions for computation
14804 QualType CompResultTy; // Type of computation result
14807 bool ConvertHalfVec = false;
14808
14809 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
14810 if (!LHS.isUsable() || !RHS.isUsable())
14811 return ExprError();
14812
14813 if (getLangOpts().OpenCL) {
14814 QualType LHSTy = LHSExpr->getType();
14815 QualType RHSTy = RHSExpr->getType();
14816 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
14817 // the ATOMIC_VAR_INIT macro.
14818 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
14819 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
14820 if (BO_Assign == Opc)
14821 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
14822 else
14823 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14824 return ExprError();
14825 }
14826
14827 // OpenCL special types - image, sampler, pipe, and blocks are to be used
14828 // only with a builtin functions and therefore should be disallowed here.
14829 if (LHSTy->isImageType() || RHSTy->isImageType() ||
14830 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
14831 LHSTy->isPipeType() || RHSTy->isPipeType() ||
14832 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
14833 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
14834 return ExprError();
14835 }
14836 }
14837
14838 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14839 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
14840
14841 switch (Opc) {
14842 case BO_Assign:
14843 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
14844 if (getLangOpts().CPlusPlus &&
14845 LHS.get()->getObjectKind() != OK_ObjCProperty) {
14846 VK = LHS.get()->getValueKind();
14847 OK = LHS.get()->getObjectKind();
14848 }
14849 if (!ResultTy.isNull()) {
14850 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14851 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
14852
14853 // Avoid copying a block to the heap if the block is assigned to a local
14854 // auto variable that is declared in the same scope as the block. This
14855 // optimization is unsafe if the local variable is declared in an outer
14856 // scope. For example:
14857 //
14858 // BlockTy b;
14859 // {
14860 // b = ^{...};
14861 // }
14862 // // It is unsafe to invoke the block here if it wasn't copied to the
14863 // // heap.
14864 // b();
14865
14866 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
14867 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
14868 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
14869 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
14870 BE->getBlockDecl()->setCanAvoidCopyToHeap();
14871
14873 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
14875 }
14876 RecordModifiableNonNullParam(*this, LHS.get());
14877 break;
14878 case BO_PtrMemD:
14879 case BO_PtrMemI:
14880 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
14881 Opc == BO_PtrMemI);
14882 break;
14883 case BO_Mul:
14884 case BO_Div:
14885 ConvertHalfVec = true;
14886 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
14887 Opc == BO_Div);
14888 break;
14889 case BO_Rem:
14890 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
14891 break;
14892 case BO_Add:
14893 ConvertHalfVec = true;
14894 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
14895 break;
14896 case BO_Sub:
14897 ConvertHalfVec = true;
14898 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
14899 break;
14900 case BO_Shl:
14901 case BO_Shr:
14902 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
14903 break;
14904 case BO_LE:
14905 case BO_LT:
14906 case BO_GE:
14907 case BO_GT:
14908 ConvertHalfVec = true;
14909 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14910
14911 if (const auto *BI = dyn_cast<BinaryOperator>(LHSExpr);
14912 BI && BI->isComparisonOp())
14913 Diag(OpLoc, diag::warn_consecutive_comparison);
14914
14915 break;
14916 case BO_EQ:
14917 case BO_NE:
14918 ConvertHalfVec = true;
14919 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14920 break;
14921 case BO_Cmp:
14922 ConvertHalfVec = true;
14923 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
14924 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
14925 break;
14926 case BO_And:
14927 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
14928 [[fallthrough]];
14929 case BO_Xor:
14930 case BO_Or:
14931 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14932 break;
14933 case BO_LAnd:
14934 case BO_LOr:
14935 ConvertHalfVec = true;
14936 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
14937 break;
14938 case BO_MulAssign:
14939 case BO_DivAssign:
14940 ConvertHalfVec = true;
14941 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
14942 Opc == BO_DivAssign);
14943 CompLHSTy = CompResultTy;
14944 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14945 ResultTy =
14946 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14947 break;
14948 case BO_RemAssign:
14949 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
14950 CompLHSTy = CompResultTy;
14951 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14952 ResultTy =
14953 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14954 break;
14955 case BO_AddAssign:
14956 ConvertHalfVec = true;
14957 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
14958 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14959 ResultTy =
14960 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14961 break;
14962 case BO_SubAssign:
14963 ConvertHalfVec = true;
14964 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
14965 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14966 ResultTy =
14967 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14968 break;
14969 case BO_ShlAssign:
14970 case BO_ShrAssign:
14971 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
14972 CompLHSTy = CompResultTy;
14973 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14974 ResultTy =
14975 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14976 break;
14977 case BO_AndAssign:
14978 case BO_OrAssign: // fallthrough
14979 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
14980 [[fallthrough]];
14981 case BO_XorAssign:
14982 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
14983 CompLHSTy = CompResultTy;
14984 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
14985 ResultTy =
14986 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
14987 break;
14988 case BO_Comma:
14989 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
14990 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
14991 VK = RHS.get()->getValueKind();
14992 OK = RHS.get()->getObjectKind();
14993 }
14994 break;
14995 }
14996 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
14997 return ExprError();
14998
14999 // Some of the binary operations require promoting operands of half vector to
15000 // float vectors and truncating the result back to half vector. For now, we do
15001 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15002 // arm64).
15003 assert(
15004 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15005 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15006 "both sides are half vectors or neither sides are");
15007 ConvertHalfVec =
15008 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15009
15010 // Check for array bounds violations for both sides of the BinaryOperator
15011 CheckArrayAccess(LHS.get());
15012 CheckArrayAccess(RHS.get());
15013
15014 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15015 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15016 &Context.Idents.get("object_setClass"),
15018 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15019 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15020 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15022 "object_setClass(")
15023 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15024 ",")
15025 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15026 }
15027 else
15028 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15029 }
15030 else if (const ObjCIvarRefExpr *OIRE =
15031 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15032 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15033
15034 // Opc is not a compound assignment if CompResultTy is null.
15035 if (CompResultTy.isNull()) {
15036 if (ConvertHalfVec)
15037 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15038 OpLoc, CurFPFeatureOverrides());
15039 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15040 VK, OK, OpLoc, CurFPFeatureOverrides());
15041 }
15042
15043 // Handle compound assignments.
15044 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15046 VK = VK_LValue;
15047 OK = LHS.get()->getObjectKind();
15048 }
15049
15050 // The LHS is not converted to the result type for fixed-point compound
15051 // assignment as the common type is computed on demand. Reset the CompLHSTy
15052 // to the LHS type we would have gotten after unary conversions.
15053 if (CompResultTy->isFixedPointType())
15054 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15055
15056 if (ConvertHalfVec)
15057 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15058 OpLoc, CurFPFeatureOverrides());
15059
15061 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15062 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15063}
15064
15065/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15066/// operators are mixed in a way that suggests that the programmer forgot that
15067/// comparison operators have higher precedence. The most typical example of
15068/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15070 SourceLocation OpLoc, Expr *LHSExpr,
15071 Expr *RHSExpr) {
15072 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15073 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15074
15075 // Check that one of the sides is a comparison operator and the other isn't.
15076 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15077 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15078 if (isLeftComp == isRightComp)
15079 return;
15080
15081 // Bitwise operations are sometimes used as eager logical ops.
15082 // Don't diagnose this.
15083 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15084 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15085 if (isLeftBitwise || isRightBitwise)
15086 return;
15087
15088 SourceRange DiagRange = isLeftComp
15089 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15090 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15091 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15092 SourceRange ParensRange =
15093 isLeftComp
15094 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15095 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15096
15097 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15098 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15099 SuggestParentheses(Self, OpLoc,
15100 Self.PDiag(diag::note_precedence_silence) << OpStr,
15101 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15102 SuggestParentheses(Self, OpLoc,
15103 Self.PDiag(diag::note_precedence_bitwise_first)
15105 ParensRange);
15106}
15107
15108/// It accepts a '&&' expr that is inside a '||' one.
15109/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15110/// in parentheses.
15111static void
15113 BinaryOperator *Bop) {
15114 assert(Bop->getOpcode() == BO_LAnd);
15115 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15116 << Bop->getSourceRange() << OpLoc;
15118 Self.PDiag(diag::note_precedence_silence)
15119 << Bop->getOpcodeStr(),
15120 Bop->getSourceRange());
15121}
15122
15123/// Look for '&&' in the left hand of a '||' expr.
15125 Expr *LHSExpr, Expr *RHSExpr) {
15126 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15127 if (Bop->getOpcode() == BO_LAnd) {
15128 // If it's "string_literal && a || b" don't warn since the precedence
15129 // doesn't matter.
15130 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15131 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15132 } else if (Bop->getOpcode() == BO_LOr) {
15133 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15134 // If it's "a || b && string_literal || c" we didn't warn earlier for
15135 // "a || b && string_literal", but warn now.
15136 if (RBop->getOpcode() == BO_LAnd &&
15137 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15138 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15139 }
15140 }
15141 }
15142}
15143
15144/// Look for '&&' in the right hand of a '||' expr.
15146 Expr *LHSExpr, Expr *RHSExpr) {
15147 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15148 if (Bop->getOpcode() == BO_LAnd) {
15149 // If it's "a || b && string_literal" don't warn since the precedence
15150 // doesn't matter.
15151 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15152 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15153 }
15154 }
15155}
15156
15157/// Look for bitwise op in the left or right hand of a bitwise op with
15158/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15159/// the '&' expression in parentheses.
15161 SourceLocation OpLoc, Expr *SubExpr) {
15162 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15163 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15164 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15165 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15166 << Bop->getSourceRange() << OpLoc;
15167 SuggestParentheses(S, Bop->getOperatorLoc(),
15168 S.PDiag(diag::note_precedence_silence)
15169 << Bop->getOpcodeStr(),
15170 Bop->getSourceRange());
15171 }
15172 }
15173}
15174
15176 Expr *SubExpr, StringRef Shift) {
15177 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15178 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15179 StringRef Op = Bop->getOpcodeStr();
15180 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15181 << Bop->getSourceRange() << OpLoc << Shift << Op;
15182 SuggestParentheses(S, Bop->getOperatorLoc(),
15183 S.PDiag(diag::note_precedence_silence) << Op,
15184 Bop->getSourceRange());
15185 }
15186 }
15187}
15188
15190 Expr *LHSExpr, Expr *RHSExpr) {
15191 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15192 if (!OCE)
15193 return;
15194
15195 FunctionDecl *FD = OCE->getDirectCallee();
15196 if (!FD || !FD->isOverloadedOperator())
15197 return;
15198
15200 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15201 return;
15202
15203 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15204 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15205 << (Kind == OO_LessLess);
15207 S.PDiag(diag::note_precedence_silence)
15208 << (Kind == OO_LessLess ? "<<" : ">>"),
15209 OCE->getSourceRange());
15211 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15212 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15213}
15214
15215/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15216/// precedence.
15218 SourceLocation OpLoc, Expr *LHSExpr,
15219 Expr *RHSExpr){
15220 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15222 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15223
15224 // Diagnose "arg1 & arg2 | arg3"
15225 if ((Opc == BO_Or || Opc == BO_Xor) &&
15226 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15227 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15228 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15229 }
15230
15231 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15232 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15233 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15234 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15235 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15236 }
15237
15238 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15239 || Opc == BO_Shr) {
15240 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15241 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15242 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15243 }
15244
15245 // Warn on overloaded shift operators and comparisons, such as:
15246 // cout << 5 == 4;
15248 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15249}
15250
15252 Expr *Operand) {
15253 if (auto *CT = Operand->getType()->getAs<ComplexType>()) {
15254 QualType ElementType = CT->getElementType();
15255 bool IsComplexRangePromoted = S.getLangOpts().getComplexRange() ==
15257 if (ElementType->isFloatingType() && IsComplexRangePromoted) {
15258 ASTContext &Ctx = S.getASTContext();
15259 QualType HigherElementType = Ctx.GetHigherPrecisionFPType(ElementType);
15260 const llvm::fltSemantics &ElementTypeSemantics =
15261 Ctx.getFloatTypeSemantics(ElementType);
15262 const llvm::fltSemantics &HigherElementTypeSemantics =
15263 Ctx.getFloatTypeSemantics(HigherElementType);
15264 if (llvm::APFloat::semanticsMaxExponent(ElementTypeSemantics) * 2 + 1 >
15265 llvm::APFloat::semanticsMaxExponent(HigherElementTypeSemantics)) {
15266 // Retain the location of the first use of higher precision type.
15269 for (auto &[Type, Num] : S.ExcessPrecisionNotSatisfied) {
15270 if (Type == HigherElementType) {
15271 Num++;
15272 return;
15273 }
15274 }
15275 S.ExcessPrecisionNotSatisfied.push_back(std::make_pair(
15276 HigherElementType, S.ExcessPrecisionNotSatisfied.size()));
15277 }
15278 }
15279 }
15280}
15281
15283 tok::TokenKind Kind,
15284 Expr *LHSExpr, Expr *RHSExpr) {
15285 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15286 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15287 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15288
15289 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15290 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15291
15292 // Emit warnings if the requested higher precision type equal to the current
15293 // type precision.
15294 if (Kind == tok::TokenKind::slash)
15295 DetectPrecisionLossInComplexDivision(*this, TokLoc, LHSExpr);
15296
15297 BuiltinCountedByRefKind K =
15298 BinaryOperator::isAssignmentOp(Opc) ? AssignmentKind : BinaryExprKind;
15299
15300 CheckInvalidBuiltinCountedByRef(LHSExpr, K);
15301 CheckInvalidBuiltinCountedByRef(RHSExpr, K);
15302
15303 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15304}
15305
15307 UnresolvedSetImpl &Functions) {
15309 if (OverOp != OO_None && OverOp != OO_Equal)
15310 LookupOverloadedOperatorName(OverOp, S, Functions);
15311
15312 // In C++20 onwards, we may have a second operator to look up.
15313 if (getLangOpts().CPlusPlus20) {
15315 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15316 }
15317}
15318
15319/// Build an overloaded binary operator expression in the given scope.
15322 Expr *LHS, Expr *RHS) {
15323 switch (Opc) {
15324 case BO_Assign:
15325 // In the non-overloaded case, we warn about self-assignment (x = x) for
15326 // both simple assignment and certain compound assignments where algebra
15327 // tells us the operation yields a constant result. When the operator is
15328 // overloaded, we can't do the latter because we don't want to assume that
15329 // those algebraic identities still apply; for example, a path-building
15330 // library might use operator/= to append paths. But it's still reasonable
15331 // to assume that simple assignment is just moving/copying values around
15332 // and so self-assignment is likely a bug.
15333 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15334 [[fallthrough]];
15335 case BO_DivAssign:
15336 case BO_RemAssign:
15337 case BO_SubAssign:
15338 case BO_AndAssign:
15339 case BO_OrAssign:
15340 case BO_XorAssign:
15341 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15342 break;
15343 default:
15344 break;
15345 }
15346
15347 // Find all of the overloaded operators visible from this point.
15348 UnresolvedSet<16> Functions;
15349 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15350
15351 // Build the (potentially-overloaded, potentially-dependent)
15352 // binary operation.
15353 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15354}
15355
15358 Expr *LHSExpr, Expr *RHSExpr) {
15359 ExprResult LHS, RHS;
15360 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15361 if (!LHS.isUsable() || !RHS.isUsable())
15362 return ExprError();
15363 LHSExpr = LHS.get();
15364 RHSExpr = RHS.get();
15365
15366 // We want to end up calling one of SemaPseudoObject::checkAssignment
15367 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15368 // both expressions are overloadable or either is type-dependent),
15369 // or CreateBuiltinBinOp (in any other case). We also want to get
15370 // any placeholder types out of the way.
15371
15372 // Handle pseudo-objects in the LHS.
15373 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15374 // Assignments with a pseudo-object l-value need special analysis.
15375 if (pty->getKind() == BuiltinType::PseudoObject &&
15377 return PseudoObject().checkAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15378
15379 // Don't resolve overloads if the other type is overloadable.
15380 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15381 // We can't actually test that if we still have a placeholder,
15382 // though. Fortunately, none of the exceptions we see in that
15383 // code below are valid when the LHS is an overload set. Note
15384 // that an overload set can be dependently-typed, but it never
15385 // instantiates to having an overloadable type.
15386 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15387 if (resolvedRHS.isInvalid()) return ExprError();
15388 RHSExpr = resolvedRHS.get();
15389
15390 if (RHSExpr->isTypeDependent() ||
15391 RHSExpr->getType()->isOverloadableType())
15392 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15393 }
15394
15395 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15396 // template, diagnose the missing 'template' keyword instead of diagnosing
15397 // an invalid use of a bound member function.
15398 //
15399 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15400 // to C++1z [over.over]/1.4, but we already checked for that case above.
15401 if (Opc == BO_LT && inTemplateInstantiation() &&
15402 (pty->getKind() == BuiltinType::BoundMember ||
15403 pty->getKind() == BuiltinType::Overload)) {
15404 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15405 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15406 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15407 return isa<FunctionTemplateDecl>(ND);
15408 })) {
15409 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15410 : OE->getNameLoc(),
15411 diag::err_template_kw_missing)
15412 << OE->getName().getAsString() << "";
15413 return ExprError();
15414 }
15415 }
15416
15417 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15418 if (LHS.isInvalid()) return ExprError();
15419 LHSExpr = LHS.get();
15420 }
15421
15422 // Handle pseudo-objects in the RHS.
15423 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15424 // An overload in the RHS can potentially be resolved by the type
15425 // being assigned to.
15426 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15427 if (getLangOpts().CPlusPlus &&
15428 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15429 LHSExpr->getType()->isOverloadableType()))
15430 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15431
15432 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15433 }
15434
15435 // Don't resolve overloads if the other type is overloadable.
15436 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15437 LHSExpr->getType()->isOverloadableType())
15438 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15439
15440 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15441 if (!resolvedRHS.isUsable()) return ExprError();
15442 RHSExpr = resolvedRHS.get();
15443 }
15444
15445 if (getLangOpts().CPlusPlus) {
15446 // Otherwise, build an overloaded op if either expression is type-dependent
15447 // or has an overloadable type.
15448 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15449 LHSExpr->getType()->isOverloadableType() ||
15450 RHSExpr->getType()->isOverloadableType())
15451 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15452 }
15453
15454 if (getLangOpts().RecoveryAST &&
15455 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15456 assert(!getLangOpts().CPlusPlus);
15457 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15458 "Should only occur in error-recovery path.");
15460 // C [6.15.16] p3:
15461 // An assignment expression has the value of the left operand after the
15462 // assignment, but is not an lvalue.
15464 Context, LHSExpr, RHSExpr, Opc,
15466 OpLoc, CurFPFeatureOverrides());
15467 QualType ResultType;
15468 switch (Opc) {
15469 case BO_Assign:
15470 ResultType = LHSExpr->getType().getUnqualifiedType();
15471 break;
15472 case BO_LT:
15473 case BO_GT:
15474 case BO_LE:
15475 case BO_GE:
15476 case BO_EQ:
15477 case BO_NE:
15478 case BO_LAnd:
15479 case BO_LOr:
15480 // These operators have a fixed result type regardless of operands.
15481 ResultType = Context.IntTy;
15482 break;
15483 case BO_Comma:
15484 ResultType = RHSExpr->getType();
15485 break;
15486 default:
15487 ResultType = Context.DependentTy;
15488 break;
15489 }
15490 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15491 VK_PRValue, OK_Ordinary, OpLoc,
15493 }
15494
15495 // Build a built-in binary operation.
15496 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15497}
15498
15500 if (T.isNull() || T->isDependentType())
15501 return false;
15502
15503 if (!Ctx.isPromotableIntegerType(T))
15504 return true;
15505
15506 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15507}
15508
15510 UnaryOperatorKind Opc, Expr *InputExpr,
15511 bool IsAfterAmp) {
15512 ExprResult Input = InputExpr;
15515 QualType resultType;
15516 bool CanOverflow = false;
15517
15518 bool ConvertHalfVec = false;
15519 if (getLangOpts().OpenCL) {
15520 QualType Ty = InputExpr->getType();
15521 // The only legal unary operation for atomics is '&'.
15522 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15523 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15524 // only with a builtin functions and therefore should be disallowed here.
15525 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15526 || Ty->isBlockPointerType())) {
15527 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15528 << InputExpr->getType()
15529 << Input.get()->getSourceRange());
15530 }
15531 }
15532
15533 if (getLangOpts().HLSL && OpLoc.isValid()) {
15534 if (Opc == UO_AddrOf)
15535 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15536 if (Opc == UO_Deref)
15537 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15538 }
15539
15540 if (InputExpr->isTypeDependent() &&
15541 InputExpr->getType()->isSpecificBuiltinType(BuiltinType::Dependent)) {
15542 resultType = Context.DependentTy;
15543 } else {
15544 switch (Opc) {
15545 case UO_PreInc:
15546 case UO_PreDec:
15547 case UO_PostInc:
15548 case UO_PostDec:
15549 resultType =
15550 CheckIncrementDecrementOperand(*this, Input.get(), VK, OK, OpLoc,
15551 Opc == UO_PreInc || Opc == UO_PostInc,
15552 Opc == UO_PreInc || Opc == UO_PreDec);
15553 CanOverflow = isOverflowingIntegerType(Context, resultType);
15554 break;
15555 case UO_AddrOf:
15556 resultType = CheckAddressOfOperand(Input, OpLoc);
15557 CheckAddressOfNoDeref(InputExpr);
15558 RecordModifiableNonNullParam(*this, InputExpr);
15559 break;
15560 case UO_Deref: {
15562 if (Input.isInvalid())
15563 return ExprError();
15564 resultType =
15565 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15566 break;
15567 }
15568 case UO_Plus:
15569 case UO_Minus:
15570 CanOverflow = Opc == UO_Minus &&
15572 Input = UsualUnaryConversions(Input.get());
15573 if (Input.isInvalid())
15574 return ExprError();
15575 // Unary plus and minus require promoting an operand of half vector to a
15576 // float vector and truncating the result back to a half vector. For now,
15577 // we do this only when HalfArgsAndReturns is set (that is, when the
15578 // target is arm or arm64).
15579 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15580
15581 // If the operand is a half vector, promote it to a float vector.
15582 if (ConvertHalfVec)
15583 Input = convertVector(Input.get(), Context.FloatTy, *this);
15584 resultType = Input.get()->getType();
15585 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15586 break;
15587 else if (resultType->isVectorType() &&
15588 // The z vector extensions don't allow + or - with bool vectors.
15589 (!Context.getLangOpts().ZVector ||
15590 resultType->castAs<VectorType>()->getVectorKind() !=
15592 break;
15593 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
15594 break;
15595 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15596 Opc == UO_Plus && resultType->isPointerType())
15597 break;
15598
15599 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15600 << resultType << Input.get()->getSourceRange());
15601
15602 case UO_Not: // bitwise complement
15603 Input = UsualUnaryConversions(Input.get());
15604 if (Input.isInvalid())
15605 return ExprError();
15606 resultType = Input.get()->getType();
15607 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15608 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15609 // C99 does not support '~' for complex conjugation.
15610 Diag(OpLoc, diag::ext_integer_complement_complex)
15611 << resultType << Input.get()->getSourceRange();
15612 else if (resultType->hasIntegerRepresentation())
15613 break;
15614 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15615 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15616 // on vector float types.
15617 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15618 if (!T->isIntegerType())
15619 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15620 << resultType << Input.get()->getSourceRange());
15621 } else {
15622 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15623 << resultType << Input.get()->getSourceRange());
15624 }
15625 break;
15626
15627 case UO_LNot: // logical negation
15628 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15630 if (Input.isInvalid())
15631 return ExprError();
15632 resultType = Input.get()->getType();
15633
15634 // Though we still have to promote half FP to float...
15635 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15636 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast)
15637 .get();
15638 resultType = Context.FloatTy;
15639 }
15640
15641 // WebAsembly tables can't be used in unary expressions.
15642 if (resultType->isPointerType() &&
15644 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15645 << resultType << Input.get()->getSourceRange());
15646 }
15647
15648 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15649 // C99 6.5.3.3p1: ok, fallthrough;
15650 if (Context.getLangOpts().CPlusPlus) {
15651 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15652 // operand contextually converted to bool.
15653 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15654 ScalarTypeToBooleanCastKind(resultType));
15655 } else if (Context.getLangOpts().OpenCL &&
15656 Context.getLangOpts().OpenCLVersion < 120) {
15657 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15658 // operate on scalar float types.
15659 if (!resultType->isIntegerType() && !resultType->isPointerType())
15660 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15661 << resultType << Input.get()->getSourceRange());
15662 }
15663 } else if (resultType->isExtVectorType()) {
15664 if (Context.getLangOpts().OpenCL &&
15666 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15667 // operate on vector float types.
15668 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15669 if (!T->isIntegerType())
15670 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15671 << resultType << Input.get()->getSourceRange());
15672 }
15673 // Vector logical not returns the signed variant of the operand type.
15674 resultType = GetSignedVectorType(resultType);
15675 break;
15676 } else if (Context.getLangOpts().CPlusPlus &&
15677 resultType->isVectorType()) {
15678 const VectorType *VTy = resultType->castAs<VectorType>();
15679 if (VTy->getVectorKind() != VectorKind::Generic)
15680 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15681 << resultType << Input.get()->getSourceRange());
15682
15683 // Vector logical not returns the signed variant of the operand type.
15684 resultType = GetSignedVectorType(resultType);
15685 break;
15686 } else {
15687 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15688 << resultType << Input.get()->getSourceRange());
15689 }
15690
15691 // LNot always has type int. C99 6.5.3.3p5.
15692 // In C++, it's bool. C++ 5.3.1p8
15693 resultType = Context.getLogicalOperationType();
15694 break;
15695 case UO_Real:
15696 case UO_Imag:
15697 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15698 // _Real maps ordinary l-values into ordinary l-values. _Imag maps
15699 // ordinary complex l-values to ordinary l-values and all other values to
15700 // r-values.
15701 if (Input.isInvalid())
15702 return ExprError();
15703 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15704 if (Input.get()->isGLValue() &&
15705 Input.get()->getObjectKind() == OK_Ordinary)
15706 VK = Input.get()->getValueKind();
15707 } else if (!getLangOpts().CPlusPlus) {
15708 // In C, a volatile scalar is read by __imag. In C++, it is not.
15709 Input = DefaultLvalueConversion(Input.get());
15710 }
15711 break;
15712 case UO_Extension:
15713 resultType = Input.get()->getType();
15714 VK = Input.get()->getValueKind();
15715 OK = Input.get()->getObjectKind();
15716 break;
15717 case UO_Coawait:
15718 // It's unnecessary to represent the pass-through operator co_await in the
15719 // AST; just return the input expression instead.
15720 assert(!Input.get()->getType()->isDependentType() &&
15721 "the co_await expression must be non-dependant before "
15722 "building operator co_await");
15723 return Input;
15724 }
15725 }
15726 if (resultType.isNull() || Input.isInvalid())
15727 return ExprError();
15728
15729 // Check for array bounds violations in the operand of the UnaryOperator,
15730 // except for the '*' and '&' operators that have to be handled specially
15731 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15732 // that are explicitly defined as valid by the standard).
15733 if (Opc != UO_AddrOf && Opc != UO_Deref)
15734 CheckArrayAccess(Input.get());
15735
15736 auto *UO =
15737 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15738 OpLoc, CanOverflow, CurFPFeatureOverrides());
15739
15740 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15741 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15743 ExprEvalContexts.back().PossibleDerefs.insert(UO);
15744
15745 // Convert the result back to a half vector.
15746 if (ConvertHalfVec)
15747 return convertVector(UO, Context.HalfTy, *this);
15748 return UO;
15749}
15750
15752 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15753 if (!DRE->getQualifier())
15754 return false;
15755
15756 ValueDecl *VD = DRE->getDecl();
15757 if (!VD->isCXXClassMember())
15758 return false;
15759
15760 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15761 return true;
15762 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
15763 return Method->isImplicitObjectMemberFunction();
15764
15765 return false;
15766 }
15767
15768 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
15769 if (!ULE->getQualifier())
15770 return false;
15771
15772 for (NamedDecl *D : ULE->decls()) {
15773 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
15774 if (Method->isImplicitObjectMemberFunction())
15775 return true;
15776 } else {
15777 // Overload set does not contain methods.
15778 break;
15779 }
15780 }
15781
15782 return false;
15783 }
15784
15785 return false;
15786}
15787
15789 UnaryOperatorKind Opc, Expr *Input,
15790 bool IsAfterAmp) {
15791 // First things first: handle placeholders so that the
15792 // overloaded-operator check considers the right type.
15793 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
15794 // Increment and decrement of pseudo-object references.
15795 if (pty->getKind() == BuiltinType::PseudoObject &&
15797 return PseudoObject().checkIncDec(S, OpLoc, Opc, Input);
15798
15799 // extension is always a builtin operator.
15800 if (Opc == UO_Extension)
15801 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15802
15803 // & gets special logic for several kinds of placeholder.
15804 // The builtin code knows what to do.
15805 if (Opc == UO_AddrOf &&
15806 (pty->getKind() == BuiltinType::Overload ||
15807 pty->getKind() == BuiltinType::UnknownAny ||
15808 pty->getKind() == BuiltinType::BoundMember))
15809 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15810
15811 // Anything else needs to be handled now.
15813 if (Result.isInvalid()) return ExprError();
15814 Input = Result.get();
15815 }
15816
15817 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
15819 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
15820 // Find all of the overloaded operators visible from this point.
15821 UnresolvedSet<16> Functions;
15823 if (S && OverOp != OO_None)
15824 LookupOverloadedOperatorName(OverOp, S, Functions);
15825
15826 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
15827 }
15828
15829 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
15830}
15831
15833 Expr *Input, bool IsAfterAmp) {
15834 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
15835 IsAfterAmp);
15836}
15837
15839 LabelDecl *TheDecl) {
15840 TheDecl->markUsed(Context);
15841 // Create the AST node. The address of a label always has type 'void*'.
15842 auto *Res = new (Context) AddrLabelExpr(
15843 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
15844
15845 if (getCurFunction())
15846 getCurFunction()->AddrLabels.push_back(Res);
15847
15848 return Res;
15849}
15850
15853 // Make sure we diagnose jumping into a statement expression.
15855}
15856
15858 // Note that function is also called by TreeTransform when leaving a
15859 // StmtExpr scope without rebuilding anything.
15860
15863}
15864
15866 SourceLocation RPLoc) {
15867 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
15868}
15869
15871 SourceLocation RPLoc, unsigned TemplateDepth) {
15872 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
15873 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
15874
15877 assert(!Cleanup.exprNeedsCleanups() &&
15878 "cleanups within StmtExpr not correctly bound!");
15880
15881 // FIXME: there are a variety of strange constraints to enforce here, for
15882 // example, it is not possible to goto into a stmt expression apparently.
15883 // More semantic analysis is needed.
15884
15885 // If there are sub-stmts in the compound stmt, take the type of the last one
15886 // as the type of the stmtexpr.
15887 QualType Ty = Context.VoidTy;
15888 bool StmtExprMayBindToTemp = false;
15889 if (!Compound->body_empty()) {
15890 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
15891 if (const auto *LastStmt =
15892 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
15893 if (const Expr *Value = LastStmt->getExprStmt()) {
15894 StmtExprMayBindToTemp = true;
15895 Ty = Value->getType();
15896 }
15897 }
15898 }
15899
15900 // FIXME: Check that expression type is complete/non-abstract; statement
15901 // expressions are not lvalues.
15902 Expr *ResStmtExpr =
15903 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
15904 if (StmtExprMayBindToTemp)
15905 return MaybeBindToTemporary(ResStmtExpr);
15906 return ResStmtExpr;
15907}
15908
15910 if (ER.isInvalid())
15911 return ExprError();
15912
15913 // Do function/array conversion on the last expression, but not
15914 // lvalue-to-rvalue. However, initialize an unqualified type.
15916 if (ER.isInvalid())
15917 return ExprError();
15918 Expr *E = ER.get();
15919
15920 if (E->isTypeDependent())
15921 return E;
15922
15923 // In ARC, if the final expression ends in a consume, splice
15924 // the consume out and bind it later. In the alternate case
15925 // (when dealing with a retainable type), the result
15926 // initialization will create a produce. In both cases the
15927 // result will be +1, and we'll need to balance that out with
15928 // a bind.
15929 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
15930 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
15931 return Cast->getSubExpr();
15932
15933 // FIXME: Provide a better location for the initialization.
15937 SourceLocation(), E);
15938}
15939
15941 TypeSourceInfo *TInfo,
15942 ArrayRef<OffsetOfComponent> Components,
15943 SourceLocation RParenLoc) {
15944 QualType ArgTy = TInfo->getType();
15945 bool Dependent = ArgTy->isDependentType();
15946 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
15947
15948 // We must have at least one component that refers to the type, and the first
15949 // one is known to be a field designator. Verify that the ArgTy represents
15950 // a struct/union/class.
15951 if (!Dependent && !ArgTy->isRecordType())
15952 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
15953 << ArgTy << TypeRange);
15954
15955 // Type must be complete per C99 7.17p3 because a declaring a variable
15956 // with an incomplete type would be ill-formed.
15957 if (!Dependent
15958 && RequireCompleteType(BuiltinLoc, ArgTy,
15959 diag::err_offsetof_incomplete_type, TypeRange))
15960 return ExprError();
15961
15962 bool DidWarnAboutNonPOD = false;
15963 QualType CurrentType = ArgTy;
15966 for (const OffsetOfComponent &OC : Components) {
15967 if (OC.isBrackets) {
15968 // Offset of an array sub-field. TODO: Should we allow vector elements?
15969 if (!CurrentType->isDependentType()) {
15970 const ArrayType *AT = Context.getAsArrayType(CurrentType);
15971 if(!AT)
15972 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
15973 << CurrentType);
15974 CurrentType = AT->getElementType();
15975 } else
15976 CurrentType = Context.DependentTy;
15977
15978 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
15979 if (IdxRval.isInvalid())
15980 return ExprError();
15981 Expr *Idx = IdxRval.get();
15982
15983 // The expression must be an integral expression.
15984 // FIXME: An integral constant expression?
15985 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
15986 !Idx->getType()->isIntegerType())
15987 return ExprError(
15988 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
15989 << Idx->getSourceRange());
15990
15991 // Record this array index.
15992 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
15993 Exprs.push_back(Idx);
15994 continue;
15995 }
15996
15997 // Offset of a field.
15998 if (CurrentType->isDependentType()) {
15999 // We have the offset of a field, but we can't look into the dependent
16000 // type. Just record the identifier of the field.
16001 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16002 CurrentType = Context.DependentTy;
16003 continue;
16004 }
16005
16006 // We need to have a complete type to look into.
16007 if (RequireCompleteType(OC.LocStart, CurrentType,
16008 diag::err_offsetof_incomplete_type))
16009 return ExprError();
16010
16011 // Look for the designated field.
16012 const RecordType *RC = CurrentType->getAs<RecordType>();
16013 if (!RC)
16014 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16015 << CurrentType);
16016 RecordDecl *RD = RC->getDecl();
16017
16018 // C++ [lib.support.types]p5:
16019 // The macro offsetof accepts a restricted set of type arguments in this
16020 // International Standard. type shall be a POD structure or a POD union
16021 // (clause 9).
16022 // C++11 [support.types]p4:
16023 // If type is not a standard-layout class (Clause 9), the results are
16024 // undefined.
16025 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16026 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16027 unsigned DiagID =
16028 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16029 : diag::ext_offsetof_non_pod_type;
16030
16031 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16032 Diag(BuiltinLoc, DiagID)
16033 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16034 DidWarnAboutNonPOD = true;
16035 }
16036 }
16037
16038 // Look for the field.
16039 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16040 LookupQualifiedName(R, RD);
16041 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16042 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16043 if (!MemberDecl) {
16044 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16045 MemberDecl = IndirectMemberDecl->getAnonField();
16046 }
16047
16048 if (!MemberDecl) {
16049 // Lookup could be ambiguous when looking up a placeholder variable
16050 // __builtin_offsetof(S, _).
16051 // In that case we would already have emitted a diagnostic
16052 if (!R.isAmbiguous())
16053 Diag(BuiltinLoc, diag::err_no_member)
16054 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16055 return ExprError();
16056 }
16057
16058 // C99 7.17p3:
16059 // (If the specified member is a bit-field, the behavior is undefined.)
16060 //
16061 // We diagnose this as an error.
16062 if (MemberDecl->isBitField()) {
16063 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16064 << MemberDecl->getDeclName()
16065 << SourceRange(BuiltinLoc, RParenLoc);
16066 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16067 return ExprError();
16068 }
16069
16070 RecordDecl *Parent = MemberDecl->getParent();
16071 if (IndirectMemberDecl)
16072 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16073
16074 // If the member was found in a base class, introduce OffsetOfNodes for
16075 // the base class indirections.
16076 CXXBasePaths Paths;
16077 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16078 Paths)) {
16079 if (Paths.getDetectedVirtual()) {
16080 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16081 << MemberDecl->getDeclName()
16082 << SourceRange(BuiltinLoc, RParenLoc);
16083 return ExprError();
16084 }
16085
16086 CXXBasePath &Path = Paths.front();
16087 for (const CXXBasePathElement &B : Path)
16088 Comps.push_back(OffsetOfNode(B.Base));
16089 }
16090
16091 if (IndirectMemberDecl) {
16092 for (auto *FI : IndirectMemberDecl->chain()) {
16093 assert(isa<FieldDecl>(FI));
16094 Comps.push_back(OffsetOfNode(OC.LocStart,
16095 cast<FieldDecl>(FI), OC.LocEnd));
16096 }
16097 } else
16098 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16099
16100 CurrentType = MemberDecl->getType().getNonReferenceType();
16101 }
16102
16103 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16104 Comps, Exprs, RParenLoc);
16105}
16106
16108 SourceLocation BuiltinLoc,
16110 ParsedType ParsedArgTy,
16111 ArrayRef<OffsetOfComponent> Components,
16112 SourceLocation RParenLoc) {
16113
16114 TypeSourceInfo *ArgTInfo;
16115 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16116 if (ArgTy.isNull())
16117 return ExprError();
16118
16119 if (!ArgTInfo)
16120 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16121
16122 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16123}
16124
16125
16127 Expr *CondExpr,
16128 Expr *LHSExpr, Expr *RHSExpr,
16129 SourceLocation RPLoc) {
16130 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16131
16134 QualType resType;
16135 bool CondIsTrue = false;
16136 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16137 resType = Context.DependentTy;
16138 } else {
16139 // The conditional expression is required to be a constant expression.
16140 llvm::APSInt condEval(32);
16142 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16143 if (CondICE.isInvalid())
16144 return ExprError();
16145 CondExpr = CondICE.get();
16146 CondIsTrue = condEval.getZExtValue();
16147
16148 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16149 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16150
16151 resType = ActiveExpr->getType();
16152 VK = ActiveExpr->getValueKind();
16153 OK = ActiveExpr->getObjectKind();
16154 }
16155
16156 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16157 resType, VK, OK, RPLoc, CondIsTrue);
16158}
16159
16160//===----------------------------------------------------------------------===//
16161// Clang Extensions.
16162//===----------------------------------------------------------------------===//
16163
16164void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16166
16167 if (LangOpts.CPlusPlus) {
16169 Decl *ManglingContextDecl;
16170 std::tie(MCtx, ManglingContextDecl) =
16171 getCurrentMangleNumberContext(Block->getDeclContext());
16172 if (MCtx) {
16173 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16174 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16175 }
16176 }
16177
16178 PushBlockScope(CurScope, Block);
16180 if (CurScope)
16181 PushDeclContext(CurScope, Block);
16182 else
16183 CurContext = Block;
16184
16186
16187 // Enter a new evaluation context to insulate the block from any
16188 // cleanups from the enclosing full-expression.
16191}
16192
16194 Scope *CurScope) {
16195 assert(ParamInfo.getIdentifier() == nullptr &&
16196 "block-id should have no identifier!");
16197 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16198 BlockScopeInfo *CurBlock = getCurBlock();
16199
16200 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16201 QualType T = Sig->getType();
16203
16204 // GetTypeForDeclarator always produces a function type for a block
16205 // literal signature. Furthermore, it is always a FunctionProtoType
16206 // unless the function was written with a typedef.
16207 assert(T->isFunctionType() &&
16208 "GetTypeForDeclarator made a non-function block signature");
16209
16210 // Look for an explicit signature in that function type.
16211 FunctionProtoTypeLoc ExplicitSignature;
16212
16213 if ((ExplicitSignature = Sig->getTypeLoc()
16215
16216 // Check whether that explicit signature was synthesized by
16217 // GetTypeForDeclarator. If so, don't save that as part of the
16218 // written signature.
16219 if (ExplicitSignature.getLocalRangeBegin() ==
16220 ExplicitSignature.getLocalRangeEnd()) {
16221 // This would be much cheaper if we stored TypeLocs instead of
16222 // TypeSourceInfos.
16223 TypeLoc Result = ExplicitSignature.getReturnLoc();
16224 unsigned Size = Result.getFullDataSize();
16225 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16226 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16227
16228 ExplicitSignature = FunctionProtoTypeLoc();
16229 }
16230 }
16231
16232 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16233 CurBlock->FunctionType = T;
16234
16235 const auto *Fn = T->castAs<FunctionType>();
16236 QualType RetTy = Fn->getReturnType();
16237 bool isVariadic =
16238 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16239
16240 CurBlock->TheDecl->setIsVariadic(isVariadic);
16241
16242 // Context.DependentTy is used as a placeholder for a missing block
16243 // return type. TODO: what should we do with declarators like:
16244 // ^ * { ... }
16245 // If the answer is "apply template argument deduction"....
16246 if (RetTy != Context.DependentTy) {
16247 CurBlock->ReturnType = RetTy;
16248 CurBlock->TheDecl->setBlockMissingReturnType(false);
16249 CurBlock->HasImplicitReturnType = false;
16250 }
16251
16252 // Push block parameters from the declarator if we had them.
16254 if (ExplicitSignature) {
16255 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16256 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16257 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16258 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16259 // Diagnose this as an extension in C17 and earlier.
16260 if (!getLangOpts().C23)
16261 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16262 }
16263 Params.push_back(Param);
16264 }
16265
16266 // Fake up parameter variables if we have a typedef, like
16267 // ^ fntype { ... }
16268 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16269 for (const auto &I : Fn->param_types()) {
16271 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16272 Params.push_back(Param);
16273 }
16274 }
16275
16276 // Set the parameters on the block decl.
16277 if (!Params.empty()) {
16278 CurBlock->TheDecl->setParams(Params);
16280 /*CheckParameterNames=*/false);
16281 }
16282
16283 // Finally we can process decl attributes.
16284 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16285
16286 // Put the parameter variables in scope.
16287 for (auto *AI : CurBlock->TheDecl->parameters()) {
16288 AI->setOwningFunction(CurBlock->TheDecl);
16289
16290 // If this has an identifier, add it to the scope stack.
16291 if (AI->getIdentifier()) {
16292 CheckShadow(CurBlock->TheScope, AI);
16293
16294 PushOnScopeChains(AI, CurBlock->TheScope);
16295 }
16296
16297 if (AI->isInvalidDecl())
16298 CurBlock->TheDecl->setInvalidDecl();
16299 }
16300}
16301
16302void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16303 // Leave the expression-evaluation context.
16306
16307 // Pop off CurBlock, handle nested blocks.
16310}
16311
16313 Stmt *Body, Scope *CurScope) {
16314 // If blocks are disabled, emit an error.
16315 if (!LangOpts.Blocks)
16316 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16317
16318 // Leave the expression-evaluation context.
16321 assert(!Cleanup.exprNeedsCleanups() &&
16322 "cleanups within block not correctly bound!");
16324
16325 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16326 BlockDecl *BD = BSI->TheDecl;
16327
16329
16330 if (BSI->HasImplicitReturnType)
16332
16333 QualType RetTy = Context.VoidTy;
16334 if (!BSI->ReturnType.isNull())
16335 RetTy = BSI->ReturnType;
16336
16337 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16338 QualType BlockTy;
16339
16340 // If the user wrote a function type in some form, try to use that.
16341 if (!BSI->FunctionType.isNull()) {
16342 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16343
16344 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16345 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16346
16347 // Turn protoless block types into nullary block types.
16348 if (isa<FunctionNoProtoType>(FTy)) {
16350 EPI.ExtInfo = Ext;
16351 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16352
16353 // Otherwise, if we don't need to change anything about the function type,
16354 // preserve its sugar structure.
16355 } else if (FTy->getReturnType() == RetTy &&
16356 (!NoReturn || FTy->getNoReturnAttr())) {
16357 BlockTy = BSI->FunctionType;
16358
16359 // Otherwise, make the minimal modifications to the function type.
16360 } else {
16361 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16363 EPI.TypeQuals = Qualifiers();
16364 EPI.ExtInfo = Ext;
16365 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16366 }
16367
16368 // If we don't have a function type, just build one from nothing.
16369 } else {
16371 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16372 BlockTy = Context.getFunctionType(RetTy, {}, EPI);
16373 }
16374
16376 BlockTy = Context.getBlockPointerType(BlockTy);
16377
16378 // If needed, diagnose invalid gotos and switches in the block.
16379 if (getCurFunction()->NeedsScopeChecking() &&
16381 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16382
16383 BD->setBody(cast<CompoundStmt>(Body));
16384
16385 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16387
16388 // Try to apply the named return value optimization. We have to check again
16389 // if we can do this, though, because blocks keep return statements around
16390 // to deduce an implicit return type.
16391 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16392 !BD->isDependentContext())
16393 computeNRVO(Body, BSI);
16394
16399
16401
16402 // Set the captured variables on the block.
16404 for (Capture &Cap : BSI->Captures) {
16405 if (Cap.isInvalid() || Cap.isThisCapture())
16406 continue;
16407 // Cap.getVariable() is always a VarDecl because
16408 // blocks cannot capture structured bindings or other ValueDecl kinds.
16409 auto *Var = cast<VarDecl>(Cap.getVariable());
16410 Expr *CopyExpr = nullptr;
16411 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16412 if (const RecordType *Record =
16413 Cap.getCaptureType()->getAs<RecordType>()) {
16414 // The capture logic needs the destructor, so make sure we mark it.
16415 // Usually this is unnecessary because most local variables have
16416 // their destructors marked at declaration time, but parameters are
16417 // an exception because it's technically only the call site that
16418 // actually requires the destructor.
16419 if (isa<ParmVarDecl>(Var))
16421
16422 // Enter a separate potentially-evaluated context while building block
16423 // initializers to isolate their cleanups from those of the block
16424 // itself.
16425 // FIXME: Is this appropriate even when the block itself occurs in an
16426 // unevaluated operand?
16429
16431
16433 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16434
16435 // According to the blocks spec, the capture of a variable from
16436 // the stack requires a const copy constructor. This is not true
16437 // of the copy/move done to move a __block variable to the heap.
16438 if (!Result.isInvalid() &&
16439 !Result.get()->getType().isConstQualified()) {
16441 Result.get()->getType().withConst(),
16442 CK_NoOp, VK_LValue);
16443 }
16444
16445 if (!Result.isInvalid()) {
16447 InitializedEntity::InitializeBlock(Var->getLocation(),
16448 Cap.getCaptureType()),
16449 Loc, Result.get());
16450 }
16451
16452 // Build a full-expression copy expression if initialization
16453 // succeeded and used a non-trivial constructor. Recover from
16454 // errors by pretending that the copy isn't necessary.
16455 if (!Result.isInvalid() &&
16456 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16457 ->isTrivial()) {
16459 CopyExpr = Result.get();
16460 }
16461 }
16462 }
16463
16464 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16465 CopyExpr);
16466 Captures.push_back(NewCap);
16467 }
16468 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16469
16470 // Pop the block scope now but keep it alive to the end of this function.
16472 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16473
16474 BlockExpr *Result = new (Context)
16475 BlockExpr(BD, BlockTy, BSI->ContainsUnexpandedParameterPack);
16476
16477 // If the block isn't obviously global, i.e. it captures anything at
16478 // all, then we need to do a few things in the surrounding context:
16479 if (Result->getBlockDecl()->hasCaptures()) {
16480 // First, this expression has a new cleanup object.
16481 ExprCleanupObjects.push_back(Result->getBlockDecl());
16483
16484 // It also gets a branch-protected scope if any of the captured
16485 // variables needs destruction.
16486 for (const auto &CI : Result->getBlockDecl()->captures()) {
16487 const VarDecl *var = CI.getVariable();
16488 if (var->getType().isDestructedType() != QualType::DK_none) {
16490 break;
16491 }
16492 }
16493 }
16494
16495 if (getCurFunction())
16496 getCurFunction()->addBlock(BD);
16497
16498 // This can happen if the block's return type is deduced, but
16499 // the return expression is invalid.
16500 if (BD->isInvalidDecl())
16501 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
16502 {Result}, Result->getType());
16503 return Result;
16504}
16505
16507 SourceLocation RPLoc) {
16508 TypeSourceInfo *TInfo;
16509 GetTypeFromParser(Ty, &TInfo);
16510 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16511}
16512
16514 Expr *E, TypeSourceInfo *TInfo,
16515 SourceLocation RPLoc) {
16516 Expr *OrigExpr = E;
16517 bool IsMS = false;
16518
16519 // CUDA device code does not support varargs.
16520 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16521 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16525 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16526 }
16527 }
16528
16529 // NVPTX does not support va_arg expression.
16530 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16531 Context.getTargetInfo().getTriple().isNVPTX())
16532 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16533
16534 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16535 // as Microsoft ABI on an actual Microsoft platform, where
16536 // __builtin_ms_va_list and __builtin_va_list are the same.)
16539 QualType MSVaListType = Context.getBuiltinMSVaListType();
16540 if (Context.hasSameType(MSVaListType, E->getType())) {
16541 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16542 return ExprError();
16543 IsMS = true;
16544 }
16545 }
16546
16547 // Get the va_list type
16548 QualType VaListType = Context.getBuiltinVaListType();
16549 if (!IsMS) {
16550 if (VaListType->isArrayType()) {
16551 // Deal with implicit array decay; for example, on x86-64,
16552 // va_list is an array, but it's supposed to decay to
16553 // a pointer for va_arg.
16554 VaListType = Context.getArrayDecayedType(VaListType);
16555 // Make sure the input expression also decays appropriately.
16557 if (Result.isInvalid())
16558 return ExprError();
16559 E = Result.get();
16560 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16561 // If va_list is a record type and we are compiling in C++ mode,
16562 // check the argument using reference binding.
16564 Context, Context.getLValueReferenceType(VaListType), false);
16566 if (Init.isInvalid())
16567 return ExprError();
16568 E = Init.getAs<Expr>();
16569 } else {
16570 // Otherwise, the va_list argument must be an l-value because
16571 // it is modified by va_arg.
16572 if (!E->isTypeDependent() &&
16573 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16574 return ExprError();
16575 }
16576 }
16577
16578 if (!IsMS && !E->isTypeDependent() &&
16579 !Context.hasSameType(VaListType, E->getType()))
16580 return ExprError(
16581 Diag(E->getBeginLoc(),
16582 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16583 << OrigExpr->getType() << E->getSourceRange());
16584
16585 if (!TInfo->getType()->isDependentType()) {
16586 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16587 diag::err_second_parameter_to_va_arg_incomplete,
16588 TInfo->getTypeLoc()))
16589 return ExprError();
16590
16592 TInfo->getType(),
16593 diag::err_second_parameter_to_va_arg_abstract,
16594 TInfo->getTypeLoc()))
16595 return ExprError();
16596
16597 if (!TInfo->getType().isPODType(Context)) {
16598 Diag(TInfo->getTypeLoc().getBeginLoc(),
16599 TInfo->getType()->isObjCLifetimeType()
16600 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16601 : diag::warn_second_parameter_to_va_arg_not_pod)
16602 << TInfo->getType()
16603 << TInfo->getTypeLoc().getSourceRange();
16604 }
16605
16606 if (TInfo->getType()->isArrayType()) {
16608 PDiag(diag::warn_second_parameter_to_va_arg_array)
16609 << TInfo->getType()
16610 << TInfo->getTypeLoc().getSourceRange());
16611 }
16612
16613 // Check for va_arg where arguments of the given type will be promoted
16614 // (i.e. this va_arg is guaranteed to have undefined behavior).
16615 QualType PromoteType;
16616 if (Context.isPromotableIntegerType(TInfo->getType())) {
16617 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16618 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16619 // and C23 7.16.1.1p2 says, in part:
16620 // If type is not compatible with the type of the actual next argument
16621 // (as promoted according to the default argument promotions), the
16622 // behavior is undefined, except for the following cases:
16623 // - both types are pointers to qualified or unqualified versions of
16624 // compatible types;
16625 // - one type is compatible with a signed integer type, the other
16626 // type is compatible with the corresponding unsigned integer type,
16627 // and the value is representable in both types;
16628 // - one type is pointer to qualified or unqualified void and the
16629 // other is a pointer to a qualified or unqualified character type;
16630 // - or, the type of the next argument is nullptr_t and type is a
16631 // pointer type that has the same representation and alignment
16632 // requirements as a pointer to a character type.
16633 // Given that type compatibility is the primary requirement (ignoring
16634 // qualifications), you would think we could call typesAreCompatible()
16635 // directly to test this. However, in C++, that checks for *same type*,
16636 // which causes false positives when passing an enumeration type to
16637 // va_arg. Instead, get the underlying type of the enumeration and pass
16638 // that.
16639 QualType UnderlyingType = TInfo->getType();
16640 if (const auto *ET = UnderlyingType->getAs<EnumType>())
16641 UnderlyingType = ET->getDecl()->getIntegerType();
16642 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16643 /*CompareUnqualified*/ true))
16644 PromoteType = QualType();
16645
16646 // If the types are still not compatible, we need to test whether the
16647 // promoted type and the underlying type are the same except for
16648 // signedness. Ask the AST for the correctly corresponding type and see
16649 // if that's compatible.
16650 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16651 PromoteType->isUnsignedIntegerType() !=
16652 UnderlyingType->isUnsignedIntegerType()) {
16653 UnderlyingType =
16654 UnderlyingType->isUnsignedIntegerType()
16655 ? Context.getCorrespondingSignedType(UnderlyingType)
16656 : Context.getCorrespondingUnsignedType(UnderlyingType);
16657 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16658 /*CompareUnqualified*/ true))
16659 PromoteType = QualType();
16660 }
16661 }
16662 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16663 PromoteType = Context.DoubleTy;
16664 if (!PromoteType.isNull())
16666 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16667 << TInfo->getType()
16668 << PromoteType
16669 << TInfo->getTypeLoc().getSourceRange());
16670 }
16671
16673 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16674}
16675
16677 // The type of __null will be int or long, depending on the size of
16678 // pointers on the target.
16679 QualType Ty;
16681 if (pw == Context.getTargetInfo().getIntWidth())
16682 Ty = Context.IntTy;
16683 else if (pw == Context.getTargetInfo().getLongWidth())
16684 Ty = Context.LongTy;
16685 else if (pw == Context.getTargetInfo().getLongLongWidth())
16686 Ty = Context.LongLongTy;
16687 else {
16688 llvm_unreachable("I don't know size of pointer!");
16689 }
16690
16691 return new (Context) GNUNullExpr(Ty, TokenLoc);
16692}
16693
16695 CXXRecordDecl *ImplDecl = nullptr;
16696
16697 // Fetch the std::source_location::__impl decl.
16698 if (NamespaceDecl *Std = S.getStdNamespace()) {
16699 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16701 if (S.LookupQualifiedName(ResultSL, Std)) {
16702 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16703 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16705 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16706 S.LookupQualifiedName(ResultImpl, SLDecl)) {
16707 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16708 }
16709 }
16710 }
16711 }
16712
16713 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16714 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16715 return nullptr;
16716 }
16717
16718 // Verify that __impl is a trivial struct type, with no base classes, and with
16719 // only the four expected fields.
16720 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16721 ImplDecl->getNumBases() != 0) {
16722 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16723 return nullptr;
16724 }
16725
16726 unsigned Count = 0;
16727 for (FieldDecl *F : ImplDecl->fields()) {
16728 StringRef Name = F->getName();
16729
16730 if (Name == "_M_file_name") {
16731 if (F->getType() !=
16733 break;
16734 Count++;
16735 } else if (Name == "_M_function_name") {
16736 if (F->getType() !=
16738 break;
16739 Count++;
16740 } else if (Name == "_M_line") {
16741 if (!F->getType()->isIntegerType())
16742 break;
16743 Count++;
16744 } else if (Name == "_M_column") {
16745 if (!F->getType()->isIntegerType())
16746 break;
16747 Count++;
16748 } else {
16749 Count = 100; // invalid
16750 break;
16751 }
16752 }
16753 if (Count != 4) {
16754 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16755 return nullptr;
16756 }
16757
16758 return ImplDecl;
16759}
16760
16762 SourceLocation BuiltinLoc,
16763 SourceLocation RPLoc) {
16764 QualType ResultTy;
16765 switch (Kind) {
16771 ResultTy =
16773 break;
16774 }
16777 ResultTy = Context.UnsignedIntTy;
16778 break;
16782 LookupStdSourceLocationImpl(*this, BuiltinLoc);
16784 return ExprError();
16785 }
16786 ResultTy = Context.getPointerType(
16788 break;
16789 }
16790
16791 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
16792}
16793
16795 SourceLocation BuiltinLoc,
16796 SourceLocation RPLoc,
16797 DeclContext *ParentContext) {
16798 return new (Context)
16799 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
16800}
16801
16803 StringLiteral *BinaryData) {
16805 Data->BinaryData = BinaryData;
16806 return new (Context)
16807 EmbedExpr(Context, EmbedKeywordLoc, Data, /*NumOfElements=*/0,
16808 Data->getDataElementCount());
16809}
16810
16812 const Expr *SrcExpr) {
16813 if (!DstType->isFunctionPointerType() ||
16814 !SrcExpr->getType()->isFunctionType())
16815 return false;
16816
16817 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
16818 if (!DRE)
16819 return false;
16820
16821 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
16822 if (!FD)
16823 return false;
16824
16826 /*Complain=*/true,
16827 SrcExpr->getBeginLoc());
16828}
16829
16832 QualType DstType, QualType SrcType,
16833 Expr *SrcExpr, AssignmentAction Action,
16834 bool *Complained) {
16835 if (Complained)
16836 *Complained = false;
16837
16838 // Decode the result (notice that AST's are still created for extensions).
16839 bool CheckInferredResultType = false;
16840 bool isInvalid = false;
16841 unsigned DiagKind = 0;
16842 ConversionFixItGenerator ConvHints;
16843 bool MayHaveConvFixit = false;
16844 bool MayHaveFunctionDiff = false;
16845 const ObjCInterfaceDecl *IFace = nullptr;
16846 const ObjCProtocolDecl *PDecl = nullptr;
16847
16848 switch (ConvTy) {
16849 case Compatible:
16850 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
16851 return false;
16852
16853 case PointerToInt:
16854 if (getLangOpts().CPlusPlus) {
16855 DiagKind = diag::err_typecheck_convert_pointer_int;
16856 isInvalid = true;
16857 } else {
16858 DiagKind = diag::ext_typecheck_convert_pointer_int;
16859 }
16860 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16861 MayHaveConvFixit = true;
16862 break;
16863 case IntToPointer:
16864 if (getLangOpts().CPlusPlus) {
16865 DiagKind = diag::err_typecheck_convert_int_pointer;
16866 isInvalid = true;
16867 } else {
16868 DiagKind = diag::ext_typecheck_convert_int_pointer;
16869 }
16870 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16871 MayHaveConvFixit = true;
16872 break;
16874 DiagKind =
16875 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
16876 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16877 MayHaveConvFixit = true;
16878 break;
16880 if (getLangOpts().CPlusPlus) {
16881 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
16882 isInvalid = true;
16883 } else {
16884 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
16885 }
16886 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16887 MayHaveConvFixit = true;
16888 break;
16891 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
16892 } else if (getLangOpts().CPlusPlus) {
16893 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
16894 isInvalid = true;
16895 } else {
16896 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
16897 }
16898 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
16899 SrcType->isObjCObjectPointerType();
16900 if (CheckInferredResultType) {
16901 SrcType = SrcType.getUnqualifiedType();
16902 DstType = DstType.getUnqualifiedType();
16903 } else {
16904 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
16905 }
16906 MayHaveConvFixit = true;
16907 break;
16909 if (getLangOpts().CPlusPlus) {
16910 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
16911 isInvalid = true;
16912 } else {
16913 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
16914 }
16915 break;
16917 if (getLangOpts().CPlusPlus) {
16918 DiagKind = diag::err_typecheck_convert_pointer_void_func;
16919 isInvalid = true;
16920 } else {
16921 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
16922 }
16923 break;
16925 // Perform array-to-pointer decay if necessary.
16926 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
16927
16928 isInvalid = true;
16929
16930 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
16931 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
16932 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
16933 DiagKind = diag::err_typecheck_incompatible_address_space;
16934 break;
16935 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
16936 DiagKind = diag::err_typecheck_incompatible_ownership;
16937 break;
16938 }
16939
16940 llvm_unreachable("unknown error case for discarding qualifiers!");
16941 // fallthrough
16942 }
16944 // If the qualifiers lost were because we were applying the
16945 // (deprecated) C++ conversion from a string literal to a char*
16946 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
16947 // Ideally, this check would be performed in
16948 // checkPointerTypesForAssignment. However, that would require a
16949 // bit of refactoring (so that the second argument is an
16950 // expression, rather than a type), which should be done as part
16951 // of a larger effort to fix checkPointerTypesForAssignment for
16952 // C++ semantics.
16953 if (getLangOpts().CPlusPlus &&
16955 return false;
16956 if (getLangOpts().CPlusPlus) {
16957 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
16958 isInvalid = true;
16959 } else {
16960 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
16961 }
16962
16963 break;
16965 if (getLangOpts().CPlusPlus) {
16966 isInvalid = true;
16967 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
16968 } else {
16969 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
16970 }
16971 break;
16973 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
16974 isInvalid = true;
16975 break;
16976 case IntToBlockPointer:
16977 DiagKind = diag::err_int_to_block_pointer;
16978 isInvalid = true;
16979 break;
16981 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
16982 isInvalid = true;
16983 break;
16985 if (SrcType->isObjCQualifiedIdType()) {
16986 const ObjCObjectPointerType *srcOPT =
16987 SrcType->castAs<ObjCObjectPointerType>();
16988 for (auto *srcProto : srcOPT->quals()) {
16989 PDecl = srcProto;
16990 break;
16991 }
16992 if (const ObjCInterfaceType *IFaceT =
16994 IFace = IFaceT->getDecl();
16995 }
16996 else if (DstType->isObjCQualifiedIdType()) {
16997 const ObjCObjectPointerType *dstOPT =
16998 DstType->castAs<ObjCObjectPointerType>();
16999 for (auto *dstProto : dstOPT->quals()) {
17000 PDecl = dstProto;
17001 break;
17002 }
17003 if (const ObjCInterfaceType *IFaceT =
17005 IFace = IFaceT->getDecl();
17006 }
17007 if (getLangOpts().CPlusPlus) {
17008 DiagKind = diag::err_incompatible_qualified_id;
17009 isInvalid = true;
17010 } else {
17011 DiagKind = diag::warn_incompatible_qualified_id;
17012 }
17013 break;
17014 }
17016 if (getLangOpts().CPlusPlus) {
17017 DiagKind = diag::err_incompatible_vectors;
17018 isInvalid = true;
17019 } else {
17020 DiagKind = diag::warn_incompatible_vectors;
17021 }
17022 break;
17024 DiagKind = diag::err_arc_weak_unavailable_assign;
17025 isInvalid = true;
17026 break;
17027 case Incompatible:
17028 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17029 if (Complained)
17030 *Complained = true;
17031 return true;
17032 }
17033
17034 DiagKind = diag::err_typecheck_convert_incompatible;
17035 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17036 MayHaveConvFixit = true;
17037 isInvalid = true;
17038 MayHaveFunctionDiff = true;
17039 break;
17040 }
17041
17042 QualType FirstType, SecondType;
17043 switch (Action) {
17046 // The destination type comes first.
17047 FirstType = DstType;
17048 SecondType = SrcType;
17049 break;
17050
17057 // The source type comes first.
17058 FirstType = SrcType;
17059 SecondType = DstType;
17060 break;
17061 }
17062
17063 PartialDiagnostic FDiag = PDiag(DiagKind);
17064 AssignmentAction ActionForDiag = Action;
17066 ActionForDiag = AssignmentAction::Passing;
17067
17068 FDiag << FirstType << SecondType << ActionForDiag
17069 << SrcExpr->getSourceRange();
17070
17071 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17072 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17073 auto isPlainChar = [](const clang::Type *Type) {
17074 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17075 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17076 };
17077 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17078 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17079 }
17080
17081 // If we can fix the conversion, suggest the FixIts.
17082 if (!ConvHints.isNull()) {
17083 for (FixItHint &H : ConvHints.Hints)
17084 FDiag << H;
17085 }
17086
17087 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17088
17089 if (MayHaveFunctionDiff)
17090 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17091
17092 Diag(Loc, FDiag);
17093 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17094 DiagKind == diag::err_incompatible_qualified_id) &&
17095 PDecl && IFace && !IFace->hasDefinition())
17096 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17097 << IFace << PDecl;
17098
17099 if (SecondType == Context.OverloadTy)
17101 FirstType, /*TakingAddress=*/true);
17102
17103 if (CheckInferredResultType)
17105
17106 if (Action == AssignmentAction::Returning && ConvTy == IncompatiblePointer)
17108
17109 if (Complained)
17110 *Complained = true;
17111 return isInvalid;
17112}
17113
17115 llvm::APSInt *Result,
17116 AllowFoldKind CanFold) {
17117 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17118 public:
17119 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17120 QualType T) override {
17121 return S.Diag(Loc, diag::err_ice_not_integral)
17122 << T << S.LangOpts.CPlusPlus;
17123 }
17124 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17125 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17126 }
17127 } Diagnoser;
17128
17129 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17130}
17131
17133 llvm::APSInt *Result,
17134 unsigned DiagID,
17135 AllowFoldKind CanFold) {
17136 class IDDiagnoser : public VerifyICEDiagnoser {
17137 unsigned DiagID;
17138
17139 public:
17140 IDDiagnoser(unsigned DiagID)
17141 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17142
17143 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17144 return S.Diag(Loc, DiagID);
17145 }
17146 } Diagnoser(DiagID);
17147
17148 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17149}
17150
17153 QualType T) {
17154 return diagnoseNotICE(S, Loc);
17155}
17156
17159 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17160}
17161
17164 VerifyICEDiagnoser &Diagnoser,
17165 AllowFoldKind CanFold) {
17166 SourceLocation DiagLoc = E->getBeginLoc();
17167
17168 if (getLangOpts().CPlusPlus11) {
17169 // C++11 [expr.const]p5:
17170 // If an expression of literal class type is used in a context where an
17171 // integral constant expression is required, then that class type shall
17172 // have a single non-explicit conversion function to an integral or
17173 // unscoped enumeration type
17174 ExprResult Converted;
17175 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17176 VerifyICEDiagnoser &BaseDiagnoser;
17177 public:
17178 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17179 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17180 BaseDiagnoser.Suppress, true),
17181 BaseDiagnoser(BaseDiagnoser) {}
17182
17183 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17184 QualType T) override {
17185 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17186 }
17187
17188 SemaDiagnosticBuilder diagnoseIncomplete(
17189 Sema &S, SourceLocation Loc, QualType T) override {
17190 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17191 }
17192
17193 SemaDiagnosticBuilder diagnoseExplicitConv(
17194 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17195 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17196 }
17197
17198 SemaDiagnosticBuilder noteExplicitConv(
17199 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17200 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17201 << ConvTy->isEnumeralType() << ConvTy;
17202 }
17203
17204 SemaDiagnosticBuilder diagnoseAmbiguous(
17205 Sema &S, SourceLocation Loc, QualType T) override {
17206 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17207 }
17208
17209 SemaDiagnosticBuilder noteAmbiguous(
17210 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17211 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17212 << ConvTy->isEnumeralType() << ConvTy;
17213 }
17214
17215 SemaDiagnosticBuilder diagnoseConversion(
17216 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17217 llvm_unreachable("conversion functions are permitted");
17218 }
17219 } ConvertDiagnoser(Diagnoser);
17220
17221 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17222 ConvertDiagnoser);
17223 if (Converted.isInvalid())
17224 return Converted;
17225 E = Converted.get();
17226 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17227 // don't try to evaluate it later. We also don't want to return the
17228 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17229 // this function will attempt to use 'Value'.
17230 if (isa<RecoveryExpr>(E))
17231 return ExprError();
17233 return ExprError();
17234 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17235 // An ICE must be of integral or unscoped enumeration type.
17236 if (!Diagnoser.Suppress)
17237 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17238 << E->getSourceRange();
17239 return ExprError();
17240 }
17241
17242 ExprResult RValueExpr = DefaultLvalueConversion(E);
17243 if (RValueExpr.isInvalid())
17244 return ExprError();
17245
17246 E = RValueExpr.get();
17247
17248 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17249 // in the non-ICE case.
17252 if (Result)
17254 if (!isa<ConstantExpr>(E))
17257
17258 if (Notes.empty())
17259 return E;
17260
17261 // If our only note is the usual "invalid subexpression" note, just point
17262 // the caret at its location rather than producing an essentially
17263 // redundant note.
17264 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17265 diag::note_invalid_subexpr_in_const_expr) {
17266 DiagLoc = Notes[0].first;
17267 Notes.clear();
17268 }
17269
17270 if (getLangOpts().CPlusPlus) {
17271 if (!Diagnoser.Suppress) {
17272 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17273 for (const PartialDiagnosticAt &Note : Notes)
17274 Diag(Note.first, Note.second);
17275 }
17276 return ExprError();
17277 }
17278
17279 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17280 for (const PartialDiagnosticAt &Note : Notes)
17281 Diag(Note.first, Note.second);
17282
17283 return E;
17284 }
17285
17286 Expr::EvalResult EvalResult;
17288 EvalResult.Diag = &Notes;
17289
17290 // Try to evaluate the expression, and produce diagnostics explaining why it's
17291 // not a constant expression as a side-effect.
17292 bool Folded =
17293 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17294 EvalResult.Val.isInt() && !EvalResult.HasSideEffects &&
17295 (!getLangOpts().CPlusPlus || !EvalResult.HasUndefinedBehavior);
17296
17297 if (!isa<ConstantExpr>(E))
17298 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17299
17300 // In C++11, we can rely on diagnostics being produced for any expression
17301 // which is not a constant expression. If no diagnostics were produced, then
17302 // this is a constant expression.
17303 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17304 if (Result)
17305 *Result = EvalResult.Val.getInt();
17306 return E;
17307 }
17308
17309 // If our only note is the usual "invalid subexpression" note, just point
17310 // the caret at its location rather than producing an essentially
17311 // redundant note.
17312 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17313 diag::note_invalid_subexpr_in_const_expr) {
17314 DiagLoc = Notes[0].first;
17315 Notes.clear();
17316 }
17317
17318 if (!Folded || !CanFold) {
17319 if (!Diagnoser.Suppress) {
17320 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17321 for (const PartialDiagnosticAt &Note : Notes)
17322 Diag(Note.first, Note.second);
17323 }
17324
17325 return ExprError();
17326 }
17327
17328 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17329 for (const PartialDiagnosticAt &Note : Notes)
17330 Diag(Note.first, Note.second);
17331
17332 if (Result)
17333 *Result = EvalResult.Val.getInt();
17334 return E;
17335}
17336
17337namespace {
17338 // Handle the case where we conclude a expression which we speculatively
17339 // considered to be unevaluated is actually evaluated.
17340 class TransformToPE : public TreeTransform<TransformToPE> {
17341 typedef TreeTransform<TransformToPE> BaseTransform;
17342
17343 public:
17344 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17345
17346 // Make sure we redo semantic analysis
17347 bool AlwaysRebuild() { return true; }
17348 bool ReplacingOriginal() { return true; }
17349
17350 // We need to special-case DeclRefExprs referring to FieldDecls which
17351 // are not part of a member pointer formation; normal TreeTransforming
17352 // doesn't catch this case because of the way we represent them in the AST.
17353 // FIXME: This is a bit ugly; is it really the best way to handle this
17354 // case?
17355 //
17356 // Error on DeclRefExprs referring to FieldDecls.
17357 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17358 if (isa<FieldDecl>(E->getDecl()) &&
17359 !SemaRef.isUnevaluatedContext())
17360 return SemaRef.Diag(E->getLocation(),
17361 diag::err_invalid_non_static_member_use)
17362 << E->getDecl() << E->getSourceRange();
17363
17364 return BaseTransform::TransformDeclRefExpr(E);
17365 }
17366
17367 // Exception: filter out member pointer formation
17368 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17369 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17370 return E;
17371
17372 return BaseTransform::TransformUnaryOperator(E);
17373 }
17374
17375 // The body of a lambda-expression is in a separate expression evaluation
17376 // context so never needs to be transformed.
17377 // FIXME: Ideally we wouldn't transform the closure type either, and would
17378 // just recreate the capture expressions and lambda expression.
17379 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17380 return SkipLambdaBody(E, Body);
17381 }
17382 };
17383}
17384
17386 assert(isUnevaluatedContext() &&
17387 "Should only transform unevaluated expressions");
17388 ExprEvalContexts.back().Context =
17389 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17391 return E;
17392 return TransformToPE(*this).TransformExpr(E);
17393}
17394
17396 assert(isUnevaluatedContext() &&
17397 "Should only transform unevaluated expressions");
17400 return TInfo;
17401 return TransformToPE(*this).TransformType(TInfo);
17402}
17403
17404void
17406 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17408 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17409 LambdaContextDecl, ExprContext);
17410
17411 // Discarded statements and immediate contexts nested in other
17412 // discarded statements or immediate context are themselves
17413 // a discarded statement or an immediate context, respectively.
17414 ExprEvalContexts.back().InDiscardedStatement =
17416
17417 // C++23 [expr.const]/p15
17418 // An expression or conversion is in an immediate function context if [...]
17419 // it is a subexpression of a manifestly constant-evaluated expression or
17420 // conversion.
17421 const auto &Prev = parentEvaluationContext();
17422 ExprEvalContexts.back().InImmediateFunctionContext =
17423 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17424
17425 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17426 Prev.InImmediateEscalatingFunctionContext;
17427
17428 Cleanup.reset();
17429 if (!MaybeODRUseExprs.empty())
17430 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17431}
17432
17433void
17437 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17438 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17439}
17440
17441namespace {
17442
17443const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17444 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17445 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17446 if (E->getOpcode() == UO_Deref)
17447 return CheckPossibleDeref(S, E->getSubExpr());
17448 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17449 return CheckPossibleDeref(S, E->getBase());
17450 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17451 return CheckPossibleDeref(S, E->getBase());
17452 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17453 QualType Inner;
17454 QualType Ty = E->getType();
17455 if (const auto *Ptr = Ty->getAs<PointerType>())
17456 Inner = Ptr->getPointeeType();
17457 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17458 Inner = Arr->getElementType();
17459 else
17460 return nullptr;
17461
17462 if (Inner->hasAttr(attr::NoDeref))
17463 return E;
17464 }
17465 return nullptr;
17466}
17467
17468} // namespace
17469
17471 for (const Expr *E : Rec.PossibleDerefs) {
17472 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17473 if (DeclRef) {
17474 const ValueDecl *Decl = DeclRef->getDecl();
17475 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17476 << Decl->getName() << E->getSourceRange();
17477 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17478 } else {
17479 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17480 << E->getSourceRange();
17481 }
17482 }
17483 Rec.PossibleDerefs.clear();
17484}
17485
17488 return;
17489
17490 // Note: ignoring parens here is not justified by the standard rules, but
17491 // ignoring parentheses seems like a more reasonable approach, and this only
17492 // drives a deprecation warning so doesn't affect conformance.
17493 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17494 if (BO->getOpcode() == BO_Assign) {
17495 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17496 llvm::erase(LHSs, BO->getLHS());
17497 }
17498 }
17499}
17500
17502 assert(getLangOpts().CPlusPlus20 &&
17503 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17504 "Cannot mark an immediate escalating expression outside of an "
17505 "immediate escalating context");
17506 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
17507 Call && Call->getCallee()) {
17508 if (auto *DeclRef =
17509 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17510 DeclRef->setIsImmediateEscalating(true);
17511 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
17512 Ctr->setIsImmediateEscalating(true);
17513 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
17514 DeclRef->setIsImmediateEscalating(true);
17515 } else {
17516 assert(false && "expected an immediately escalating expression");
17517 }
17519 FI->FoundImmediateEscalatingExpression = true;
17520}
17521
17523 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17524 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
17527 return E;
17528
17529 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17530 /// It's OK if this fails; we'll also remove this in
17531 /// HandleImmediateInvocations, but catching it here allows us to avoid
17532 /// walking the AST looking for it in simple cases.
17533 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17534 if (auto *DeclRef =
17535 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17536 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17537
17538 // C++23 [expr.const]/p16
17539 // An expression or conversion is immediate-escalating if it is not initially
17540 // in an immediate function context and it is [...] an immediate invocation
17541 // that is not a constant expression and is not a subexpression of an
17542 // immediate invocation.
17543 APValue Cached;
17544 auto CheckConstantExpressionAndKeepResult = [&]() {
17546 Expr::EvalResult Eval;
17547 Eval.Diag = &Notes;
17548 bool Res = E.get()->EvaluateAsConstantExpr(
17549 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
17550 if (Res && Notes.empty()) {
17551 Cached = std::move(Eval.Val);
17552 return true;
17553 }
17554 return false;
17555 };
17556
17557 if (!E.get()->isValueDependent() &&
17558 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17559 !CheckConstantExpressionAndKeepResult()) {
17561 return E;
17562 }
17563
17564 if (Cleanup.exprNeedsCleanups()) {
17565 // Since an immediate invocation is a full expression itself - it requires
17566 // an additional ExprWithCleanups node, but it can participate to a bigger
17567 // full expression which actually requires cleanups to be run after so
17568 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
17569 // may discard cleanups for outer expression too early.
17570
17571 // Note that ExprWithCleanups created here must always have empty cleanup
17572 // objects:
17573 // - compound literals do not create cleanup objects in C++ and immediate
17574 // invocations are C++-only.
17575 // - blocks are not allowed inside constant expressions and compiler will
17576 // issue an error if they appear there.
17577 //
17578 // Hence, in correct code any cleanup objects created inside current
17579 // evaluation context must be outside the immediate invocation.
17582 }
17583
17585 getASTContext(), E.get(),
17586 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17587 getASTContext()),
17588 /*IsImmediateInvocation*/ true);
17589 if (Cached.hasValue())
17590 Res->MoveIntoResult(Cached, getASTContext());
17591 /// Value-dependent constant expressions should not be immediately
17592 /// evaluated until they are instantiated.
17593 if (!Res->isValueDependent())
17594 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17595 return Res;
17596}
17597
17601 Expr::EvalResult Eval;
17602 Eval.Diag = &Notes;
17603 ConstantExpr *CE = Candidate.getPointer();
17604 bool Result = CE->EvaluateAsConstantExpr(
17605 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17606 if (!Result || !Notes.empty()) {
17608 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17609 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17610 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
17611 FunctionDecl *FD = nullptr;
17612 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17613 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17614 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17615 FD = Call->getConstructor();
17616 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
17617 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
17618
17619 assert(FD && FD->isImmediateFunction() &&
17620 "could not find an immediate function in this expression");
17621 if (FD->isInvalidDecl())
17622 return;
17623 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
17624 << FD << FD->isConsteval();
17625 if (auto Context =
17627 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17628 << Context->Decl;
17629 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17630 }
17631 if (!FD->isConsteval())
17633 for (auto &Note : Notes)
17634 SemaRef.Diag(Note.first, Note.second);
17635 return;
17636 }
17638}
17639
17643 struct ComplexRemove : TreeTransform<ComplexRemove> {
17645 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17648 CurrentII;
17649 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17652 4>::reverse_iterator Current)
17653 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17654 void RemoveImmediateInvocation(ConstantExpr* E) {
17655 auto It = std::find_if(CurrentII, IISet.rend(),
17657 return Elem.getPointer() == E;
17658 });
17659 // It is possible that some subexpression of the current immediate
17660 // invocation was handled from another expression evaluation context. Do
17661 // not handle the current immediate invocation if some of its
17662 // subexpressions failed before.
17663 if (It == IISet.rend()) {
17664 if (SemaRef.FailedImmediateInvocations.contains(E))
17665 CurrentII->setInt(1);
17666 } else {
17667 It->setInt(1); // Mark as deleted
17668 }
17669 }
17670 ExprResult TransformConstantExpr(ConstantExpr *E) {
17671 if (!E->isImmediateInvocation())
17672 return Base::TransformConstantExpr(E);
17673 RemoveImmediateInvocation(E);
17674 return Base::TransformExpr(E->getSubExpr());
17675 }
17676 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17677 /// we need to remove its DeclRefExpr from the DRSet.
17678 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17679 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17680 return Base::TransformCXXOperatorCallExpr(E);
17681 }
17682 /// Base::TransformUserDefinedLiteral doesn't preserve the
17683 /// UserDefinedLiteral node.
17684 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
17685 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
17686 /// here.
17687 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17688 if (!Init)
17689 return Init;
17690
17691 // We cannot use IgnoreImpCasts because we need to preserve
17692 // full expressions.
17693 while (true) {
17694 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Init))
17695 Init = ICE->getSubExpr();
17696 else if (auto *ICE = dyn_cast<MaterializeTemporaryExpr>(Init))
17697 Init = ICE->getSubExpr();
17698 else
17699 break;
17700 }
17701 /// ConstantExprs are the first layer of implicit node to be removed so if
17702 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17703 if (auto *CE = dyn_cast<ConstantExpr>(Init);
17704 CE && CE->isImmediateInvocation())
17705 RemoveImmediateInvocation(CE);
17706 return Base::TransformInitializer(Init, NotCopyInit);
17707 }
17708 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17709 DRSet.erase(E);
17710 return E;
17711 }
17712 ExprResult TransformLambdaExpr(LambdaExpr *E) {
17713 // Do not rebuild lambdas to avoid creating a new type.
17714 // Lambdas have already been processed inside their eval contexts.
17715 return E;
17716 }
17717 bool AlwaysRebuild() { return false; }
17718 bool ReplacingOriginal() { return true; }
17719 bool AllowSkippingCXXConstructExpr() {
17720 bool Res = AllowSkippingFirstCXXConstructExpr;
17721 AllowSkippingFirstCXXConstructExpr = true;
17722 return Res;
17723 }
17724 bool AllowSkippingFirstCXXConstructExpr = true;
17725 } Transformer(SemaRef, Rec.ReferenceToConsteval,
17727
17728 /// CXXConstructExpr with a single argument are getting skipped by
17729 /// TreeTransform in some situtation because they could be implicit. This
17730 /// can only occur for the top-level CXXConstructExpr because it is used
17731 /// nowhere in the expression being transformed therefore will not be rebuilt.
17732 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17733 /// skipping the first CXXConstructExpr.
17734 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17735 Transformer.AllowSkippingFirstCXXConstructExpr = false;
17736
17737 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17738 // The result may not be usable in case of previous compilation errors.
17739 // In this case evaluation of the expression may result in crash so just
17740 // don't do anything further with the result.
17741 if (Res.isUsable()) {
17743 It->getPointer()->setSubExpr(Res.get());
17744 }
17745}
17746
17747static void
17750 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
17751 Rec.ReferenceToConsteval.size() == 0) ||
17753 return;
17754
17755 /// When we have more than 1 ImmediateInvocationCandidates or previously
17756 /// failed immediate invocations, we need to check for nested
17757 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
17758 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
17759 /// invocation.
17760 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
17762
17763 /// Prevent sema calls during the tree transform from adding pointers that
17764 /// are already in the sets.
17765 llvm::SaveAndRestore DisableIITracking(
17767
17768 /// Prevent diagnostic during tree transfrom as they are duplicates
17770
17771 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
17772 It != Rec.ImmediateInvocationCandidates.rend(); It++)
17773 if (!It->getInt())
17775 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
17776 Rec.ReferenceToConsteval.size()) {
17777 struct SimpleRemove : DynamicRecursiveASTVisitor {
17778 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17779 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
17780 bool VisitDeclRefExpr(DeclRefExpr *E) override {
17781 DRSet.erase(E);
17782 return DRSet.size();
17783 }
17784 } Visitor(Rec.ReferenceToConsteval);
17785 Visitor.TraverseStmt(
17786 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
17787 }
17788 for (auto CE : Rec.ImmediateInvocationCandidates)
17789 if (!CE.getInt())
17791 for (auto *DR : Rec.ReferenceToConsteval) {
17792 // If the expression is immediate escalating, it is not an error;
17793 // The outer context itself becomes immediate and further errors,
17794 // if any, will be handled by DiagnoseImmediateEscalatingReason.
17795 if (DR->isImmediateEscalating())
17796 continue;
17797 auto *FD = cast<FunctionDecl>(DR->getDecl());
17798 const NamedDecl *ND = FD;
17799 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
17800 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
17801 ND = MD->getParent();
17802
17803 // C++23 [expr.const]/p16
17804 // An expression or conversion is immediate-escalating if it is not
17805 // initially in an immediate function context and it is [...] a
17806 // potentially-evaluated id-expression that denotes an immediate function
17807 // that is not a subexpression of an immediate invocation.
17808 bool ImmediateEscalating = false;
17809 bool IsPotentiallyEvaluated =
17810 Rec.Context ==
17812 Rec.Context ==
17814 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
17815 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
17816
17818 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
17819 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
17820 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
17821 if (!FD->getBuiltinID())
17822 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
17823 if (auto Context =
17825 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17826 << Context->Decl;
17827 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17828 }
17829 if (FD->isImmediateEscalating() && !FD->isConsteval())
17831
17832 } else {
17834 }
17835 }
17836}
17837
17840 unsigned NumTypos = Rec.NumTypos;
17841
17842 if (!Rec.Lambdas.empty()) {
17844 if (!getLangOpts().CPlusPlus20 &&
17845 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
17846 Rec.isUnevaluated() ||
17848 unsigned D;
17849 if (Rec.isUnevaluated()) {
17850 // C++11 [expr.prim.lambda]p2:
17851 // A lambda-expression shall not appear in an unevaluated operand
17852 // (Clause 5).
17853 D = diag::err_lambda_unevaluated_operand;
17854 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
17855 // C++1y [expr.const]p2:
17856 // A conditional-expression e is a core constant expression unless the
17857 // evaluation of e, following the rules of the abstract machine, would
17858 // evaluate [...] a lambda-expression.
17859 D = diag::err_lambda_in_constant_expression;
17860 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
17861 // C++17 [expr.prim.lamda]p2:
17862 // A lambda-expression shall not appear [...] in a template-argument.
17863 D = diag::err_lambda_in_invalid_context;
17864 } else
17865 llvm_unreachable("Couldn't infer lambda error message.");
17866
17867 for (const auto *L : Rec.Lambdas)
17868 Diag(L->getBeginLoc(), D);
17869 }
17870 }
17871
17872 // Append the collected materialized temporaries into previous context before
17873 // exit if the previous also is a lifetime extending context.
17875 parentEvaluationContext().InLifetimeExtendingContext &&
17876 !Rec.ForRangeLifetimeExtendTemps.empty()) {
17879 }
17880
17882 HandleImmediateInvocations(*this, Rec);
17883
17884 // Warn on any volatile-qualified simple-assignments that are not discarded-
17885 // value expressions nor unevaluated operands (those cases get removed from
17886 // this list by CheckUnusedVolatileAssignment).
17887 for (auto *BO : Rec.VolatileAssignmentLHSs)
17888 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
17889 << BO->getType();
17890
17891 // When are coming out of an unevaluated context, clear out any
17892 // temporaries that we may have created as part of the evaluation of
17893 // the expression in that context: they aren't relevant because they
17894 // will never be constructed.
17895 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
17897 ExprCleanupObjects.end());
17898 Cleanup = Rec.ParentCleanup;
17901 // Otherwise, merge the contexts together.
17902 } else {
17904 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
17905 Rec.SavedMaybeODRUseExprs.end());
17906 }
17907
17908 // Pop the current expression evaluation context off the stack.
17909 ExprEvalContexts.pop_back();
17910
17911 // The global expression evaluation context record is never popped.
17912 ExprEvalContexts.back().NumTypos += NumTypos;
17913}
17914
17916 ExprCleanupObjects.erase(
17917 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
17918 ExprCleanupObjects.end());
17919 Cleanup.reset();
17920 MaybeODRUseExprs.clear();
17921}
17922
17925 if (Result.isInvalid())
17926 return ExprError();
17927 E = Result.get();
17928 if (!E->getType()->isVariablyModifiedType())
17929 return E;
17931}
17932
17933/// Are we in a context that is potentially constant evaluated per C++20
17934/// [expr.const]p12?
17936 /// C++2a [expr.const]p12:
17937 // An expression or conversion is potentially constant evaluated if it is
17938 switch (SemaRef.ExprEvalContexts.back().Context) {
17941
17942 // -- a manifestly constant-evaluated expression,
17946 // -- a potentially-evaluated expression,
17948 // -- an immediate subexpression of a braced-init-list,
17949
17950 // -- [FIXME] an expression of the form & cast-expression that occurs
17951 // within a templated entity
17952 // -- a subexpression of one of the above that is not a subexpression of
17953 // a nested unevaluated operand.
17954 return true;
17955
17958 // Expressions in this context are never evaluated.
17959 return false;
17960 }
17961 llvm_unreachable("Invalid context");
17962}
17963
17964/// Return true if this function has a calling convention that requires mangling
17965/// in the size of the parameter pack.
17967 // These manglings don't do anything on non-Windows or non-x86 platforms, so
17968 // we don't need parameter type sizes.
17969 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
17970 if (!TT.isOSWindows() || !TT.isX86())
17971 return false;
17972
17973 // If this is C++ and this isn't an extern "C" function, parameters do not
17974 // need to be complete. In this case, C++ mangling will apply, which doesn't
17975 // use the size of the parameters.
17976 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
17977 return false;
17978
17979 // Stdcall, fastcall, and vectorcall need this special treatment.
17980 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
17981 switch (CC) {
17982 case CC_X86StdCall:
17983 case CC_X86FastCall:
17984 case CC_X86VectorCall:
17985 return true;
17986 default:
17987 break;
17988 }
17989 return false;
17990}
17991
17992/// Require that all of the parameter types of function be complete. Normally,
17993/// parameter types are only required to be complete when a function is called
17994/// or defined, but to mangle functions with certain calling conventions, the
17995/// mangler needs to know the size of the parameter list. In this situation,
17996/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
17997/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
17998/// result in a linker error. Clang doesn't implement this behavior, and instead
17999/// attempts to error at compile time.
18002 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18003 FunctionDecl *FD;
18004 ParmVarDecl *Param;
18005
18006 public:
18007 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18008 : FD(FD), Param(Param) {}
18009
18010 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18011 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18012 StringRef CCName;
18013 switch (CC) {
18014 case CC_X86StdCall:
18015 CCName = "stdcall";
18016 break;
18017 case CC_X86FastCall:
18018 CCName = "fastcall";
18019 break;
18020 case CC_X86VectorCall:
18021 CCName = "vectorcall";
18022 break;
18023 default:
18024 llvm_unreachable("CC does not need mangling");
18025 }
18026
18027 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18028 << Param->getDeclName() << FD->getDeclName() << CCName;
18029 }
18030 };
18031
18032 for (ParmVarDecl *Param : FD->parameters()) {
18033 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18034 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18035 }
18036}
18037
18038namespace {
18039enum class OdrUseContext {
18040 /// Declarations in this context are not odr-used.
18041 None,
18042 /// Declarations in this context are formally odr-used, but this is a
18043 /// dependent context.
18044 Dependent,
18045 /// Declarations in this context are odr-used but not actually used (yet).
18046 FormallyOdrUsed,
18047 /// Declarations in this context are used.
18048 Used
18049};
18050}
18051
18052/// Are we within a context in which references to resolved functions or to
18053/// variables result in odr-use?
18054static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18055 OdrUseContext Result;
18056
18057 switch (SemaRef.ExprEvalContexts.back().Context) {
18061 return OdrUseContext::None;
18062
18066 Result = OdrUseContext::Used;
18067 break;
18068
18070 Result = OdrUseContext::FormallyOdrUsed;
18071 break;
18072
18074 // A default argument formally results in odr-use, but doesn't actually
18075 // result in a use in any real sense until it itself is used.
18076 Result = OdrUseContext::FormallyOdrUsed;
18077 break;
18078 }
18079
18081 return OdrUseContext::Dependent;
18082
18083 return Result;
18084}
18085
18087 if (!Func->isConstexpr())
18088 return false;
18089
18090 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18091 return true;
18092 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18093 return CCD && CCD->getInheritedConstructor();
18094}
18095
18097 bool MightBeOdrUse) {
18098 assert(Func && "No function?");
18099
18100 Func->setReferenced();
18101
18102 // Recursive functions aren't really used until they're used from some other
18103 // context.
18104 bool IsRecursiveCall = CurContext == Func;
18105
18106 // C++11 [basic.def.odr]p3:
18107 // A function whose name appears as a potentially-evaluated expression is
18108 // odr-used if it is the unique lookup result or the selected member of a
18109 // set of overloaded functions [...].
18110 //
18111 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18112 // can just check that here.
18113 OdrUseContext OdrUse =
18114 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18115 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18116 OdrUse = OdrUseContext::FormallyOdrUsed;
18117
18118 // Trivial default constructors and destructors are never actually used.
18119 // FIXME: What about other special members?
18120 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18121 OdrUse == OdrUseContext::Used) {
18122 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18123 if (Constructor->isDefaultConstructor())
18124 OdrUse = OdrUseContext::FormallyOdrUsed;
18125 if (isa<CXXDestructorDecl>(Func))
18126 OdrUse = OdrUseContext::FormallyOdrUsed;
18127 }
18128
18129 // C++20 [expr.const]p12:
18130 // A function [...] is needed for constant evaluation if it is [...] a
18131 // constexpr function that is named by an expression that is potentially
18132 // constant evaluated
18133 bool NeededForConstantEvaluation =
18136
18137 // Determine whether we require a function definition to exist, per
18138 // C++11 [temp.inst]p3:
18139 // Unless a function template specialization has been explicitly
18140 // instantiated or explicitly specialized, the function template
18141 // specialization is implicitly instantiated when the specialization is
18142 // referenced in a context that requires a function definition to exist.
18143 // C++20 [temp.inst]p7:
18144 // The existence of a definition of a [...] function is considered to
18145 // affect the semantics of the program if the [...] function is needed for
18146 // constant evaluation by an expression
18147 // C++20 [basic.def.odr]p10:
18148 // Every program shall contain exactly one definition of every non-inline
18149 // function or variable that is odr-used in that program outside of a
18150 // discarded statement
18151 // C++20 [special]p1:
18152 // The implementation will implicitly define [defaulted special members]
18153 // if they are odr-used or needed for constant evaluation.
18154 //
18155 // Note that we skip the implicit instantiation of templates that are only
18156 // used in unused default arguments or by recursive calls to themselves.
18157 // This is formally non-conforming, but seems reasonable in practice.
18158 bool NeedDefinition =
18159 !IsRecursiveCall &&
18160 (OdrUse == OdrUseContext::Used ||
18161 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18162
18163 // C++14 [temp.expl.spec]p6:
18164 // If a template [...] is explicitly specialized then that specialization
18165 // shall be declared before the first use of that specialization that would
18166 // cause an implicit instantiation to take place, in every translation unit
18167 // in which such a use occurs
18168 if (NeedDefinition &&
18169 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18170 Func->getMemberSpecializationInfo()))
18172
18173 if (getLangOpts().CUDA)
18174 CUDA().CheckCall(Loc, Func);
18175
18176 // If we need a definition, try to create one.
18177 if (NeedDefinition && !Func->getBody()) {
18179 if (CXXConstructorDecl *Constructor =
18180 dyn_cast<CXXConstructorDecl>(Func)) {
18181 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18182 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18183 if (Constructor->isDefaultConstructor()) {
18184 if (Constructor->isTrivial() &&
18185 !Constructor->hasAttr<DLLExportAttr>())
18186 return;
18188 } else if (Constructor->isCopyConstructor()) {
18189 DefineImplicitCopyConstructor(Loc, Constructor);
18190 } else if (Constructor->isMoveConstructor()) {
18191 DefineImplicitMoveConstructor(Loc, Constructor);
18192 }
18193 } else if (Constructor->getInheritedConstructor()) {
18194 DefineInheritingConstructor(Loc, Constructor);
18195 }
18196 } else if (CXXDestructorDecl *Destructor =
18197 dyn_cast<CXXDestructorDecl>(Func)) {
18198 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18199 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18200 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18201 return;
18203 }
18204 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18205 MarkVTableUsed(Loc, Destructor->getParent());
18206 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18207 if (MethodDecl->isOverloadedOperator() &&
18208 MethodDecl->getOverloadedOperator() == OO_Equal) {
18209 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18210 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18211 if (MethodDecl->isCopyAssignmentOperator())
18212 DefineImplicitCopyAssignment(Loc, MethodDecl);
18213 else if (MethodDecl->isMoveAssignmentOperator())
18214 DefineImplicitMoveAssignment(Loc, MethodDecl);
18215 }
18216 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18217 MethodDecl->getParent()->isLambda()) {
18218 CXXConversionDecl *Conversion =
18219 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18220 if (Conversion->isLambdaToBlockPointerConversion())
18222 else
18224 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18225 MarkVTableUsed(Loc, MethodDecl->getParent());
18226 }
18227
18228 if (Func->isDefaulted() && !Func->isDeleted()) {
18232 }
18233
18234 // Implicit instantiation of function templates and member functions of
18235 // class templates.
18236 if (Func->isImplicitlyInstantiable()) {
18238 Func->getTemplateSpecializationKindForInstantiation();
18239 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18240 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18241 if (FirstInstantiation) {
18242 PointOfInstantiation = Loc;
18243 if (auto *MSI = Func->getMemberSpecializationInfo())
18244 MSI->setPointOfInstantiation(Loc);
18245 // FIXME: Notify listener.
18246 else
18247 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18248 } else if (TSK != TSK_ImplicitInstantiation) {
18249 // Use the point of use as the point of instantiation, instead of the
18250 // point of explicit instantiation (which we track as the actual point
18251 // of instantiation). This gives better backtraces in diagnostics.
18252 PointOfInstantiation = Loc;
18253 }
18254
18255 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18256 Func->isConstexpr()) {
18257 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18258 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18259 CodeSynthesisContexts.size())
18261 std::make_pair(Func, PointOfInstantiation));
18262 else if (Func->isConstexpr())
18263 // Do not defer instantiations of constexpr functions, to avoid the
18264 // expression evaluator needing to call back into Sema if it sees a
18265 // call to such a function.
18266 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18267 else {
18268 Func->setInstantiationIsPending(true);
18269 PendingInstantiations.push_back(
18270 std::make_pair(Func, PointOfInstantiation));
18271 if (llvm::isTimeTraceVerbose()) {
18272 llvm::timeTraceAddInstantEvent("DeferInstantiation", [&] {
18273 std::string Name;
18274 llvm::raw_string_ostream OS(Name);
18275 Func->getNameForDiagnostic(OS, getPrintingPolicy(),
18276 /*Qualified=*/true);
18277 return Name;
18278 });
18279 }
18280 // Notify the consumer that a function was implicitly instantiated.
18282 }
18283 }
18284 } else {
18285 // Walk redefinitions, as some of them may be instantiable.
18286 for (auto *i : Func->redecls()) {
18287 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18288 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18289 }
18290 }
18291 });
18292 }
18293
18294 // If a constructor was defined in the context of a default parameter
18295 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18296 // context), its initializers may not be referenced yet.
18297 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18299 *this,
18300 Constructor->isImmediateFunction()
18303 Constructor);
18304 for (CXXCtorInitializer *Init : Constructor->inits()) {
18305 if (Init->isInClassMemberInitializer())
18306 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18307 MarkDeclarationsReferencedInExpr(Init->getInit());
18308 });
18309 }
18310 }
18311
18312 // C++14 [except.spec]p17:
18313 // An exception-specification is considered to be needed when:
18314 // - the function is odr-used or, if it appears in an unevaluated operand,
18315 // would be odr-used if the expression were potentially-evaluated;
18316 //
18317 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18318 // function is a pure virtual function we're calling, and in that case the
18319 // function was selected by overload resolution and we need to resolve its
18320 // exception specification for a different reason.
18321 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18324
18325 // A callee could be called by a host function then by a device function.
18326 // If we only try recording once, we will miss recording the use on device
18327 // side. Therefore keep trying until it is recorded.
18328 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18331
18332 // If this is the first "real" use, act on that.
18333 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18334 // Keep track of used but undefined functions.
18335 if (!Func->isDefined()) {
18336 if (mightHaveNonExternalLinkage(Func))
18337 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18338 else if (Func->getMostRecentDecl()->isInlined() &&
18339 !LangOpts.GNUInline &&
18340 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18341 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18343 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18344 }
18345
18346 // Some x86 Windows calling conventions mangle the size of the parameter
18347 // pack into the name. Computing the size of the parameters requires the
18348 // parameter types to be complete. Check that now.
18351
18352 // In the MS C++ ABI, the compiler emits destructor variants where they are
18353 // used. If the destructor is used here but defined elsewhere, mark the
18354 // virtual base destructors referenced. If those virtual base destructors
18355 // are inline, this will ensure they are defined when emitting the complete
18356 // destructor variant. This checking may be redundant if the destructor is
18357 // provided later in this TU.
18359 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18360 CXXRecordDecl *Parent = Dtor->getParent();
18361 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18363 }
18364 }
18365
18366 Func->markUsed(Context);
18367 }
18368}
18369
18370/// Directly mark a variable odr-used. Given a choice, prefer to use
18371/// MarkVariableReferenced since it does additional checks and then
18372/// calls MarkVarDeclODRUsed.
18373/// If the variable must be captured:
18374/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18375/// - else capture it in the DeclContext that maps to the
18376/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18377static void
18379 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18380 // Keep track of used but undefined variables.
18381 // FIXME: We shouldn't suppress this warning for static data members.
18382 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18383 assert(Var && "expected a capturable variable");
18384
18386 (!Var->isExternallyVisible() || Var->isInline() ||
18388 !(Var->isStaticDataMember() && Var->hasInit())) {
18390 if (old.isInvalid())
18391 old = Loc;
18392 }
18393 QualType CaptureType, DeclRefType;
18394 if (SemaRef.LangOpts.OpenMP)
18397 /*EllipsisLoc*/ SourceLocation(),
18398 /*BuildAndDiagnose*/ true, CaptureType,
18399 DeclRefType, FunctionScopeIndexToStopAt);
18400
18401 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18402 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18403 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
18404 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
18405 if (VarTarget == SemaCUDA::CVT_Host &&
18406 (UserTarget == CUDAFunctionTarget::Device ||
18407 UserTarget == CUDAFunctionTarget::HostDevice ||
18408 UserTarget == CUDAFunctionTarget::Global)) {
18409 // Diagnose ODR-use of host global variables in device functions.
18410 // Reference of device global variables in host functions is allowed
18411 // through shadow variables therefore it is not diagnosed.
18412 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18413 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18414 << /*host*/ 2 << /*variable*/ 1 << Var
18415 << llvm::to_underlying(UserTarget);
18417 Var->getType().isConstQualified()
18418 ? diag::note_cuda_const_var_unpromoted
18419 : diag::note_cuda_host_var);
18420 }
18421 } else if (VarTarget == SemaCUDA::CVT_Device &&
18422 !Var->hasAttr<CUDASharedAttr>() &&
18423 (UserTarget == CUDAFunctionTarget::Host ||
18424 UserTarget == CUDAFunctionTarget::HostDevice)) {
18425 // Record a CUDA/HIP device side variable if it is ODR-used
18426 // by host code. This is done conservatively, when the variable is
18427 // referenced in any of the following contexts:
18428 // - a non-function context
18429 // - a host function
18430 // - a host device function
18431 // This makes the ODR-use of the device side variable by host code to
18432 // be visible in the device compilation for the compiler to be able to
18433 // emit template variables instantiated by host code only and to
18434 // externalize the static device side variable ODR-used by host code.
18435 if (!Var->hasExternalStorage())
18437 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18438 (!FD || (!FD->getDescribedFunctionTemplate() &&
18442 }
18443 }
18444
18445 V->markUsed(SemaRef.Context);
18446}
18447
18450 unsigned CapturingScopeIndex) {
18451 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18452}
18453
18455 ValueDecl *var) {
18456 DeclContext *VarDC = var->getDeclContext();
18457
18458 // If the parameter still belongs to the translation unit, then
18459 // we're actually just using one parameter in the declaration of
18460 // the next.
18461 if (isa<ParmVarDecl>(var) &&
18462 isa<TranslationUnitDecl>(VarDC))
18463 return;
18464
18465 // For C code, don't diagnose about capture if we're not actually in code
18466 // right now; it's impossible to write a non-constant expression outside of
18467 // function context, so we'll get other (more useful) diagnostics later.
18468 //
18469 // For C++, things get a bit more nasty... it would be nice to suppress this
18470 // diagnostic for certain cases like using a local variable in an array bound
18471 // for a member of a local class, but the correct predicate is not obvious.
18472 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18473 return;
18474
18475 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18476 unsigned ContextKind = 3; // unknown
18477 if (isa<CXXMethodDecl>(VarDC) &&
18478 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18479 ContextKind = 2;
18480 } else if (isa<FunctionDecl>(VarDC)) {
18481 ContextKind = 0;
18482 } else if (isa<BlockDecl>(VarDC)) {
18483 ContextKind = 1;
18484 }
18485
18486 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18487 << var << ValueKind << ContextKind << VarDC;
18488 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18489 << var;
18490
18491 // FIXME: Add additional diagnostic info about class etc. which prevents
18492 // capture.
18493}
18494
18496 ValueDecl *Var,
18497 bool &SubCapturesAreNested,
18498 QualType &CaptureType,
18499 QualType &DeclRefType) {
18500 // Check whether we've already captured it.
18501 if (CSI->CaptureMap.count(Var)) {
18502 // If we found a capture, any subcaptures are nested.
18503 SubCapturesAreNested = true;
18504
18505 // Retrieve the capture type for this variable.
18506 CaptureType = CSI->getCapture(Var).getCaptureType();
18507
18508 // Compute the type of an expression that refers to this variable.
18509 DeclRefType = CaptureType.getNonReferenceType();
18510
18511 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18512 // are mutable in the sense that user can change their value - they are
18513 // private instances of the captured declarations.
18514 const Capture &Cap = CSI->getCapture(Var);
18515 // C++ [expr.prim.lambda]p10:
18516 // The type of such a data member is [...] an lvalue reference to the
18517 // referenced function type if the entity is a reference to a function.
18518 // [...]
18519 if (Cap.isCopyCapture() && !DeclRefType->isFunctionType() &&
18520 !(isa<LambdaScopeInfo>(CSI) &&
18521 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
18522 !(isa<CapturedRegionScopeInfo>(CSI) &&
18523 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18524 DeclRefType.addConst();
18525 return true;
18526 }
18527 return false;
18528}
18529
18530// Only block literals, captured statements, and lambda expressions can
18531// capture; other scopes don't work.
18533 ValueDecl *Var,
18535 const bool Diagnose,
18536 Sema &S) {
18537 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18539
18540 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18541 if (Underlying) {
18542 if (Underlying->hasLocalStorage() && Diagnose)
18544 }
18545 return nullptr;
18546}
18547
18548// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18549// certain types of variables (unnamed, variably modified types etc.)
18550// so check for eligibility.
18552 SourceLocation Loc, const bool Diagnose,
18553 Sema &S) {
18554
18555 assert((isa<VarDecl, BindingDecl>(Var)) &&
18556 "Only variables and structured bindings can be captured");
18557
18558 bool IsBlock = isa<BlockScopeInfo>(CSI);
18559 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18560
18561 // Lambdas are not allowed to capture unnamed variables
18562 // (e.g. anonymous unions).
18563 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18564 // assuming that's the intent.
18565 if (IsLambda && !Var->getDeclName()) {
18566 if (Diagnose) {
18567 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18568 S.Diag(Var->getLocation(), diag::note_declared_at);
18569 }
18570 return false;
18571 }
18572
18573 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18574 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18575 if (Diagnose) {
18576 S.Diag(Loc, diag::err_ref_vm_type);
18577 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18578 }
18579 return false;
18580 }
18581 // Prohibit structs with flexible array members too.
18582 // We cannot capture what is in the tail end of the struct.
18583 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18584 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18585 if (Diagnose) {
18586 if (IsBlock)
18587 S.Diag(Loc, diag::err_ref_flexarray_type);
18588 else
18589 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18590 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18591 }
18592 return false;
18593 }
18594 }
18595 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18596 // Lambdas and captured statements are not allowed to capture __block
18597 // variables; they don't support the expected semantics.
18598 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18599 if (Diagnose) {
18600 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18601 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18602 }
18603 return false;
18604 }
18605 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18606 if (S.getLangOpts().OpenCL && IsBlock &&
18607 Var->getType()->isBlockPointerType()) {
18608 if (Diagnose)
18609 S.Diag(Loc, diag::err_opencl_block_ref_block);
18610 return false;
18611 }
18612
18613 if (isa<BindingDecl>(Var)) {
18614 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18615 if (Diagnose)
18617 return false;
18618 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18619 S.Diag(Loc, S.LangOpts.CPlusPlus20
18620 ? diag::warn_cxx17_compat_capture_binding
18621 : diag::ext_capture_binding)
18622 << Var;
18623 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18624 }
18625 }
18626
18627 return true;
18628}
18629
18630// Returns true if the capture by block was successful.
18632 SourceLocation Loc, const bool BuildAndDiagnose,
18633 QualType &CaptureType, QualType &DeclRefType,
18634 const bool Nested, Sema &S, bool Invalid) {
18635 bool ByRef = false;
18636
18637 // Blocks are not allowed to capture arrays, excepting OpenCL.
18638 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18639 // (decayed to pointers).
18640 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18641 if (BuildAndDiagnose) {
18642 S.Diag(Loc, diag::err_ref_array_type);
18643 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18644 Invalid = true;
18645 } else {
18646 return false;
18647 }
18648 }
18649
18650 // Forbid the block-capture of autoreleasing variables.
18651 if (!Invalid &&
18653 if (BuildAndDiagnose) {
18654 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18655 << /*block*/ 0;
18656 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18657 Invalid = true;
18658 } else {
18659 return false;
18660 }
18661 }
18662
18663 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18664 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18665 QualType PointeeTy = PT->getPointeeType();
18666
18667 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18669 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18670 if (BuildAndDiagnose) {
18671 SourceLocation VarLoc = Var->getLocation();
18672 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18673 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18674 }
18675 }
18676 }
18677
18678 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18679 if (HasBlocksAttr || CaptureType->isReferenceType() ||
18680 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
18681 // Block capture by reference does not change the capture or
18682 // declaration reference types.
18683 ByRef = true;
18684 } else {
18685 // Block capture by copy introduces 'const'.
18686 CaptureType = CaptureType.getNonReferenceType().withConst();
18687 DeclRefType = CaptureType;
18688 }
18689
18690 // Actually capture the variable.
18691 if (BuildAndDiagnose)
18692 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18693 CaptureType, Invalid);
18694
18695 return !Invalid;
18696}
18697
18698/// Capture the given variable in the captured region.
18701 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18702 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18703 bool IsTopScope, Sema &S, bool Invalid) {
18704 // By default, capture variables by reference.
18705 bool ByRef = true;
18706 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18707 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18708 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18709 // Using an LValue reference type is consistent with Lambdas (see below).
18710 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
18711 bool HasConst = DeclRefType.isConstQualified();
18712 DeclRefType = DeclRefType.getUnqualifiedType();
18713 // Don't lose diagnostics about assignments to const.
18714 if (HasConst)
18715 DeclRefType.addConst();
18716 }
18717 // Do not capture firstprivates in tasks.
18718 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
18719 RSI->OpenMPCaptureLevel) != OMPC_unknown)
18720 return true;
18721 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18722 RSI->OpenMPCaptureLevel);
18723 }
18724
18725 if (ByRef)
18726 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18727 else
18728 CaptureType = DeclRefType;
18729
18730 // Actually capture the variable.
18731 if (BuildAndDiagnose)
18732 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18733 Loc, SourceLocation(), CaptureType, Invalid);
18734
18735 return !Invalid;
18736}
18737
18738/// Capture the given variable in the lambda.
18740 SourceLocation Loc, const bool BuildAndDiagnose,
18741 QualType &CaptureType, QualType &DeclRefType,
18742 const bool RefersToCapturedVariable,
18743 const Sema::TryCaptureKind Kind,
18744 SourceLocation EllipsisLoc, const bool IsTopScope,
18745 Sema &S, bool Invalid) {
18746 // Determine whether we are capturing by reference or by value.
18747 bool ByRef = false;
18748 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18749 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18750 } else {
18751 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18752 }
18753
18754 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
18756 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
18757 Invalid = true;
18758 }
18759
18760 // Compute the type of the field that will capture this variable.
18761 if (ByRef) {
18762 // C++11 [expr.prim.lambda]p15:
18763 // An entity is captured by reference if it is implicitly or
18764 // explicitly captured but not captured by copy. It is
18765 // unspecified whether additional unnamed non-static data
18766 // members are declared in the closure type for entities
18767 // captured by reference.
18768 //
18769 // FIXME: It is not clear whether we want to build an lvalue reference
18770 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18771 // to do the former, while EDG does the latter. Core issue 1249 will
18772 // clarify, but for now we follow GCC because it's a more permissive and
18773 // easily defensible position.
18774 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18775 } else {
18776 // C++11 [expr.prim.lambda]p14:
18777 // For each entity captured by copy, an unnamed non-static
18778 // data member is declared in the closure type. The
18779 // declaration order of these members is unspecified. The type
18780 // of such a data member is the type of the corresponding
18781 // captured entity if the entity is not a reference to an
18782 // object, or the referenced type otherwise. [Note: If the
18783 // captured entity is a reference to a function, the
18784 // corresponding data member is also a reference to a
18785 // function. - end note ]
18786 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
18787 if (!RefType->getPointeeType()->isFunctionType())
18788 CaptureType = RefType->getPointeeType();
18789 }
18790
18791 // Forbid the lambda copy-capture of autoreleasing variables.
18792 if (!Invalid &&
18794 if (BuildAndDiagnose) {
18795 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
18796 S.Diag(Var->getLocation(), diag::note_previous_decl)
18797 << Var->getDeclName();
18798 Invalid = true;
18799 } else {
18800 return false;
18801 }
18802 }
18803
18804 // Make sure that by-copy captures are of a complete and non-abstract type.
18805 if (!Invalid && BuildAndDiagnose) {
18806 if (!CaptureType->isDependentType() &&
18808 Loc, CaptureType,
18809 diag::err_capture_of_incomplete_or_sizeless_type,
18810 Var->getDeclName()))
18811 Invalid = true;
18812 else if (S.RequireNonAbstractType(Loc, CaptureType,
18813 diag::err_capture_of_abstract_type))
18814 Invalid = true;
18815 }
18816 }
18817
18818 // Compute the type of a reference to this captured variable.
18819 if (ByRef)
18820 DeclRefType = CaptureType.getNonReferenceType();
18821 else {
18822 // C++ [expr.prim.lambda]p5:
18823 // The closure type for a lambda-expression has a public inline
18824 // function call operator [...]. This function call operator is
18825 // declared const (9.3.1) if and only if the lambda-expression's
18826 // parameter-declaration-clause is not followed by mutable.
18827 DeclRefType = CaptureType.getNonReferenceType();
18828 bool Const = LSI->lambdaCaptureShouldBeConst();
18829 // C++ [expr.prim.lambda]p10:
18830 // The type of such a data member is [...] an lvalue reference to the
18831 // referenced function type if the entity is a reference to a function.
18832 // [...]
18833 if (Const && !CaptureType->isReferenceType() &&
18834 !DeclRefType->isFunctionType())
18835 DeclRefType.addConst();
18836 }
18837
18838 // Add the capture.
18839 if (BuildAndDiagnose)
18840 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
18841 Loc, EllipsisLoc, CaptureType, Invalid);
18842
18843 return !Invalid;
18844}
18845
18847 const ASTContext &Context) {
18848 // Offer a Copy fix even if the type is dependent.
18849 if (Var->getType()->isDependentType())
18850 return true;
18852 if (T.isTriviallyCopyableType(Context))
18853 return true;
18854 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
18855
18856 if (!(RD = RD->getDefinition()))
18857 return false;
18858 if (RD->hasSimpleCopyConstructor())
18859 return true;
18860 if (RD->hasUserDeclaredCopyConstructor())
18861 for (CXXConstructorDecl *Ctor : RD->ctors())
18862 if (Ctor->isCopyConstructor())
18863 return !Ctor->isDeleted();
18864 }
18865 return false;
18866}
18867
18868/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18869/// default capture. Fixes may be omitted if they aren't allowed by the
18870/// standard, for example we can't emit a default copy capture fix-it if we
18871/// already explicitly copy capture capture another variable.
18873 ValueDecl *Var) {
18875 // Don't offer Capture by copy of default capture by copy fixes if Var is
18876 // known not to be copy constructible.
18877 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
18878
18879 SmallString<32> FixBuffer;
18880 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
18881 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
18882 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
18883 if (ShouldOfferCopyFix) {
18884 // Offer fixes to insert an explicit capture for the variable.
18885 // [] -> [VarName]
18886 // [OtherCapture] -> [OtherCapture, VarName]
18887 FixBuffer.assign({Separator, Var->getName()});
18888 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18889 << Var << /*value*/ 0
18890 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18891 }
18892 // As above but capture by reference.
18893 FixBuffer.assign({Separator, "&", Var->getName()});
18894 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
18895 << Var << /*reference*/ 1
18896 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
18897 }
18898
18899 // Only try to offer default capture if there are no captures excluding this
18900 // and init captures.
18901 // [this]: OK.
18902 // [X = Y]: OK.
18903 // [&A, &B]: Don't offer.
18904 // [A, B]: Don't offer.
18905 if (llvm::any_of(LSI->Captures, [](Capture &C) {
18906 return !C.isThisCapture() && !C.isInitCapture();
18907 }))
18908 return;
18909
18910 // The default capture specifiers, '=' or '&', must appear first in the
18911 // capture body.
18912 SourceLocation DefaultInsertLoc =
18914
18915 if (ShouldOfferCopyFix) {
18916 bool CanDefaultCopyCapture = true;
18917 // [=, *this] OK since c++17
18918 // [=, this] OK since c++20
18919 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
18920 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
18922 : false;
18923 // We can't use default capture by copy if any captures already specified
18924 // capture by copy.
18925 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
18926 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
18927 })) {
18928 FixBuffer.assign({"=", Separator});
18929 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18930 << /*value*/ 0
18931 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18932 }
18933 }
18934
18935 // We can't use default capture by reference if any captures already specified
18936 // capture by reference.
18937 if (llvm::none_of(LSI->Captures, [](Capture &C) {
18938 return !C.isInitCapture() && C.isReferenceCapture() &&
18939 !C.isThisCapture();
18940 })) {
18941 FixBuffer.assign({"&", Separator});
18942 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
18943 << /*reference*/ 1
18944 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
18945 }
18946}
18947
18949 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
18950 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
18951 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
18952 // An init-capture is notionally from the context surrounding its
18953 // declaration, but its parent DC is the lambda class.
18954 DeclContext *VarDC = Var->getDeclContext();
18955 DeclContext *DC = CurContext;
18956
18957 // Skip past RequiresExprBodys because they don't constitute function scopes.
18958 while (DC->isRequiresExprBody())
18959 DC = DC->getParent();
18960
18961 // tryCaptureVariable is called every time a DeclRef is formed,
18962 // it can therefore have non-negigible impact on performances.
18963 // For local variables and when there is no capturing scope,
18964 // we can bailout early.
18965 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
18966 return true;
18967
18968 // Exception: Function parameters are not tied to the function's DeclContext
18969 // until we enter the function definition. Capturing them anyway would result
18970 // in an out-of-bounds error while traversing DC and its parents.
18971 if (isa<ParmVarDecl>(Var) && !VarDC->isFunctionOrMethod())
18972 return true;
18973
18974 const auto *VD = dyn_cast<VarDecl>(Var);
18975 if (VD) {
18976 if (VD->isInitCapture())
18977 VarDC = VarDC->getParent();
18978 } else {
18980 }
18981 assert(VD && "Cannot capture a null variable");
18982
18983 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
18984 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
18985 // We need to sync up the Declaration Context with the
18986 // FunctionScopeIndexToStopAt
18987 if (FunctionScopeIndexToStopAt) {
18988 assert(!FunctionScopes.empty() && "No function scopes to stop at?");
18989 unsigned FSIndex = FunctionScopes.size() - 1;
18990 // When we're parsing the lambda parameter list, the current DeclContext is
18991 // NOT the lambda but its parent. So move away the current LSI before
18992 // aligning DC and FunctionScopeIndexToStopAt.
18993 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FunctionScopes[FSIndex]);
18994 FSIndex && LSI && !LSI->AfterParameterList)
18995 --FSIndex;
18996 assert(MaxFunctionScopesIndex <= FSIndex &&
18997 "FunctionScopeIndexToStopAt should be no greater than FSIndex into "
18998 "FunctionScopes.");
18999 while (FSIndex != MaxFunctionScopesIndex) {
19001 --FSIndex;
19002 }
19003 }
19004
19005 // Capture global variables if it is required to use private copy of this
19006 // variable.
19007 bool IsGlobal = !VD->hasLocalStorage();
19008 if (IsGlobal && !(LangOpts.OpenMP &&
19009 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19010 MaxFunctionScopesIndex)))
19011 return true;
19012
19013 if (isa<VarDecl>(Var))
19014 Var = cast<VarDecl>(Var->getCanonicalDecl());
19015
19016 // Walk up the stack to determine whether we can capture the variable,
19017 // performing the "simple" checks that don't depend on type. We stop when
19018 // we've either hit the declared scope of the variable or find an existing
19019 // capture of that variable. We start from the innermost capturing-entity
19020 // (the DC) and ensure that all intervening capturing-entities
19021 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19022 // declcontext can either capture the variable or have already captured
19023 // the variable.
19024 CaptureType = Var->getType();
19025 DeclRefType = CaptureType.getNonReferenceType();
19026 bool Nested = false;
19027 bool Explicit = (Kind != TryCapture_Implicit);
19028 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19029 do {
19030
19031 LambdaScopeInfo *LSI = nullptr;
19032 if (!FunctionScopes.empty())
19033 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19034 FunctionScopes[FunctionScopesIndex]);
19035
19036 bool IsInScopeDeclarationContext =
19037 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19038
19039 if (LSI && !LSI->AfterParameterList) {
19040 // This allows capturing parameters from a default value which does not
19041 // seems correct
19042 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19043 return true;
19044 }
19045 // If the variable is declared in the current context, there is no need to
19046 // capture it.
19047 if (IsInScopeDeclarationContext &&
19048 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19049 return true;
19050
19051 // Only block literals, captured statements, and lambda expressions can
19052 // capture; other scopes don't work.
19053 DeclContext *ParentDC =
19054 !IsInScopeDeclarationContext
19055 ? DC->getParent()
19056 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19057 BuildAndDiagnose, *this);
19058 // We need to check for the parent *first* because, if we *have*
19059 // private-captured a global variable, we need to recursively capture it in
19060 // intermediate blocks, lambdas, etc.
19061 if (!ParentDC) {
19062 if (IsGlobal) {
19063 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19064 break;
19065 }
19066 return true;
19067 }
19068
19069 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19070 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
19071
19072 // Check whether we've already captured it.
19073 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19074 DeclRefType)) {
19075 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19076 break;
19077 }
19078
19079 // When evaluating some attributes (like enable_if) we might refer to a
19080 // function parameter appertaining to the same declaration as that
19081 // attribute.
19082 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19083 Parm && Parm->getDeclContext() == DC)
19084 return true;
19085
19086 // If we are instantiating a generic lambda call operator body,
19087 // we do not want to capture new variables. What was captured
19088 // during either a lambdas transformation or initial parsing
19089 // should be used.
19091 if (BuildAndDiagnose) {
19092 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19094 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19095 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19096 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19097 buildLambdaCaptureFixit(*this, LSI, Var);
19098 } else
19100 }
19101 return true;
19102 }
19103
19104 // Try to capture variable-length arrays types.
19105 if (Var->getType()->isVariablyModifiedType()) {
19106 // We're going to walk down into the type and look for VLA
19107 // expressions.
19108 QualType QTy = Var->getType();
19109 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19110 QTy = PVD->getOriginalType();
19112 }
19113
19114 if (getLangOpts().OpenMP) {
19115 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19116 // OpenMP private variables should not be captured in outer scope, so
19117 // just break here. Similarly, global variables that are captured in a
19118 // target region should not be captured outside the scope of the region.
19119 if (RSI->CapRegionKind == CR_OpenMP) {
19120 // FIXME: We should support capturing structured bindings in OpenMP.
19121 if (isa<BindingDecl>(Var)) {
19122 if (BuildAndDiagnose) {
19123 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19124 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19125 }
19126 return true;
19127 }
19128 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19129 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19130 // If the variable is private (i.e. not captured) and has variably
19131 // modified type, we still need to capture the type for correct
19132 // codegen in all regions, associated with the construct. Currently,
19133 // it is captured in the innermost captured region only.
19134 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19135 Var->getType()->isVariablyModifiedType()) {
19136 QualType QTy = Var->getType();
19137 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19138 QTy = PVD->getOriginalType();
19139 for (int I = 1,
19140 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
19141 I < E; ++I) {
19142 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19143 FunctionScopes[FunctionScopesIndex - I]);
19144 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19145 "Wrong number of captured regions associated with the "
19146 "OpenMP construct.");
19147 captureVariablyModifiedType(Context, QTy, OuterRSI);
19148 }
19149 }
19150 bool IsTargetCap =
19151 IsOpenMPPrivateDecl != OMPC_private &&
19152 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19153 RSI->OpenMPCaptureLevel);
19154 // Do not capture global if it is not privatized in outer regions.
19155 bool IsGlobalCap =
19156 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19157 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19158
19159 // When we detect target captures we are looking from inside the
19160 // target region, therefore we need to propagate the capture from the
19161 // enclosing region. Therefore, the capture is not initially nested.
19162 if (IsTargetCap)
19163 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19164 RSI->OpenMPLevel);
19165
19166 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19167 (IsGlobal && !IsGlobalCap)) {
19168 Nested = !IsTargetCap;
19169 bool HasConst = DeclRefType.isConstQualified();
19170 DeclRefType = DeclRefType.getUnqualifiedType();
19171 // Don't lose diagnostics about assignments to const.
19172 if (HasConst)
19173 DeclRefType.addConst();
19174 CaptureType = Context.getLValueReferenceType(DeclRefType);
19175 break;
19176 }
19177 }
19178 }
19179 }
19181 // No capture-default, and this is not an explicit capture
19182 // so cannot capture this variable.
19183 if (BuildAndDiagnose) {
19184 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19185 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19186 auto *LSI = cast<LambdaScopeInfo>(CSI);
19187 if (LSI->Lambda) {
19188 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19189 buildLambdaCaptureFixit(*this, LSI, Var);
19190 }
19191 // FIXME: If we error out because an outer lambda can not implicitly
19192 // capture a variable that an inner lambda explicitly captures, we
19193 // should have the inner lambda do the explicit capture - because
19194 // it makes for cleaner diagnostics later. This would purely be done
19195 // so that the diagnostic does not misleadingly claim that a variable
19196 // can not be captured by a lambda implicitly even though it is captured
19197 // explicitly. Suggestion:
19198 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19199 // at the function head
19200 // - cache the StartingDeclContext - this must be a lambda
19201 // - captureInLambda in the innermost lambda the variable.
19202 }
19203 return true;
19204 }
19205 Explicit = false;
19206 FunctionScopesIndex--;
19207 if (IsInScopeDeclarationContext)
19208 DC = ParentDC;
19209 } while (!VarDC->Equals(DC));
19210
19211 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19212 // computing the type of the capture at each step, checking type-specific
19213 // requirements, and adding captures if requested.
19214 // If the variable had already been captured previously, we start capturing
19215 // at the lambda nested within that one.
19216 bool Invalid = false;
19217 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19218 ++I) {
19219 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19220
19221 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19222 // certain types of variables (unnamed, variably modified types etc.)
19223 // so check for eligibility.
19224 if (!Invalid)
19225 Invalid =
19226 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19227
19228 // After encountering an error, if we're actually supposed to capture, keep
19229 // capturing in nested contexts to suppress any follow-on diagnostics.
19230 if (Invalid && !BuildAndDiagnose)
19231 return true;
19232
19233 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19234 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19235 DeclRefType, Nested, *this, Invalid);
19236 Nested = true;
19237 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19239 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19240 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19241 Nested = true;
19242 } else {
19243 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19244 Invalid =
19245 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19246 DeclRefType, Nested, Kind, EllipsisLoc,
19247 /*IsTopScope*/ I == N - 1, *this, Invalid);
19248 Nested = true;
19249 }
19250
19251 if (Invalid && !BuildAndDiagnose)
19252 return true;
19253 }
19254 return Invalid;
19255}
19256
19258 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19259 QualType CaptureType;
19260 QualType DeclRefType;
19261 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19262 /*BuildAndDiagnose=*/true, CaptureType,
19263 DeclRefType, nullptr);
19264}
19265
19267 QualType CaptureType;
19268 QualType DeclRefType;
19270 /*BuildAndDiagnose=*/false, CaptureType,
19271 DeclRefType, nullptr);
19272}
19273
19275 assert(Var && "Null value cannot be captured");
19276
19277 QualType CaptureType;
19278 QualType DeclRefType;
19279
19280 // Determine whether we can capture this variable.
19282 /*BuildAndDiagnose=*/false, CaptureType,
19283 DeclRefType, nullptr))
19284 return QualType();
19285
19286 return DeclRefType;
19287}
19288
19289namespace {
19290// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19291// The produced TemplateArgumentListInfo* points to data stored within this
19292// object, so should only be used in contexts where the pointer will not be
19293// used after the CopiedTemplateArgs object is destroyed.
19294class CopiedTemplateArgs {
19295 bool HasArgs;
19296 TemplateArgumentListInfo TemplateArgStorage;
19297public:
19298 template<typename RefExpr>
19299 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19300 if (HasArgs)
19301 E->copyTemplateArgumentsInto(TemplateArgStorage);
19302 }
19303 operator TemplateArgumentListInfo*()
19304#ifdef __has_cpp_attribute
19305#if __has_cpp_attribute(clang::lifetimebound)
19306 [[clang::lifetimebound]]
19307#endif
19308#endif
19309 {
19310 return HasArgs ? &TemplateArgStorage : nullptr;
19311 }
19312};
19313}
19314
19315/// Walk the set of potential results of an expression and mark them all as
19316/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19317///
19318/// \return A new expression if we found any potential results, ExprEmpty() if
19319/// not, and ExprError() if we diagnosed an error.
19321 NonOdrUseReason NOUR) {
19322 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19323 // an object that satisfies the requirements for appearing in a
19324 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19325 // is immediately applied." This function handles the lvalue-to-rvalue
19326 // conversion part.
19327 //
19328 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19329 // transform it into the relevant kind of non-odr-use node and rebuild the
19330 // tree of nodes leading to it.
19331 //
19332 // This is a mini-TreeTransform that only transforms a restricted subset of
19333 // nodes (and only certain operands of them).
19334
19335 // Rebuild a subexpression.
19336 auto Rebuild = [&](Expr *Sub) {
19337 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19338 };
19339
19340 // Check whether a potential result satisfies the requirements of NOUR.
19341 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19342 // Any entity other than a VarDecl is always odr-used whenever it's named
19343 // in a potentially-evaluated expression.
19344 auto *VD = dyn_cast<VarDecl>(D);
19345 if (!VD)
19346 return true;
19347
19348 // C++2a [basic.def.odr]p4:
19349 // A variable x whose name appears as a potentially-evalauted expression
19350 // e is odr-used by e unless
19351 // -- x is a reference that is usable in constant expressions, or
19352 // -- x is a variable of non-reference type that is usable in constant
19353 // expressions and has no mutable subobjects, and e is an element of
19354 // the set of potential results of an expression of
19355 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19356 // conversion is applied, or
19357 // -- x is a variable of non-reference type, and e is an element of the
19358 // set of potential results of a discarded-value expression to which
19359 // the lvalue-to-rvalue conversion is not applied
19360 //
19361 // We check the first bullet and the "potentially-evaluated" condition in
19362 // BuildDeclRefExpr. We check the type requirements in the second bullet
19363 // in CheckLValueToRValueConversionOperand below.
19364 switch (NOUR) {
19365 case NOUR_None:
19366 case NOUR_Unevaluated:
19367 llvm_unreachable("unexpected non-odr-use-reason");
19368
19369 case NOUR_Constant:
19370 // Constant references were handled when they were built.
19371 if (VD->getType()->isReferenceType())
19372 return true;
19373 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19374 if (RD->hasDefinition() && RD->hasMutableFields())
19375 return true;
19376 if (!VD->isUsableInConstantExpressions(S.Context))
19377 return true;
19378 break;
19379
19380 case NOUR_Discarded:
19381 if (VD->getType()->isReferenceType())
19382 return true;
19383 break;
19384 }
19385 return false;
19386 };
19387
19388 // Mark that this expression does not constitute an odr-use.
19389 auto MarkNotOdrUsed = [&] {
19390 S.MaybeODRUseExprs.remove(E);
19391 if (LambdaScopeInfo *LSI = S.getCurLambda())
19392 LSI->markVariableExprAsNonODRUsed(E);
19393 };
19394
19395 // C++2a [basic.def.odr]p2:
19396 // The set of potential results of an expression e is defined as follows:
19397 switch (E->getStmtClass()) {
19398 // -- If e is an id-expression, ...
19399 case Expr::DeclRefExprClass: {
19400 auto *DRE = cast<DeclRefExpr>(E);
19401 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19402 break;
19403
19404 // Rebuild as a non-odr-use DeclRefExpr.
19405 MarkNotOdrUsed();
19406 return DeclRefExpr::Create(
19407 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19408 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19409 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19410 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19411 }
19412
19413 case Expr::FunctionParmPackExprClass: {
19414 auto *FPPE = cast<FunctionParmPackExpr>(E);
19415 // If any of the declarations in the pack is odr-used, then the expression
19416 // as a whole constitutes an odr-use.
19417 for (VarDecl *D : *FPPE)
19418 if (IsPotentialResultOdrUsed(D))
19419 return ExprEmpty();
19420
19421 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19422 // nothing cares about whether we marked this as an odr-use, but it might
19423 // be useful for non-compiler tools.
19424 MarkNotOdrUsed();
19425 break;
19426 }
19427
19428 // -- If e is a subscripting operation with an array operand...
19429 case Expr::ArraySubscriptExprClass: {
19430 auto *ASE = cast<ArraySubscriptExpr>(E);
19431 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19432 if (!OldBase->getType()->isArrayType())
19433 break;
19434 ExprResult Base = Rebuild(OldBase);
19435 if (!Base.isUsable())
19436 return Base;
19437 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19438 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19439 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19440 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19441 ASE->getRBracketLoc());
19442 }
19443
19444 case Expr::MemberExprClass: {
19445 auto *ME = cast<MemberExpr>(E);
19446 // -- If e is a class member access expression [...] naming a non-static
19447 // data member...
19448 if (isa<FieldDecl>(ME->getMemberDecl())) {
19449 ExprResult Base = Rebuild(ME->getBase());
19450 if (!Base.isUsable())
19451 return Base;
19452 return MemberExpr::Create(
19453 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19454 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19455 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19456 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19457 ME->getObjectKind(), ME->isNonOdrUse());
19458 }
19459
19460 if (ME->getMemberDecl()->isCXXInstanceMember())
19461 break;
19462
19463 // -- If e is a class member access expression naming a static data member,
19464 // ...
19465 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19466 break;
19467
19468 // Rebuild as a non-odr-use MemberExpr.
19469 MarkNotOdrUsed();
19470 return MemberExpr::Create(
19471 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19472 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19473 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19474 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19475 }
19476
19477 case Expr::BinaryOperatorClass: {
19478 auto *BO = cast<BinaryOperator>(E);
19479 Expr *LHS = BO->getLHS();
19480 Expr *RHS = BO->getRHS();
19481 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19482 if (BO->getOpcode() == BO_PtrMemD) {
19483 ExprResult Sub = Rebuild(LHS);
19484 if (!Sub.isUsable())
19485 return Sub;
19486 BO->setLHS(Sub.get());
19487 // -- If e is a comma expression, ...
19488 } else if (BO->getOpcode() == BO_Comma) {
19489 ExprResult Sub = Rebuild(RHS);
19490 if (!Sub.isUsable())
19491 return Sub;
19492 BO->setRHS(Sub.get());
19493 } else {
19494 break;
19495 }
19496 return ExprResult(BO);
19497 }
19498
19499 // -- If e has the form (e1)...
19500 case Expr::ParenExprClass: {
19501 auto *PE = cast<ParenExpr>(E);
19502 ExprResult Sub = Rebuild(PE->getSubExpr());
19503 if (!Sub.isUsable())
19504 return Sub;
19505 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19506 }
19507
19508 // -- If e is a glvalue conditional expression, ...
19509 // We don't apply this to a binary conditional operator. FIXME: Should we?
19510 case Expr::ConditionalOperatorClass: {
19511 auto *CO = cast<ConditionalOperator>(E);
19512 ExprResult LHS = Rebuild(CO->getLHS());
19513 if (LHS.isInvalid())
19514 return ExprError();
19515 ExprResult RHS = Rebuild(CO->getRHS());
19516 if (RHS.isInvalid())
19517 return ExprError();
19518 if (!LHS.isUsable() && !RHS.isUsable())
19519 return ExprEmpty();
19520 if (!LHS.isUsable())
19521 LHS = CO->getLHS();
19522 if (!RHS.isUsable())
19523 RHS = CO->getRHS();
19524 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19525 CO->getCond(), LHS.get(), RHS.get());
19526 }
19527
19528 // [Clang extension]
19529 // -- If e has the form __extension__ e1...
19530 case Expr::UnaryOperatorClass: {
19531 auto *UO = cast<UnaryOperator>(E);
19532 if (UO->getOpcode() != UO_Extension)
19533 break;
19534 ExprResult Sub = Rebuild(UO->getSubExpr());
19535 if (!Sub.isUsable())
19536 return Sub;
19537 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19538 Sub.get());
19539 }
19540
19541 // [Clang extension]
19542 // -- If e has the form _Generic(...), the set of potential results is the
19543 // union of the sets of potential results of the associated expressions.
19544 case Expr::GenericSelectionExprClass: {
19545 auto *GSE = cast<GenericSelectionExpr>(E);
19546
19547 SmallVector<Expr *, 4> AssocExprs;
19548 bool AnyChanged = false;
19549 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19550 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19551 if (AssocExpr.isInvalid())
19552 return ExprError();
19553 if (AssocExpr.isUsable()) {
19554 AssocExprs.push_back(AssocExpr.get());
19555 AnyChanged = true;
19556 } else {
19557 AssocExprs.push_back(OrigAssocExpr);
19558 }
19559 }
19560
19561 void *ExOrTy = nullptr;
19562 bool IsExpr = GSE->isExprPredicate();
19563 if (IsExpr)
19564 ExOrTy = GSE->getControllingExpr();
19565 else
19566 ExOrTy = GSE->getControllingType();
19567 return AnyChanged ? S.CreateGenericSelectionExpr(
19568 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19569 GSE->getRParenLoc(), IsExpr, ExOrTy,
19570 GSE->getAssocTypeSourceInfos(), AssocExprs)
19571 : ExprEmpty();
19572 }
19573
19574 // [Clang extension]
19575 // -- If e has the form __builtin_choose_expr(...), the set of potential
19576 // results is the union of the sets of potential results of the
19577 // second and third subexpressions.
19578 case Expr::ChooseExprClass: {
19579 auto *CE = cast<ChooseExpr>(E);
19580
19581 ExprResult LHS = Rebuild(CE->getLHS());
19582 if (LHS.isInvalid())
19583 return ExprError();
19584
19585 ExprResult RHS = Rebuild(CE->getLHS());
19586 if (RHS.isInvalid())
19587 return ExprError();
19588
19589 if (!LHS.get() && !RHS.get())
19590 return ExprEmpty();
19591 if (!LHS.isUsable())
19592 LHS = CE->getLHS();
19593 if (!RHS.isUsable())
19594 RHS = CE->getRHS();
19595
19596 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19597 RHS.get(), CE->getRParenLoc());
19598 }
19599
19600 // Step through non-syntactic nodes.
19601 case Expr::ConstantExprClass: {
19602 auto *CE = cast<ConstantExpr>(E);
19603 ExprResult Sub = Rebuild(CE->getSubExpr());
19604 if (!Sub.isUsable())
19605 return Sub;
19606 return ConstantExpr::Create(S.Context, Sub.get());
19607 }
19608
19609 // We could mostly rely on the recursive rebuilding to rebuild implicit
19610 // casts, but not at the top level, so rebuild them here.
19611 case Expr::ImplicitCastExprClass: {
19612 auto *ICE = cast<ImplicitCastExpr>(E);
19613 // Only step through the narrow set of cast kinds we expect to encounter.
19614 // Anything else suggests we've left the region in which potential results
19615 // can be found.
19616 switch (ICE->getCastKind()) {
19617 case CK_NoOp:
19618 case CK_DerivedToBase:
19619 case CK_UncheckedDerivedToBase: {
19620 ExprResult Sub = Rebuild(ICE->getSubExpr());
19621 if (!Sub.isUsable())
19622 return Sub;
19623 CXXCastPath Path(ICE->path());
19624 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19625 ICE->getValueKind(), &Path);
19626 }
19627
19628 default:
19629 break;
19630 }
19631 break;
19632 }
19633
19634 default:
19635 break;
19636 }
19637
19638 // Can't traverse through this node. Nothing to do.
19639 return ExprEmpty();
19640}
19641
19643 // Check whether the operand is or contains an object of non-trivial C union
19644 // type.
19645 if (E->getType().isVolatileQualified() &&
19651
19652 // C++2a [basic.def.odr]p4:
19653 // [...] an expression of non-volatile-qualified non-class type to which
19654 // the lvalue-to-rvalue conversion is applied [...]
19656 return E;
19657
19660 if (Result.isInvalid())
19661 return ExprError();
19662 return Result.get() ? Result : E;
19663}
19664
19666 Res = CorrectDelayedTyposInExpr(Res);
19667
19668 if (!Res.isUsable())
19669 return Res;
19670
19671 // If a constant-expression is a reference to a variable where we delay
19672 // deciding whether it is an odr-use, just assume we will apply the
19673 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19674 // (a non-type template argument), we have special handling anyway.
19676}
19677
19679 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19680 // call.
19681 MaybeODRUseExprSet LocalMaybeODRUseExprs;
19682 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19683
19684 for (Expr *E : LocalMaybeODRUseExprs) {
19685 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19686 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19687 DRE->getLocation(), *this);
19688 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19689 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19690 *this);
19691 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19692 for (VarDecl *VD : *FP)
19693 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19694 } else {
19695 llvm_unreachable("Unexpected expression");
19696 }
19697 }
19698
19699 assert(MaybeODRUseExprs.empty() &&
19700 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19701}
19702
19704 ValueDecl *Var, Expr *E) {
19706 if (!VD)
19707 return;
19708
19709 const bool RefersToEnclosingScope =
19710 (SemaRef.CurContext != VD->getDeclContext() &&
19712 if (RefersToEnclosingScope) {
19713 LambdaScopeInfo *const LSI =
19714 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19715 if (LSI && (!LSI->CallOperator ||
19716 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19717 // If a variable could potentially be odr-used, defer marking it so
19718 // until we finish analyzing the full expression for any
19719 // lvalue-to-rvalue
19720 // or discarded value conversions that would obviate odr-use.
19721 // Add it to the list of potential captures that will be analyzed
19722 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19723 // unless the variable is a reference that was initialized by a constant
19724 // expression (this will never need to be captured or odr-used).
19725 //
19726 // FIXME: We can simplify this a lot after implementing P0588R1.
19727 assert(E && "Capture variable should be used in an expression.");
19728 if (!Var->getType()->isReferenceType() ||
19731 }
19732 }
19733}
19734
19737 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19738 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19739 isa<FunctionParmPackExpr>(E)) &&
19740 "Invalid Expr argument to DoMarkVarDeclReferenced");
19741 Var->setReferenced();
19742
19743 if (Var->isInvalidDecl())
19744 return;
19745
19746 auto *MSI = Var->getMemberSpecializationInfo();
19749
19750 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19751 bool UsableInConstantExpr =
19753
19754 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19755 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19756 }
19757
19758 // C++20 [expr.const]p12:
19759 // A variable [...] is needed for constant evaluation if it is [...] a
19760 // variable whose name appears as a potentially constant evaluated
19761 // expression that is either a contexpr variable or is of non-volatile
19762 // const-qualified integral type or of reference type
19763 bool NeededForConstantEvaluation =
19764 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19765
19766 bool NeedDefinition =
19767 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19768
19769 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19770 "Can't instantiate a partial template specialization.");
19771
19772 // If this might be a member specialization of a static data member, check
19773 // the specialization is visible. We already did the checks for variable
19774 // template specializations when we created them.
19775 if (NeedDefinition && TSK != TSK_Undeclared &&
19776 !isa<VarTemplateSpecializationDecl>(Var))
19778
19779 // Perform implicit instantiation of static data members, static data member
19780 // templates of class templates, and variable template specializations. Delay
19781 // instantiations of variable templates, except for those that could be used
19782 // in a constant expression.
19783 if (NeedDefinition && isTemplateInstantiation(TSK)) {
19784 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19785 // instantiation declaration if a variable is usable in a constant
19786 // expression (among other cases).
19787 bool TryInstantiating =
19789 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
19790
19791 if (TryInstantiating) {
19792 SourceLocation PointOfInstantiation =
19793 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
19794 bool FirstInstantiation = PointOfInstantiation.isInvalid();
19795 if (FirstInstantiation) {
19796 PointOfInstantiation = Loc;
19797 if (MSI)
19798 MSI->setPointOfInstantiation(PointOfInstantiation);
19799 // FIXME: Notify listener.
19800 else
19801 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
19802 }
19803
19804 if (UsableInConstantExpr) {
19805 // Do not defer instantiations of variables that could be used in a
19806 // constant expression.
19807 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
19808 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
19809 });
19810
19811 // Re-set the member to trigger a recomputation of the dependence bits
19812 // for the expression.
19813 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19814 DRE->setDecl(DRE->getDecl());
19815 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
19816 ME->setMemberDecl(ME->getMemberDecl());
19817 } else if (FirstInstantiation) {
19819 .push_back(std::make_pair(Var, PointOfInstantiation));
19820 } else {
19821 bool Inserted = false;
19822 for (auto &I : SemaRef.SavedPendingInstantiations) {
19823 auto Iter = llvm::find_if(
19824 I, [Var](const Sema::PendingImplicitInstantiation &P) {
19825 return P.first == Var;
19826 });
19827 if (Iter != I.end()) {
19829 I.erase(Iter);
19830 Inserted = true;
19831 break;
19832 }
19833 }
19834
19835 // FIXME: For a specialization of a variable template, we don't
19836 // distinguish between "declaration and type implicitly instantiated"
19837 // and "implicit instantiation of definition requested", so we have
19838 // no direct way to avoid enqueueing the pending instantiation
19839 // multiple times.
19840 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
19842 .push_back(std::make_pair(Var, PointOfInstantiation));
19843 }
19844 }
19845 }
19846
19847 // C++2a [basic.def.odr]p4:
19848 // A variable x whose name appears as a potentially-evaluated expression e
19849 // is odr-used by e unless
19850 // -- x is a reference that is usable in constant expressions
19851 // -- x is a variable of non-reference type that is usable in constant
19852 // expressions and has no mutable subobjects [FIXME], and e is an
19853 // element of the set of potential results of an expression of
19854 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19855 // conversion is applied
19856 // -- x is a variable of non-reference type, and e is an element of the set
19857 // of potential results of a discarded-value expression to which the
19858 // lvalue-to-rvalue conversion is not applied [FIXME]
19859 //
19860 // We check the first part of the second bullet here, and
19861 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19862 // FIXME: To get the third bullet right, we need to delay this even for
19863 // variables that are not usable in constant expressions.
19864
19865 // If we already know this isn't an odr-use, there's nothing more to do.
19866 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
19867 if (DRE->isNonOdrUse())
19868 return;
19869 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
19870 if (ME->isNonOdrUse())
19871 return;
19872
19873 switch (OdrUse) {
19874 case OdrUseContext::None:
19875 // In some cases, a variable may not have been marked unevaluated, if it
19876 // appears in a defaukt initializer.
19877 assert((!E || isa<FunctionParmPackExpr>(E) ||
19879 "missing non-odr-use marking for unevaluated decl ref");
19880 break;
19881
19882 case OdrUseContext::FormallyOdrUsed:
19883 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19884 // behavior.
19885 break;
19886
19887 case OdrUseContext::Used:
19888 // If we might later find that this expression isn't actually an odr-use,
19889 // delay the marking.
19891 SemaRef.MaybeODRUseExprs.insert(E);
19892 else
19894 break;
19895
19896 case OdrUseContext::Dependent:
19897 // If this is a dependent context, we don't need to mark variables as
19898 // odr-used, but we may still need to track them for lambda capture.
19899 // FIXME: Do we also need to do this inside dependent typeid expressions
19900 // (which are modeled as unevaluated at this point)?
19902 break;
19903 }
19904}
19905
19907 BindingDecl *BD, Expr *E) {
19908 BD->setReferenced();
19909
19910 if (BD->isInvalidDecl())
19911 return;
19912
19913 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19914 if (OdrUse == OdrUseContext::Used) {
19915 QualType CaptureType, DeclRefType;
19917 /*EllipsisLoc*/ SourceLocation(),
19918 /*BuildAndDiagnose*/ true, CaptureType,
19919 DeclRefType,
19920 /*FunctionScopeIndexToStopAt*/ nullptr);
19921 } else if (OdrUse == OdrUseContext::Dependent) {
19923 }
19924}
19925
19927 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
19928}
19929
19930// C++ [temp.dep.expr]p3:
19931// An id-expression is type-dependent if it contains:
19932// - an identifier associated by name lookup with an entity captured by copy
19933// in a lambda-expression that has an explicit object parameter whose type
19934// is dependent ([dcl.fct]),
19936 Sema &SemaRef, ValueDecl *D, Expr *E) {
19937 auto *ID = dyn_cast<DeclRefExpr>(E);
19938 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
19939 return;
19940
19941 // If any enclosing lambda with a dependent explicit object parameter either
19942 // explicitly captures the variable by value, or has a capture default of '='
19943 // and does not capture the variable by reference, then the type of the DRE
19944 // is dependent on the type of that lambda's explicit object parameter.
19945 auto IsDependent = [&]() {
19946 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
19947 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
19948 if (!LSI)
19949 continue;
19950
19951 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
19952 LSI->AfterParameterList)
19953 return false;
19954
19955 const auto *MD = LSI->CallOperator;
19956 if (MD->getType().isNull())
19957 continue;
19958
19959 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
19960 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
19961 !Ty->getParamType(0)->isDependentType())
19962 continue;
19963
19964 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
19965 if (C->isCopyCapture())
19966 return true;
19967 continue;
19968 }
19969
19970 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
19971 return true;
19972 }
19973 return false;
19974 }();
19975
19976 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
19977 IsDependent, SemaRef.getASTContext());
19978}
19979
19980static void
19982 bool MightBeOdrUse,
19983 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19986
19987 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
19989 if (SemaRef.getLangOpts().CPlusPlus)
19991 Var, E);
19992 return;
19993 }
19994
19995 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
19997 if (SemaRef.getLangOpts().CPlusPlus)
19999 Decl, E);
20000 return;
20001 }
20002 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20003
20004 // If this is a call to a method via a cast, also mark the method in the
20005 // derived class used in case codegen can devirtualize the call.
20006 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20007 if (!ME)
20008 return;
20009 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20010 if (!MD)
20011 return;
20012 // Only attempt to devirtualize if this is truly a virtual call.
20013 bool IsVirtualCall = MD->isVirtual() &&
20015 if (!IsVirtualCall)
20016 return;
20017
20018 // If it's possible to devirtualize the call, mark the called function
20019 // referenced.
20021 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20022 if (DM)
20023 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20024}
20025
20027 // TODO: update this with DR# once a defect report is filed.
20028 // C++11 defect. The address of a pure member should not be an ODR use, even
20029 // if it's a qualified reference.
20030 bool OdrUse = true;
20031 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20032 if (Method->isVirtual() &&
20033 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20034 OdrUse = false;
20035
20036 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20040 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20041 !FD->isDependentContext())
20042 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20043 }
20044 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20046}
20047
20049 // C++11 [basic.def.odr]p2:
20050 // A non-overloaded function whose name appears as a potentially-evaluated
20051 // expression or a member of a set of candidate functions, if selected by
20052 // overload resolution when referred to from a potentially-evaluated
20053 // expression, is odr-used, unless it is a pure virtual function and its
20054 // name is not explicitly qualified.
20055 bool MightBeOdrUse = true;
20056 if (E->performsVirtualDispatch(getLangOpts())) {
20057 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20058 if (Method->isPureVirtual())
20059 MightBeOdrUse = false;
20060 }
20062 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20063 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20065}
20066
20068 for (VarDecl *VD : *E)
20069 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20071}
20072
20073/// Perform marking for a reference to an arbitrary declaration. It
20074/// marks the declaration referenced, and performs odr-use checking for
20075/// functions and variables. This method should not be used when building a
20076/// normal expression which refers to a variable.
20078 bool MightBeOdrUse) {
20079 if (MightBeOdrUse) {
20080 if (auto *VD = dyn_cast<VarDecl>(D)) {
20082 return;
20083 }
20084 }
20085 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20086 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20087 return;
20088 }
20089 D->setReferenced();
20090}
20091
20092namespace {
20093 // Mark all of the declarations used by a type as referenced.
20094 // FIXME: Not fully implemented yet! We need to have a better understanding
20095 // of when we're entering a context we should not recurse into.
20096 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20097 // TreeTransforms rebuilding the type in a new context. Rather than
20098 // duplicating the TreeTransform logic, we should consider reusing it here.
20099 // Currently that causes problems when rebuilding LambdaExprs.
20100class MarkReferencedDecls : public DynamicRecursiveASTVisitor {
20101 Sema &S;
20103
20104public:
20105 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) {}
20106
20107 bool TraverseTemplateArgument(const TemplateArgument &Arg) override;
20108};
20109}
20110
20111bool MarkReferencedDecls::TraverseTemplateArgument(
20112 const TemplateArgument &Arg) {
20113 {
20114 // A non-type template argument is a constant-evaluated context.
20118 if (Decl *D = Arg.getAsDecl())
20119 S.MarkAnyDeclReferenced(Loc, D, true);
20120 } else if (Arg.getKind() == TemplateArgument::Expression) {
20122 }
20123 }
20124
20126}
20127
20129 MarkReferencedDecls Marker(*this, Loc);
20130 Marker.TraverseType(T);
20131}
20132
20133namespace {
20134/// Helper class that marks all of the declarations referenced by
20135/// potentially-evaluated subexpressions as "referenced".
20136class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20137public:
20138 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20139 bool SkipLocalVariables;
20141
20142 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20144 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20145
20146 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20147 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20148 }
20149
20150 void Visit(Expr *E) {
20151 if (llvm::is_contained(StopAt, E))
20152 return;
20153 Inherited::Visit(E);
20154 }
20155
20156 void VisitConstantExpr(ConstantExpr *E) {
20157 // Don't mark declarations within a ConstantExpression, as this expression
20158 // will be evaluated and folded to a value.
20159 }
20160
20161 void VisitDeclRefExpr(DeclRefExpr *E) {
20162 // If we were asked not to visit local variables, don't.
20163 if (SkipLocalVariables) {
20164 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20165 if (VD->hasLocalStorage())
20166 return;
20167 }
20168
20169 // FIXME: This can trigger the instantiation of the initializer of a
20170 // variable, which can cause the expression to become value-dependent
20171 // or error-dependent. Do we need to propagate the new dependence bits?
20173 }
20174
20175 void VisitMemberExpr(MemberExpr *E) {
20177 Visit(E->getBase());
20178 }
20179};
20180} // namespace
20181
20183 bool SkipLocalVariables,
20184 ArrayRef<const Expr*> StopAt) {
20185 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20186}
20187
20188/// Emit a diagnostic when statements are reachable.
20189/// FIXME: check for reachability even in expressions for which we don't build a
20190/// CFG (eg, in the initializer of a global or in a constant expression).
20191/// For example,
20192/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20194 const PartialDiagnostic &PD) {
20195 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20196 if (!FunctionScopes.empty())
20197 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20199 return true;
20200 }
20201
20202 // The initializer of a constexpr variable or of the first declaration of a
20203 // static data member is not syntactically a constant evaluated constant,
20204 // but nonetheless is always required to be a constant expression, so we
20205 // can skip diagnosing.
20206 // FIXME: Using the mangling context here is a hack.
20207 if (auto *VD = dyn_cast_or_null<VarDecl>(
20208 ExprEvalContexts.back().ManglingContextDecl)) {
20209 if (VD->isConstexpr() ||
20210 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20211 return false;
20212 // FIXME: For any other kind of variable, we should build a CFG for its
20213 // initializer and check whether the context in question is reachable.
20214 }
20215
20216 Diag(Loc, PD);
20217 return true;
20218}
20219
20220/// Emit a diagnostic that describes an effect on the run-time behavior
20221/// of the program being compiled.
20222///
20223/// This routine emits the given diagnostic when the code currently being
20224/// type-checked is "potentially evaluated", meaning that there is a
20225/// possibility that the code will actually be executable. Code in sizeof()
20226/// expressions, code used only during overload resolution, etc., are not
20227/// potentially evaluated. This routine will suppress such diagnostics or,
20228/// in the absolutely nutty case of potentially potentially evaluated
20229/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20230/// later.
20231///
20232/// This routine should be used for all diagnostics that describe the run-time
20233/// behavior of a program, such as passing a non-POD value through an ellipsis.
20234/// Failure to do so will likely result in spurious diagnostics or failures
20235/// during overload resolution or within sizeof/alignof/typeof/typeid.
20237 const PartialDiagnostic &PD) {
20238
20239 if (ExprEvalContexts.back().isDiscardedStatementContext())
20240 return false;
20241
20242 switch (ExprEvalContexts.back().Context) {
20247 // The argument will never be evaluated, so don't complain.
20248 break;
20249
20252 // Relevant diagnostics should be produced by constant evaluation.
20253 break;
20254
20257 return DiagIfReachable(Loc, Stmts, PD);
20258 }
20259
20260 return false;
20261}
20262
20264 const PartialDiagnostic &PD) {
20265 return DiagRuntimeBehavior(
20266 Loc, Statement ? llvm::ArrayRef(Statement) : llvm::ArrayRef<Stmt *>(),
20267 PD);
20268}
20269
20271 CallExpr *CE, FunctionDecl *FD) {
20272 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20273 return false;
20274
20275 // If we're inside a decltype's expression, don't check for a valid return
20276 // type or construct temporaries until we know whether this is the last call.
20277 if (ExprEvalContexts.back().ExprContext ==
20279 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20280 return false;
20281 }
20282
20283 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20284 FunctionDecl *FD;
20285 CallExpr *CE;
20286
20287 public:
20288 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20289 : FD(FD), CE(CE) { }
20290
20291 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20292 if (!FD) {
20293 S.Diag(Loc, diag::err_call_incomplete_return)
20294 << T << CE->getSourceRange();
20295 return;
20296 }
20297
20298 S.Diag(Loc, diag::err_call_function_incomplete_return)
20299 << CE->getSourceRange() << FD << T;
20300 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20301 << FD->getDeclName();
20302 }
20303 } Diagnoser(FD, CE);
20304
20305 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20306 return true;
20307
20308 return false;
20309}
20310
20311// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20312// will prevent this condition from triggering, which is what we want.
20315
20316 unsigned diagnostic = diag::warn_condition_is_assignment;
20317 bool IsOrAssign = false;
20318
20319 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20320 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20321 return;
20322
20323 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20324
20325 // Greylist some idioms by putting them into a warning subcategory.
20326 if (ObjCMessageExpr *ME
20327 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20328 Selector Sel = ME->getSelector();
20329
20330 // self = [<foo> init...]
20331 if (ObjC().isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20332 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20333
20334 // <foo> = [<bar> nextObject]
20335 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20336 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20337 }
20338
20339 Loc = Op->getOperatorLoc();
20340 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20341 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20342 return;
20343
20344 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20345 Loc = Op->getOperatorLoc();
20346 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20347 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20348 else {
20349 // Not an assignment.
20350 return;
20351 }
20352
20353 Diag(Loc, diagnostic) << E->getSourceRange();
20354
20357 Diag(Loc, diag::note_condition_assign_silence)
20359 << FixItHint::CreateInsertion(Close, ")");
20360
20361 if (IsOrAssign)
20362 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20364 else
20365 Diag(Loc, diag::note_condition_assign_to_comparison)
20367}
20368
20370 // Don't warn if the parens came from a macro.
20371 SourceLocation parenLoc = ParenE->getBeginLoc();
20372 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20373 return;
20374 // Don't warn for dependent expressions.
20375 if (ParenE->isTypeDependent())
20376 return;
20377
20378 Expr *E = ParenE->IgnoreParens();
20379 if (ParenE->isProducedByFoldExpansion() && ParenE->getSubExpr() == E)
20380 return;
20381
20382 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20383 if (opE->getOpcode() == BO_EQ &&
20384 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20385 == Expr::MLV_Valid) {
20386 SourceLocation Loc = opE->getOperatorLoc();
20387
20388 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20389 SourceRange ParenERange = ParenE->getSourceRange();
20390 Diag(Loc, diag::note_equality_comparison_silence)
20391 << FixItHint::CreateRemoval(ParenERange.getBegin())
20392 << FixItHint::CreateRemoval(ParenERange.getEnd());
20393 Diag(Loc, diag::note_equality_comparison_to_assign)
20395 }
20396}
20397
20399 bool IsConstexpr) {
20401 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20403
20405 if (result.isInvalid()) return ExprError();
20406 E = result.get();
20407
20408 if (!E->isTypeDependent()) {
20409 if (getLangOpts().CPlusPlus)
20410 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20411
20413 if (ERes.isInvalid())
20414 return ExprError();
20415 E = ERes.get();
20416
20417 QualType T = E->getType();
20418 if (!T->isScalarType()) { // C99 6.8.4.1p1
20419 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20420 << T << E->getSourceRange();
20421 return ExprError();
20422 }
20423 CheckBoolLikeConversion(E, Loc);
20424 }
20425
20426 return E;
20427}
20428
20430 Expr *SubExpr, ConditionKind CK,
20431 bool MissingOK) {
20432 // MissingOK indicates whether having no condition expression is valid
20433 // (for loop) or invalid (e.g. while loop).
20434 if (!SubExpr)
20435 return MissingOK ? ConditionResult() : ConditionError();
20436
20437 ExprResult Cond;
20438 switch (CK) {
20440 Cond = CheckBooleanCondition(Loc, SubExpr);
20441 break;
20442
20444 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20445 break;
20446
20448 Cond = CheckSwitchCondition(Loc, SubExpr);
20449 break;
20450 }
20451 if (Cond.isInvalid()) {
20452 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20453 {SubExpr}, PreferredConditionType(CK));
20454 if (!Cond.get())
20455 return ConditionError();
20456 }
20457 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20459 if (!FullExpr.get())
20460 return ConditionError();
20461
20462 return ConditionResult(*this, nullptr, FullExpr,
20464}
20465
20466namespace {
20467 /// A visitor for rebuilding a call to an __unknown_any expression
20468 /// to have an appropriate type.
20469 struct RebuildUnknownAnyFunction
20470 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20471
20472 Sema &S;
20473
20474 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20475
20476 ExprResult VisitStmt(Stmt *S) {
20477 llvm_unreachable("unexpected statement!");
20478 }
20479
20480 ExprResult VisitExpr(Expr *E) {
20481 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20482 << E->getSourceRange();
20483 return ExprError();
20484 }
20485
20486 /// Rebuild an expression which simply semantically wraps another
20487 /// expression which it shares the type and value kind of.
20488 template <class T> ExprResult rebuildSugarExpr(T *E) {
20489 ExprResult SubResult = Visit(E->getSubExpr());
20490 if (SubResult.isInvalid()) return ExprError();
20491
20492 Expr *SubExpr = SubResult.get();
20493 E->setSubExpr(SubExpr);
20494 E->setType(SubExpr->getType());
20495 E->setValueKind(SubExpr->getValueKind());
20496 assert(E->getObjectKind() == OK_Ordinary);
20497 return E;
20498 }
20499
20500 ExprResult VisitParenExpr(ParenExpr *E) {
20501 return rebuildSugarExpr(E);
20502 }
20503
20504 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20505 return rebuildSugarExpr(E);
20506 }
20507
20508 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20509 ExprResult SubResult = Visit(E->getSubExpr());
20510 if (SubResult.isInvalid()) return ExprError();
20511
20512 Expr *SubExpr = SubResult.get();
20513 E->setSubExpr(SubExpr);
20514 E->setType(S.Context.getPointerType(SubExpr->getType()));
20515 assert(E->isPRValue());
20516 assert(E->getObjectKind() == OK_Ordinary);
20517 return E;
20518 }
20519
20520 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20521 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20522
20523 E->setType(VD->getType());
20524
20525 assert(E->isPRValue());
20526 if (S.getLangOpts().CPlusPlus &&
20527 !(isa<CXXMethodDecl>(VD) &&
20528 cast<CXXMethodDecl>(VD)->isInstance()))
20530
20531 return E;
20532 }
20533
20534 ExprResult VisitMemberExpr(MemberExpr *E) {
20535 return resolveDecl(E, E->getMemberDecl());
20536 }
20537
20538 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20539 return resolveDecl(E, E->getDecl());
20540 }
20541 };
20542}
20543
20544/// Given a function expression of unknown-any type, try to rebuild it
20545/// to have a function type.
20547 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20548 if (Result.isInvalid()) return ExprError();
20549 return S.DefaultFunctionArrayConversion(Result.get());
20550}
20551
20552namespace {
20553 /// A visitor for rebuilding an expression of type __unknown_anytype
20554 /// into one which resolves the type directly on the referring
20555 /// expression. Strict preservation of the original source
20556 /// structure is not a goal.
20557 struct RebuildUnknownAnyExpr
20558 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20559
20560 Sema &S;
20561
20562 /// The current destination type.
20563 QualType DestType;
20564
20565 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20566 : S(S), DestType(CastType) {}
20567
20568 ExprResult VisitStmt(Stmt *S) {
20569 llvm_unreachable("unexpected statement!");
20570 }
20571
20572 ExprResult VisitExpr(Expr *E) {
20573 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20574 << E->getSourceRange();
20575 return ExprError();
20576 }
20577
20578 ExprResult VisitCallExpr(CallExpr *E);
20579 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20580
20581 /// Rebuild an expression which simply semantically wraps another
20582 /// expression which it shares the type and value kind of.
20583 template <class T> ExprResult rebuildSugarExpr(T *E) {
20584 ExprResult SubResult = Visit(E->getSubExpr());
20585 if (SubResult.isInvalid()) return ExprError();
20586 Expr *SubExpr = SubResult.get();
20587 E->setSubExpr(SubExpr);
20588 E->setType(SubExpr->getType());
20589 E->setValueKind(SubExpr->getValueKind());
20590 assert(E->getObjectKind() == OK_Ordinary);
20591 return E;
20592 }
20593
20594 ExprResult VisitParenExpr(ParenExpr *E) {
20595 return rebuildSugarExpr(E);
20596 }
20597
20598 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20599 return rebuildSugarExpr(E);
20600 }
20601
20602 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20603 const PointerType *Ptr = DestType->getAs<PointerType>();
20604 if (!Ptr) {
20605 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20606 << E->getSourceRange();
20607 return ExprError();
20608 }
20609
20610 if (isa<CallExpr>(E->getSubExpr())) {
20611 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20612 << E->getSourceRange();
20613 return ExprError();
20614 }
20615
20616 assert(E->isPRValue());
20617 assert(E->getObjectKind() == OK_Ordinary);
20618 E->setType(DestType);
20619
20620 // Build the sub-expression as if it were an object of the pointee type.
20621 DestType = Ptr->getPointeeType();
20622 ExprResult SubResult = Visit(E->getSubExpr());
20623 if (SubResult.isInvalid()) return ExprError();
20624 E->setSubExpr(SubResult.get());
20625 return E;
20626 }
20627
20628 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20629
20630 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20631
20632 ExprResult VisitMemberExpr(MemberExpr *E) {
20633 return resolveDecl(E, E->getMemberDecl());
20634 }
20635
20636 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20637 return resolveDecl(E, E->getDecl());
20638 }
20639 };
20640}
20641
20642/// Rebuilds a call expression which yielded __unknown_anytype.
20643ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20644 Expr *CalleeExpr = E->getCallee();
20645
20646 enum FnKind {
20647 FK_MemberFunction,
20648 FK_FunctionPointer,
20649 FK_BlockPointer
20650 };
20651
20652 FnKind Kind;
20653 QualType CalleeType = CalleeExpr->getType();
20654 if (CalleeType == S.Context.BoundMemberTy) {
20655 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20656 Kind = FK_MemberFunction;
20657 CalleeType = Expr::findBoundMemberType(CalleeExpr);
20658 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20659 CalleeType = Ptr->getPointeeType();
20660 Kind = FK_FunctionPointer;
20661 } else {
20662 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20663 Kind = FK_BlockPointer;
20664 }
20665 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20666
20667 // Verify that this is a legal result type of a function.
20668 if (DestType->isArrayType() || DestType->isFunctionType()) {
20669 unsigned diagID = diag::err_func_returning_array_function;
20670 if (Kind == FK_BlockPointer)
20671 diagID = diag::err_block_returning_array_function;
20672
20673 S.Diag(E->getExprLoc(), diagID)
20674 << DestType->isFunctionType() << DestType;
20675 return ExprError();
20676 }
20677
20678 // Otherwise, go ahead and set DestType as the call's result.
20679 E->setType(DestType.getNonLValueExprType(S.Context));
20681 assert(E->getObjectKind() == OK_Ordinary);
20682
20683 // Rebuild the function type, replacing the result type with DestType.
20684 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20685 if (Proto) {
20686 // __unknown_anytype(...) is a special case used by the debugger when
20687 // it has no idea what a function's signature is.
20688 //
20689 // We want to build this call essentially under the K&R
20690 // unprototyped rules, but making a FunctionNoProtoType in C++
20691 // would foul up all sorts of assumptions. However, we cannot
20692 // simply pass all arguments as variadic arguments, nor can we
20693 // portably just call the function under a non-variadic type; see
20694 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20695 // However, it turns out that in practice it is generally safe to
20696 // call a function declared as "A foo(B,C,D);" under the prototype
20697 // "A foo(B,C,D,...);". The only known exception is with the
20698 // Windows ABI, where any variadic function is implicitly cdecl
20699 // regardless of its normal CC. Therefore we change the parameter
20700 // types to match the types of the arguments.
20701 //
20702 // This is a hack, but it is far superior to moving the
20703 // corresponding target-specific code from IR-gen to Sema/AST.
20704
20705 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20706 SmallVector<QualType, 8> ArgTypes;
20707 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20708 ArgTypes.reserve(E->getNumArgs());
20709 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20710 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20711 }
20712 ParamTypes = ArgTypes;
20713 }
20714 DestType = S.Context.getFunctionType(DestType, ParamTypes,
20715 Proto->getExtProtoInfo());
20716 } else {
20717 DestType = S.Context.getFunctionNoProtoType(DestType,
20718 FnType->getExtInfo());
20719 }
20720
20721 // Rebuild the appropriate pointer-to-function type.
20722 switch (Kind) {
20723 case FK_MemberFunction:
20724 // Nothing to do.
20725 break;
20726
20727 case FK_FunctionPointer:
20728 DestType = S.Context.getPointerType(DestType);
20729 break;
20730
20731 case FK_BlockPointer:
20732 DestType = S.Context.getBlockPointerType(DestType);
20733 break;
20734 }
20735
20736 // Finally, we can recurse.
20737 ExprResult CalleeResult = Visit(CalleeExpr);
20738 if (!CalleeResult.isUsable()) return ExprError();
20739 E->setCallee(CalleeResult.get());
20740
20741 // Bind a temporary if necessary.
20742 return S.MaybeBindToTemporary(E);
20743}
20744
20745ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20746 // Verify that this is a legal result type of a call.
20747 if (DestType->isArrayType() || DestType->isFunctionType()) {
20748 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20749 << DestType->isFunctionType() << DestType;
20750 return ExprError();
20751 }
20752
20753 // Rewrite the method result type if available.
20754 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20755 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20756 Method->setReturnType(DestType);
20757 }
20758
20759 // Change the type of the message.
20760 E->setType(DestType.getNonReferenceType());
20762
20763 return S.MaybeBindToTemporary(E);
20764}
20765
20766ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
20767 // The only case we should ever see here is a function-to-pointer decay.
20768 if (E->getCastKind() == CK_FunctionToPointerDecay) {
20769 assert(E->isPRValue());
20770 assert(E->getObjectKind() == OK_Ordinary);
20771
20772 E->setType(DestType);
20773
20774 // Rebuild the sub-expression as the pointee (function) type.
20775 DestType = DestType->castAs<PointerType>()->getPointeeType();
20776
20777 ExprResult Result = Visit(E->getSubExpr());
20778 if (!Result.isUsable()) return ExprError();
20779
20780 E->setSubExpr(Result.get());
20781 return E;
20782 } else if (E->getCastKind() == CK_LValueToRValue) {
20783 assert(E->isPRValue());
20784 assert(E->getObjectKind() == OK_Ordinary);
20785
20786 assert(isa<BlockPointerType>(E->getType()));
20787
20788 E->setType(DestType);
20789
20790 // The sub-expression has to be a lvalue reference, so rebuild it as such.
20791 DestType = S.Context.getLValueReferenceType(DestType);
20792
20793 ExprResult Result = Visit(E->getSubExpr());
20794 if (!Result.isUsable()) return ExprError();
20795
20796 E->setSubExpr(Result.get());
20797 return E;
20798 } else {
20799 llvm_unreachable("Unhandled cast type!");
20800 }
20801}
20802
20803ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
20804 ExprValueKind ValueKind = VK_LValue;
20805 QualType Type = DestType;
20806
20807 // We know how to make this work for certain kinds of decls:
20808
20809 // - functions
20810 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
20811 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
20812 DestType = Ptr->getPointeeType();
20813 ExprResult Result = resolveDecl(E, VD);
20814 if (Result.isInvalid()) return ExprError();
20815 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
20816 VK_PRValue);
20817 }
20818
20819 if (!Type->isFunctionType()) {
20820 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
20821 << VD << E->getSourceRange();
20822 return ExprError();
20823 }
20824 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
20825 // We must match the FunctionDecl's type to the hack introduced in
20826 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20827 // type. See the lengthy commentary in that routine.
20828 QualType FDT = FD->getType();
20829 const FunctionType *FnType = FDT->castAs<FunctionType>();
20830 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
20831 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
20832 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
20833 SourceLocation Loc = FD->getLocation();
20835 S.Context, FD->getDeclContext(), Loc, Loc,
20836 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
20838 false /*isInlineSpecified*/, FD->hasPrototype(),
20839 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
20840
20841 if (FD->getQualifier())
20842 NewFD->setQualifierInfo(FD->getQualifierLoc());
20843
20845 for (const auto &AI : FT->param_types()) {
20846 ParmVarDecl *Param =
20848 Param->setScopeInfo(0, Params.size());
20849 Params.push_back(Param);
20850 }
20851 NewFD->setParams(Params);
20852 DRE->setDecl(NewFD);
20853 VD = DRE->getDecl();
20854 }
20855 }
20856
20857 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
20858 if (MD->isInstance()) {
20859 ValueKind = VK_PRValue;
20861 }
20862
20863 // Function references aren't l-values in C.
20864 if (!S.getLangOpts().CPlusPlus)
20865 ValueKind = VK_PRValue;
20866
20867 // - variables
20868 } else if (isa<VarDecl>(VD)) {
20869 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
20870 Type = RefTy->getPointeeType();
20871 } else if (Type->isFunctionType()) {
20872 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
20873 << VD << E->getSourceRange();
20874 return ExprError();
20875 }
20876
20877 // - nothing else
20878 } else {
20879 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
20880 << VD << E->getSourceRange();
20881 return ExprError();
20882 }
20883
20884 // Modifying the declaration like this is friendly to IR-gen but
20885 // also really dangerous.
20886 VD->setType(DestType);
20887 E->setType(Type);
20888 E->setValueKind(ValueKind);
20889 return E;
20890}
20891
20895 // The type we're casting to must be either void or complete.
20896 if (!CastType->isVoidType() &&
20898 diag::err_typecheck_cast_to_incomplete))
20899 return ExprError();
20900
20901 // Rewrite the casted expression from scratch.
20902 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
20903 if (!result.isUsable()) return ExprError();
20904
20905 CastExpr = result.get();
20906 VK = CastExpr->getValueKind();
20907 CastKind = CK_NoOp;
20908
20909 return CastExpr;
20910}
20911
20913 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
20914}
20915
20917 Expr *arg, QualType &paramType) {
20918 // If the syntactic form of the argument is not an explicit cast of
20919 // any sort, just do default argument promotion.
20920 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
20921 if (!castArg) {
20923 if (result.isInvalid()) return ExprError();
20924 paramType = result.get()->getType();
20925 return result;
20926 }
20927
20928 // Otherwise, use the type that was written in the explicit cast.
20929 assert(!arg->hasPlaceholderType());
20930 paramType = castArg->getTypeAsWritten();
20931
20932 // Copy-initialize a parameter of that type.
20933 InitializedEntity entity =
20935 /*consumed*/ false);
20936 return PerformCopyInitialization(entity, callLoc, arg);
20937}
20938
20940 Expr *orig = E;
20941 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
20942 while (true) {
20943 E = E->IgnoreParenImpCasts();
20944 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
20945 E = call->getCallee();
20946 diagID = diag::err_uncasted_call_of_unknown_any;
20947 } else {
20948 break;
20949 }
20950 }
20951
20952 SourceLocation loc;
20953 NamedDecl *d;
20954 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
20955 loc = ref->getLocation();
20956 d = ref->getDecl();
20957 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
20958 loc = mem->getMemberLoc();
20959 d = mem->getMemberDecl();
20960 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
20961 diagID = diag::err_uncasted_call_of_unknown_any;
20962 loc = msg->getSelectorStartLoc();
20963 d = msg->getMethodDecl();
20964 if (!d) {
20965 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
20966 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
20967 << orig->getSourceRange();
20968 return ExprError();
20969 }
20970 } else {
20971 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20972 << E->getSourceRange();
20973 return ExprError();
20974 }
20975
20976 S.Diag(loc, diagID) << d << orig->getSourceRange();
20977
20978 // Never recoverable.
20979 return ExprError();
20980}
20981
20984 // C cannot handle TypoExpr nodes on either side of a binop because it
20985 // doesn't handle dependent types properly, so make sure any TypoExprs have
20986 // been dealt with before checking the operands.
20988 if (!Result.isUsable()) return ExprError();
20989 E = Result.get();
20990 }
20991
20992 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
20993 if (!placeholderType) return E;
20994
20995 switch (placeholderType->getKind()) {
20996 case BuiltinType::UnresolvedTemplate: {
20997 auto *ULE = cast<UnresolvedLookupExpr>(E);
20998 const DeclarationNameInfo &NameInfo = ULE->getNameInfo();
20999 // There's only one FoundDecl for UnresolvedTemplate type. See
21000 // BuildTemplateIdExpr.
21001 NamedDecl *Temp = *ULE->decls_begin();
21002 const bool IsTypeAliasTemplateDecl = isa<TypeAliasTemplateDecl>(Temp);
21003
21004 if (NestedNameSpecifierLoc Loc = ULE->getQualifierLoc(); Loc.hasQualifier())
21005 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21006 << Loc.getNestedNameSpecifier() << NameInfo.getName().getAsString()
21007 << Loc.getSourceRange() << IsTypeAliasTemplateDecl;
21008 else
21009 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_type_template)
21010 << "" << NameInfo.getName().getAsString() << ULE->getSourceRange()
21011 << IsTypeAliasTemplateDecl;
21012 Diag(Temp->getLocation(), diag::note_referenced_type_template)
21013 << IsTypeAliasTemplateDecl;
21014
21015 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
21016 }
21017
21018 // Overloaded expressions.
21019 case BuiltinType::Overload: {
21020 // Try to resolve a single function template specialization.
21021 // This is obligatory.
21024 return Result;
21025
21026 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21027 // leaves Result unchanged on failure.
21028 Result = E;
21030 return Result;
21031
21032 // If that failed, try to recover with a call.
21033 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21034 /*complain*/ true);
21035 return Result;
21036 }
21037
21038 // Bound member functions.
21039 case BuiltinType::BoundMember: {
21040 ExprResult result = E;
21041 const Expr *BME = E->IgnoreParens();
21042 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21043 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21044 if (isa<CXXPseudoDestructorExpr>(BME)) {
21045 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21046 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21047 if (ME->getMemberNameInfo().getName().getNameKind() ==
21049 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21050 }
21051 tryToRecoverWithCall(result, PD,
21052 /*complain*/ true);
21053 return result;
21054 }
21055
21056 // ARC unbridged casts.
21057 case BuiltinType::ARCUnbridgedCast: {
21058 Expr *realCast = ObjC().stripARCUnbridgedCast(E);
21059 ObjC().diagnoseARCUnbridgedCast(realCast);
21060 return realCast;
21061 }
21062
21063 // Expressions of unknown type.
21064 case BuiltinType::UnknownAny:
21065 return diagnoseUnknownAnyExpr(*this, E);
21066
21067 // Pseudo-objects.
21068 case BuiltinType::PseudoObject:
21069 return PseudoObject().checkRValue(E);
21070
21071 case BuiltinType::BuiltinFn: {
21072 // Accept __noop without parens by implicitly converting it to a call expr.
21073 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21074 if (DRE) {
21075 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21076 unsigned BuiltinID = FD->getBuiltinID();
21077 if (BuiltinID == Builtin::BI__noop) {
21078 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21079 CK_BuiltinFnToFnPtr)
21080 .get();
21081 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21084 }
21085
21086 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21087 // Any use of these other than a direct call is ill-formed as of C++20,
21088 // because they are not addressable functions. In earlier language
21089 // modes, warn and force an instantiation of the real body.
21090 Diag(E->getBeginLoc(),
21092 ? diag::err_use_of_unaddressable_function
21093 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21094 if (FD->isImplicitlyInstantiable()) {
21095 // Require a definition here because a normal attempt at
21096 // instantiation for a builtin will be ignored, and we won't try
21097 // again later. We assume that the definition of the template
21098 // precedes this use.
21100 /*Recursive=*/false,
21101 /*DefinitionRequired=*/true,
21102 /*AtEndOfTU=*/false);
21103 }
21104 // Produce a properly-typed reference to the function.
21105 CXXScopeSpec SS;
21106 SS.Adopt(DRE->getQualifierLoc());
21107 TemplateArgumentListInfo TemplateArgs;
21108 DRE->copyTemplateArgumentsInto(TemplateArgs);
21109 return BuildDeclRefExpr(
21110 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21111 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21112 DRE->getTemplateKeywordLoc(),
21113 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21114 }
21115 }
21116
21117 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21118 return ExprError();
21119 }
21120
21121 case BuiltinType::IncompleteMatrixIdx:
21122 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
21123 ->getRowIdx()
21124 ->getBeginLoc(),
21125 diag::err_matrix_incomplete_index);
21126 return ExprError();
21127
21128 // Expressions of unknown type.
21129 case BuiltinType::ArraySection:
21130 Diag(E->getBeginLoc(), diag::err_array_section_use)
21131 << cast<ArraySectionExpr>(E)->isOMPArraySection();
21132 return ExprError();
21133
21134 // Expressions of unknown type.
21135 case BuiltinType::OMPArrayShaping:
21136 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21137
21138 case BuiltinType::OMPIterator:
21139 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21140
21141 // Everything else should be impossible.
21142#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21143 case BuiltinType::Id:
21144#include "clang/Basic/OpenCLImageTypes.def"
21145#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21146 case BuiltinType::Id:
21147#include "clang/Basic/OpenCLExtensionTypes.def"
21148#define SVE_TYPE(Name, Id, SingletonId) \
21149 case BuiltinType::Id:
21150#include "clang/Basic/AArch64SVEACLETypes.def"
21151#define PPC_VECTOR_TYPE(Name, Id, Size) \
21152 case BuiltinType::Id:
21153#include "clang/Basic/PPCTypes.def"
21154#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21155#include "clang/Basic/RISCVVTypes.def"
21156#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21157#include "clang/Basic/WebAssemblyReferenceTypes.def"
21158#define AMDGPU_TYPE(Name, Id, SingletonId, Width, Align) case BuiltinType::Id:
21159#include "clang/Basic/AMDGPUTypes.def"
21160#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21161#include "clang/Basic/HLSLIntangibleTypes.def"
21162#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21163#define PLACEHOLDER_TYPE(Id, SingletonId)
21164#include "clang/AST/BuiltinTypes.def"
21165 break;
21166 }
21167
21168 llvm_unreachable("invalid placeholder type!");
21169}
21170
21172 if (E->isTypeDependent())
21173 return true;
21176 return false;
21177}
21178
21180 ArrayRef<Expr *> SubExprs, QualType T) {
21181 if (!Context.getLangOpts().RecoveryAST)
21182 return ExprError();
21183
21184 if (isSFINAEContext())
21185 return ExprError();
21186
21187 if (T.isNull() || T->isUndeducedType() ||
21188 !Context.getLangOpts().RecoveryASTType)
21189 // We don't know the concrete type, fallback to dependent type.
21191
21192 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21193}
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:1136
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:9126
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
Definition: SemaExpr.cpp:17748
static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope, IdentifierInfo *UDSuffix, SourceLocation UDSuffixLoc, ArrayRef< Expr * > Args, SourceLocation LitEndLoc)
BuildCookedLiteralOperatorCall - A user-defined literal was found.
Definition: SemaExpr.cpp:1940
static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHS, Expr *RHS)
Build an overloaded binary operator expression in the given scope.
Definition: SemaExpr.cpp:15320
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:10010
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:18699
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:10773
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:15069
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
Definition: SemaExpr.cpp:6133
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:10692
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:8697
static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D, bool AcceptInvalid)
Diagnoses obvious problems with the use of the given declaration as an expression.
Definition: SemaExpr.cpp:3157
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
Definition: SemaExpr.cpp:8146
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:8352
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:11739
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:10737
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:11689
static bool isParenthetizedAndQualifiedAddressOfExpr(Expr *Fn)
Definition: SemaExpr.cpp:5796
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
Definition: SemaExpr.cpp:2225
@ ConstMethod
Definition: SemaExpr.cpp:13358
@ ConstUnknown
Definition: SemaExpr.cpp:13360
@ ConstVariable
Definition: SemaExpr.cpp:13356
@ NestedConstMember
Definition: SemaExpr.cpp:13359
@ ConstMember
Definition: SemaExpr.cpp:13357
@ ConstFunction
Definition: SemaExpr.cpp:13355
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:14545
static void DetectPrecisionLossInComplexDivision(Sema &S, SourceLocation OpLoc, Expr *Operand)
Definition: SemaExpr.cpp:15251
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:18086
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
Definition: SemaExpr.cpp:13295
@ NCCK_Block
Definition: SemaExpr.cpp:13295
@ NCCK_None
Definition: SemaExpr.cpp:13295
@ NCCK_Lambda
Definition: SemaExpr.cpp:13295
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:9899
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:9175
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:6065
static Expr * recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context, DeclarationNameInfo &NameInfo, SourceLocation TemplateKWLoc, const TemplateArgumentListInfo *TemplateArgs)
In Microsoft mode, if we are inside a template class whose parent class has dependent base classes,...
Definition: SemaExpr.cpp:2635
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(Sema &SemaRef, ValueDecl *D, Expr *E)
Definition: SemaExpr.cpp:19935
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18551
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:16811
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:8601
static Decl * getPredefinedExprDecl(DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
Definition: SemaExpr.cpp:1924
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:16694
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
Definition: SemaExpr.cpp:13870
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
Definition: SemaExpr.cpp:4720
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12151
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
Definition: SemaExpr.cpp:14445
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
Definition: SemaExpr.cpp:4334
static bool ExprLooksBoolean(const Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
Definition: SemaExpr.cpp:8676
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
Definition: SemaExpr.cpp:17935
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:14601
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:10859
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
Definition: SemaExpr.cpp:7989
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19735
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
Definition: SemaExpr.cpp:3182
static bool checkCondition(Sema &S, const Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
Definition: SemaExpr.cpp:7955
static bool checkForArray(const Expr *E)
Definition: SemaExpr.cpp:11781
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
Definition: SemaExpr.cpp:6408
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
Definition: SemaExpr.cpp:13492
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19981
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:9948
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
Definition: SemaExpr.cpp:19703
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:14427
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
Definition: SemaExpr.cpp:17598
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:12026
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:8631
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:14699
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
Definition: SemaExpr.cpp:1310
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
Definition: SemaExpr.cpp:6298
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:9563
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:8270
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
Definition: SemaExpr.cpp:7976
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
Definition: SemaExpr.cpp:10704
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:14684
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
Definition: SemaExpr.cpp:4777
static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8902
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
Definition: SemaExpr.cpp:17640
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:15160
static void emitEmptyLookupTypoDiagnostic(const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, DeclarationName Typo, SourceLocation TypoLoc, ArrayRef< Expr * > Args, unsigned DiagnosticID, unsigned DiagnosticSuggestID)
Definition: SemaExpr.cpp:2360
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation OpLoc, bool IsInc, bool IsPrefix)
CheckIncrementDecrementOperand - unlike most "Check" methods, this routine doesn't need to call Usual...
Definition: SemaExpr.cpp:13975
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:8215
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:8324
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10531
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
Definition: SemaExpr.cpp:11840
static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T, const Expr *E)
Check whether E is a pointer from a decayed array type (the decayed pointer type is equal to T) and e...
Definition: SemaExpr.cpp:4211
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
Definition: SemaExpr.cpp:10579
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
Definition: SemaExpr.cpp:3474
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
Definition: SemaExpr.cpp:5755
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:11228
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4118
static Sema::AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
Definition: SemaExpr.cpp:9075
static bool unsupportedTypeConversion(const Sema &S, QualType LHSType, QualType RHSType)
Diagnose attempts to convert between __float128, __ibm128 and long double if there is no support for ...
Definition: SemaExpr.cpp:1267
static void MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
Definition: SemaExpr.cpp:18378
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:10889
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:13556
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:14077
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:17966
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:11590
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
Definition: SemaExpr.cpp:15217
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
Definition: SemaExpr.cpp:14137
static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle conversions with GCC complex int extension.
Definition: SemaExpr.cpp:1360
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
Definition: SemaExpr.cpp:4791
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:10057
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:18739
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the left hand of a '||' expr.
Definition: SemaExpr.cpp:15124
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:8731
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:18054
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:13367
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
Definition: SemaExpr.cpp:3605
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
Definition: SemaExpr.cpp:13345
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:18495
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
Definition: SemaExpr.cpp:10751
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4163
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:11423
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12069
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:20939
static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc, unsigned Offset)
getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the location of the token and the off...
Definition: SemaExpr.cpp:1932
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
Definition: SemaExpr.cpp:8390
OriginalExprKind
Definition: SemaExpr.cpp:13486
@ OEK_Variable
Definition: SemaExpr.cpp:13487
@ OEK_LValue
Definition: SemaExpr.cpp:13489
@ OEK_Member
Definition: SemaExpr.cpp:13488
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:18631
static QualType handleFloatConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmethic conversion with floating point types.
Definition: SemaExpr.cpp:1217
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
Definition: SemaExpr.cpp:10679
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:11329
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
Definition: SemaExpr.cpp:18454
static FieldDecl * FindFieldDeclInstantiationPattern(const ASTContext &Ctx, FieldDecl *Field)
Definition: SemaExpr.cpp:5564
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
Definition: SemaExpr.cpp:1292
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
Definition: SemaExpr.cpp:10495
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:13282
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:11797
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:18872
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:6367
static bool checkPtrAuthTypeDiscriminatorOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4148
static Sema::AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, SourceLocation Loc)
Definition: SemaExpr.cpp:8923
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4136
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
Definition: SemaExpr.cpp:15145
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
Definition: SemaExpr.cpp:4810
static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc, Sema::ArithConvKind ACK)
Check that the usual arithmetic conversions can be performed on this pair of expressions that might b...
Definition: SemaExpr.cpp:1492
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
Definition: SemaExpr.cpp:10940
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:6325
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
Definition: SemaExpr.cpp:1406
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4193
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
Definition: SemaExpr.cpp:10721
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:8185
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:11987
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
Definition: SemaExpr.cpp:12851
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
Definition: SemaExpr.cpp:8304
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:8616
static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr, ExprResult &ComplexExpr, QualType IntTy, QualType ComplexTy, bool SkipCast)
Convert complex integers to complex floats and real integers to real floats as required for complex a...
Definition: SemaExpr.cpp:1111
static std::pair< ExprResult, ExprResult > CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:14732
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:14643
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:20546
static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr, ExprResult &IntExpr, QualType FloatTy, QualType IntTy, bool ConvertFloat, bool ConvertInt)
Handle arithmetic conversion from integer to float.
Definition: SemaExpr.cpp:1186
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
Definition: SemaExpr.cpp:11642
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, QualType ShorterType, QualType LongerType, bool PromotePrecision)
Definition: SemaExpr.cpp:1139
static FunctionDecl * rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context, FunctionDecl *FDecl, MultiExprArg ArgExprs)
If a builtin function has a pointer argument with no explicit address space, then it should be able t...
Definition: SemaExpr.cpp:6225
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
Definition: SemaExpr.cpp:19906
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind)
Definition: SemaExpr.cpp:1900
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition: SemaExpr.cpp:107
static QualType handleFixedPointConversion(Sema &S, QualType LHSTy, QualType RHSTy)
handleFixedPointConversion - Fixed point operations between fixed point types and integers or other f...
Definition: SemaExpr.cpp:1453
static QualType handleComplexConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
Definition: SemaExpr.cpp:1162
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:13939
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
Definition: SemaExpr.cpp:18846
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:10669
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
Definition: SemaExpr.cpp:11579
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:14755
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:11629
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:13296
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:8120
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15189
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:15175
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:11619
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
Definition: SemaExpr.cpp:15112
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
Definition: SemaExpr.cpp:4400
static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int, QualType OtherIntTy)
Test if a (constant) integer Int can be casted to another integer type IntTy without losing precision...
Definition: SemaExpr.cpp:9969
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18532
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:15499
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
Definition: SemaExpr.cpp:13684
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13091
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:19320
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
Definition: SemaExpr.cpp:18000
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:11222
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:10805
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:7500
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:4901
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:5275
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:5286
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5462
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:4923
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:1372
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1439
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2104
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2233
bool isRequiresExprBody() const
Definition: DeclBase.h:2189
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1345
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1866
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:2010
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1780
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1649
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:2036
bool isFunctionOrMethod() const
Definition: DeclBase.h:2156
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1296
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1415
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:786
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1989
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:800
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
DeclaratorContext getContext() const
Definition: DeclSpec.h:2075
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2086
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2333
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:531
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:939
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:713
Recursive AST visitor that supports extension via dynamic dispatch.
virtual bool TraverseTemplateArgument(const TemplateArgument &Arg)
Recursively visit a template argument and dispatch to the appropriate method for the argument type.
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h: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:3969
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:4221
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:979
bool isFPConstrained() const
Definition: LangOptions.h:907
RoundingMode getRoundingMode() const
Definition: LangOptions.h:913
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:3738
bool isImmediateFunction() const
Definition: Decl.cpp:3300
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3898
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3653
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3756
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:3513
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:4004
bool isConsteval() const
Definition: Decl.h:2410
size_t param_size() const
Definition: Decl.h:2665
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3163
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition: Decl.cpp:3914
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:4521
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:7637
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:462
FPEvalMethodKind
Possible float expression evaluation method choices.
Definition: LangOptions.h:300
@ FEM_Extended
Use extended type for fp arithmetic.
Definition: LangOptions.h:309
@ FEM_Double
Use the type double for fp arithmetic.
Definition: LangOptions.h:307
@ 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:314
@ FEM_Source
Use the declared type for fp arithmetic.
Definition: LangOptions.h:305
@ 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:500
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:535
bool isSubscriptPointerArithmetic() const
Definition: LangOptions.h:668
bool isSignedOverflowDefined() const
Definition: LangOptions.h:664
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:4351
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:4773
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5894
Represents a parameter to a function.
Definition: Decl.h:1725
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1854
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1758
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1858
QualType getOriginalType() const
Definition: Decl.cpp:2931
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2922
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3023
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h: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:5226
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:2708
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:8049
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:12133
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:7230
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T)
Definition: SemaExpr.cpp:17152
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:17158
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:465
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:14566
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:6395
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition: Sema.h:7802
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:13155
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:733
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:15832
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:7852
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15509
bool isAlwaysConstantEvaluatedContext() const
Definition: Sema.h:7770
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:6470
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Definition: SemaDecl.cpp:15171
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:7845
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:8991
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition: Sema.h:9030
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:8999
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:19665
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13169
VariadicCallType
Definition: Sema.h:2316
@ VariadicDoesNotApply
Definition: Sema.h:2321
@ VariadicFunction
Definition: Sema.h:2317
@ VariadicMethod
Definition: Sema.h:2319
@ VariadicConstructor
Definition: Sema.h:2320
@ VariadicBlock
Definition: Sema.h:2318
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2452
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:7041
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:3639
@ NTCUC_Assignment
Definition: Sema.h:3637
@ NTCUC_FunctionReturn
Definition: Sema.h:3629
@ NTCUC_LValueToRValueVolatile
Definition: Sema.h:3643
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:7545
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs)
Decomposes the given name into a DeclarationNameInfo, its location, and possibly a list of template a...
Definition: SemaExpr.cpp:2338
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition: Sema.h:1127
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:15851
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:17470
void ActOnStmtExprError()
Definition: SemaExpr.cpp:15857
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:20182
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
Definition: SemaExpr.cpp:1557
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
Definition: SemaExpr.cpp:12178
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:16441
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition: Sema.h:857
SemaCUDA & CUDA()
Definition: Sema.h:1072
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17405
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:20398
ConditionKind
Definition: Sema.h:7352
@ Boolean
A boolean condition, from 'if', 'while', 'for', or 'do'.
@ Switch
An integral condition for a 'switch' statement.
@ ConstexprIf
A constant boolean condition from 'if constexpr'.
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2676
bool needsRebuildOfDefaultArgOrInit() const
Definition: Sema.h:7790
SourceLocation LocationOfExcessPrecisionNotSatisfied
Definition: Sema.h:7932
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:850
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:2292
Preprocessor & getPreprocessor() const
Definition: Sema.h:532
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
Definition: Sema.h:6448
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2161
QualType GetSignedSizelessVectorType(QualType V)
Definition: SemaExpr.cpp:12737
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:7921
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3538
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition: Sema.h:7833
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:18448
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:17163
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
Definition: SemaExpr.cpp:6683
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:10149
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:1666
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types? I.e.
Definition: SemaExpr.cpp:7519
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:15870
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:16513
ExpressionEvaluationContextRecord & parentEvaluationContext()
Definition: Sema.h:6460
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:784
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
ExprResult CheckUnevaluatedOperand(Expr *E)
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
Definition: SemaExpr.cpp:1042
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Look for instances where it is likely the comma operator is confused with another operator.
Definition: SemaExpr.cpp:13890
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Definition: SemaExpr.cpp:4999
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
std::vector< Token > ExpandFunctionLocalPredefinedMacros(ArrayRef< Token > Toks)
Definition: SemaExpr.cpp:1999
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
Definition: SemaExpr.cpp:7629
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:14170
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15158
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:1120
ASTContext & Context
Definition: Sema.h:910
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:7757
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
Definition: SemaCast.cpp:2704
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12973
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:9839
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:20193
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:11515
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:530
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:7894
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:21171
SemaObjC & ObjC()
Definition: Sema.h:1112
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
Definition: SemaExpr.cpp:13008
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:2670
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:7244
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:19678
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:752
bool isImmediateFunctionContext() const
Definition: Sema.h:7782
ASTContext & getASTContext() const
Definition: Sema.h:533
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:15788
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:18948
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:19926
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
Definition: SemaExpr.cpp:15306
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:17838
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9582
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:867
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
Definition: SemaExpr.cpp:3486
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
Definition: SemaExpr.cpp:6200
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3101
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr)
Definition: SemaExpr.cpp:7055
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:15838
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:5607
@ None
This is not a defaultable comparison operator.
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:7910
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:13054
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:818
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:2204
void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitMoveConstructor - Checks for feasibility of defining this constructor as the move const...
ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16126
ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< TypeSourceInfo * > Types, ArrayRef< Expr * > Exprs)
ControllingExprOrType is either a TypeSourceInfo * or an Expr *.
Definition: SemaExpr.cpp:1671
AssumedTemplateKind
Definition: Sema.h:11115
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
Definition: SemaExpr.cpp:1969
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
SourceRange getExprRange(Expr *E) const
Definition: SemaExpr.cpp:507
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition: Sema.h:673
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:7817
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:528
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition: Sema.h:7915
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20429
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:82
@ UPPC_Block
Block expression.
Definition: Sema.h:13986
const LangOptions & getLangOpts() const
Definition: Sema.h:526
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:12205
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:7293
SemaOpenACC & OpenACC()
Definition: Sema.h:1117
ReuseLambdaContextDecl_t
Definition: Sema.h:6532
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:17501
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
Definition: SemaExpr.cpp:2252
void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK)
void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc)
Produce diagnostics if FD is an aligned allocation or deallocation function that is unavailable.
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, QualType ObjectType, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E)
Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
Definition: SemaExpr.cpp:20067
Preprocessor & PP
Definition: Sema.h:909
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:10950
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5711
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:6476
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
Definition: SemaExpr.cpp:14142
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
Definition: SemaExpr.cpp:16794
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
Definition: SemaExpr.cpp:4712
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:1980
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
Definition: SemaExpr.cpp:7534
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:908
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
Definition: SemaExpr.cpp:15940
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2406
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:6733
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17522
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:7600
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:6037
SemaHLSL & HLSL()
Definition: Sema.h:1077
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:17486
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition: Sema.h:15182
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:20077
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:9863
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:6481
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:6063
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:9583
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:13556
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:936
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
Definition: SemaExpr.cpp:15751
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:941
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
Definition: SemaExpr.cpp:3638
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
Definition: SemaExpr.cpp:10417
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:9634
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:6478
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:2144
void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor)
DefineImplicitDefaultConstructor - Checks for feasibility of defining this constructor as the default...
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:640
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3189
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition: Sema.h:7786
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
Definition: SemaExpr.cpp:7280
ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool PredicateIsExpr, void *ControllingExprOrType, ArrayRef< ParsedType > ArgTypes, ArrayRef< Expr * > ArgExprs)
ControllingExprOrType is either an opaque pointer coming out of a ParsedType or an Expr *.
Definition: SemaExpr.cpp:1639
void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockError - If there is an error parsing a block, this callback is invoked to pop the informati...
Definition: SemaExpr.cpp:16302
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7670
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2361
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1045
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:7583
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:20892
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:12157
@ VAK_Invalid
Definition: Sema.h:7541
@ VAK_Valid
Definition: Sema.h:7537
@ VAK_ValidInCXX11
Definition: Sema.h:7538
@ VAK_MSVCUndefined
Definition: Sema.h:7540
@ VAK_Undefined
Definition: Sema.h:7539
SemaOpenCL & OpenCL()
Definition: Sema.h:1122
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:13565
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:16676
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:7916
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:20128
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:7778
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:7581
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition: Sema.h:7625
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition: Sema.h:7591
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition: Sema.h:7649
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition: Sema.h:7654
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition: Sema.h:7641
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:7620
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:7599
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition: Sema.h:7658
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:7583
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition: Sema.h:7610
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:7662
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition: Sema.h:7595
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition: Sema.h:7604
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:7616
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition: Sema.h:7637
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition: Sema.h:7631
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition: Sema.h:7587
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition: Sema.h:7645
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:8467
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition: Sema.h:7400
@ ACK_Arithmetic
An arithmetic operation.
Definition: Sema.h:7402
@ ACK_CompAssign
A compound assignment expression.
Definition: Sema.h:7410
@ ACK_BitwiseOp
A bitwise operation.
Definition: Sema.h:7404
@ ACK_Conditional
A conditional (?:) operator.
Definition: Sema.h:7408
@ ACK_Comparison
A comparison.
Definition: Sema.h:7406
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20026
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
Definition: SemaExpr.cpp:2896
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4109
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16761
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition: Sema.h:6290
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20982
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17385
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:13512
SourceManager & getSourceManager() const
Definition: Sema.h:531
TryCaptureKind
Definition: Sema.h:6594
@ TryCapture_Implicit
Definition: Sema.h:6595
@ TryCapture_ExplicitByRef
Definition: Sema.h:6597
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
Definition: SemaExpr.cpp:6711
bool CheckVecStepExpr(Expr *E)
Definition: SemaExpr.cpp:4390
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?: operation.
Definition: SemaExpr.cpp:8782
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:12749
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide)
Definition: SemaExpr.cpp:10592
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
Definition: SemaExpr.cpp:19642
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13729
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:3655
@ NTCUK_Copy
Definition: Sema.h:3656
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
std::vector< std::pair< QualType, unsigned > > ExcessPrecisionNotSatisfied
Definition: Sema.h:7931
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20263
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5488
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7564
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:7601
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition: Sema.cpp:2192
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:6288
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:8302
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
ExprResult ActOnStringLiteral(ArrayRef< Token > StringToks, Scope *UDLScope=nullptr)
ActOnStringLiteral - The specified tokens were lexed as pasted string fragments (e....
Definition: SemaExpr.cpp:2048
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:14967
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:15282
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:7703
@ CTK_ErrorRecovery
Definition: Sema.h:9385
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2346
bool isConstantEvaluatedContext() const
Definition: Sema.h:2152
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:12561
ASTConsumer & Consumer
Definition: Sema.h:911
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:4228
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:6485
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:946
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:13548
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5121
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3534
ExprResult ActOnEmbedExpr(SourceLocation EmbedKeywordLoc, StringLiteral *BinaryData)
Definition: SemaExpr.cpp:16802
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
Definition: SemaExpr.cpp:12694
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:8409
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition: Sema.h:6232
@ 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:6704
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
Definition: SemaExpr.cpp:4617
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5704
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:20270
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
Definition: SemaExpr.cpp:4227
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16506
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
Definition: SemaType.cpp:5817
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9120
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:873
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:20912
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:19274
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:7738
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:7768
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr)
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:17915
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:19266
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7918
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:7650
SourceManager & SourceMgr
Definition: Sema.h:913
@ TemplateNameIsRequired
Definition: Sema.h:11092
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
Definition: SemaExpr.cpp:4704
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
Definition: SemaExpr.cpp:7811
bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const
Determine whether FD is an aligned allocation or deallocation function that is unavailable.
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
Definition: SemaExpr.cpp:2393
DiagnosticsEngine & Diags
Definition: Sema.h:912
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:527
FPOptions CurFPFeatures
Definition: Sema.h:906
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:7587
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9771
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
ExprResult ActOnIntegerConstant(SourceLocation Loc, int64_t Val)
Definition: SemaExpr.cpp:3598
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5582
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
Definition: SemaExpr.cpp:20313
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:13105
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:6067
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:15865
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
Definition: SemaExpr.cpp:997
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
Definition: SemaExpr.cpp:6075
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12810
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:8885
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:13107
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:16312
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:20048
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:16830
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:18096
ExprResult ActOnStmtExprResult(ExprResult E)
Definition: SemaExpr.cpp:15909
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4757
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:5954
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:20369
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1963
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:21179
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15356
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3672
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
Definition: SemaExpr.cpp:2969
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7255
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:16164
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
Definition: SemaExpr.cpp:4830
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:14779
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9160
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:6438
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:4687
QualType PreferredConditionType(ConditionKind K) const
Definition: Sema.h:7498
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:9044
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition: Sema.h:9050
@ LOLR_Error
The lookup resulted in an error.
Definition: Sema.h:9042
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition: Sema.h:9047
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition: Sema.h:9058
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition: Sema.h:9054
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:16193
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:10631
@ 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:13544
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:2751
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:15817
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:13359
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:11073
static ConditionResult ConditionError()
Definition: Sema.h:7339
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ActOnConvertVectorExpr - create a new convert-vector expression from the provided arguments.
Definition: SemaExpr.cpp:6725
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:20916
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:5814
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:16107
SemaPseudoObject & PseudoObject()
Definition: Sema.h:1137
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2337
FullExprArg MakeFullExpr(Expr *Arg)
Definition: Sema.h:7295
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:17923
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7187
bool isCheckingDefaultArgumentOrInitializer() const
Definition: Sema.h:7794
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:5333
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:8269
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:5007
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:1262
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:320
virtual size_t getMaxBitIntWidth() const
Definition: TargetInfo.h:682
virtual bool useFP16ConversionIntrinsics() const
Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used to convert to and from __fp...
Definition: TargetInfo.h:1002
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:286
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:478
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:519
IntType getSizeType() const
Definition: TargetInfo.h:377
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:529
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1583
virtual bool supportsExtendIntArgs() const
Whether the option -fextend-arguments={32,64} is supported on the target.
Definition: TargetInfo.h:1676
virtual BuiltinVaListKind getBuiltinVaListKind() const =0
Returns the kind of __builtin_va_list type that should be used with this target.
bool hasBuiltinMSVaList() const
Returns whether or not type __builtin_ms_va_list type is available on this target.
Definition: TargetInfo.h:1042
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1333
unsigned getIntMaxTWidth() const
Return the size of intmax_t and uintmax_t for this target, in bits.
Definition: TargetInfo.h:879
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:524
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1493
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
Represents a template argument.
Definition: TemplateBase.h:61
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h: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:4958
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:4408
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:882
bool hasInit() const
Definition: Decl.cpp:2387
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2246
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1522
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1177
bool mightBeUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value might be usable in a constant expression, according to the re...
Definition: Decl.cpp:2458
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition: Decl.cpp:2883
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1495
const Expr * getInit() const
Definition: Decl.h:1319
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1168
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1135
@ TLS_None
Not a TLS variable.
Definition: Decl.h:902
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1246
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2364
bool isUsableInConstantExpressions(const ASTContext &C) const
Determine whether this variable's value can be used in a constant expression, according to the releva...
Definition: Decl.cpp:2500
SourceLocation getPointOfInstantiation() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2776
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1213
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2755
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2874
Declaration of a variable template.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h: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
@ 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:5466
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
Definition: SemaExpr.cpp:5463
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
Definition: SemaExpr.cpp:5448
ExprResult TransformBlockExpr(BlockExpr *E)
Definition: SemaExpr.cpp:5458
ExprResult TransformLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5457
bool VisitSourceLocExpr(SourceLocExpr *E) override
Definition: SemaExpr.cpp:5422
bool VisitCXXConstructExpr(CXXConstructExpr *E) override
Definition: SemaExpr.cpp:5412
bool VisitCallExpr(CallExpr *E) override
Definition: SemaExpr.cpp:5406
const ASTContext & Context
Definition: SemaExpr.cpp:5399
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) override
Definition: SemaExpr.cpp:5441
bool VisitLambdaExpr(LambdaExpr *E) override
Definition: SemaExpr.cpp:5433
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) override
Definition: SemaExpr.cpp:5437
ImmediateCallVisitor(const ASTContext &Ctx)
Definition: SemaExpr.cpp:5400
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:12687
Data structure used to record current or nested expression evaluation contexts.
Definition: Sema.h:6294
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition: Sema.h:6328
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition: Sema.h:6374
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition: Sema.h:6333
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:6341
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition: Sema.h:6337
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition: Sema.h:6347
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:6313
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:6351
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition: Sema.h:6299
unsigned NumTypos
The number of typos encountered during this expression evaluation context (i.e.
Definition: Sema.h:6307
ExpressionEvaluationContext Context
The expression evaluation context.
Definition: Sema.h:6296
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition: Sema.h:6303
Abstract class used to diagnose incomplete types.
Definition: Sema.h:7859
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
uint64_t Width
Definition: ASTContext.h:159
Describes an entity that is being assigned.