clang 19.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 "TreeTransform.h"
14#include "UsedDeclVisitor.h"
17#include "clang/AST/ASTLambda.h"
20#include "clang/AST/DeclObjC.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/TypeLoc.h"
42#include "clang/Sema/DeclSpec.h"
47#include "clang/Sema/Lookup.h"
48#include "clang/Sema/Overload.h"
50#include "clang/Sema/Scope.h"
52#include "clang/Sema/SemaCUDA.h"
56#include "clang/Sema/Template.h"
57#include "llvm/ADT/STLExtras.h"
58#include "llvm/ADT/STLForwardCompat.h"
59#include "llvm/ADT/StringExtras.h"
60#include "llvm/Support/Casting.h"
61#include "llvm/Support/ConvertUTF.h"
62#include "llvm/Support/SaveAndRestore.h"
63#include "llvm/Support/TypeSize.h"
64#include <optional>
65
66using namespace clang;
67using namespace sema;
68
69/// Determine whether the use of this declaration is valid, without
70/// emitting diagnostics.
71bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
72 // See if this is an auto-typed variable whose initializer we are parsing.
73 if (ParsingInitForAutoVars.count(D))
74 return false;
75
76 // See if this is a deleted function.
77 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
78 if (FD->isDeleted())
79 return false;
80
81 // If the function has a deduced return type, and we can't deduce it,
82 // then we can't use it either.
83 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
84 DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
85 return false;
86
87 // See if this is an aligned allocation/deallocation function that is
88 // unavailable.
89 if (TreatUnavailableAsInvalid &&
91 return false;
92 }
93
94 // See if this function is unavailable.
95 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
96 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
97 return false;
98
99 if (isa<UnresolvedUsingIfExistsDecl>(D))
100 return false;
101
102 return true;
103}
104
106 // Warn if this is used but marked unused.
107 if (const auto *A = D->getAttr<UnusedAttr>()) {
108 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
109 // should diagnose them.
110 if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
111 A->getSemanticSpelling() != UnusedAttr::C23_maybe_unused) {
112 const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
113 if (DC && !DC->hasAttr<UnusedAttr>())
114 S.Diag(Loc, diag::warn_used_but_marked_unused) << D;
115 }
116 }
117}
118
119/// Emit a note explaining that this function is deleted.
121 assert(Decl && Decl->isDeleted());
122
123 if (Decl->isDefaulted()) {
124 // If the method was explicitly defaulted, point at that declaration.
125 if (!Decl->isImplicit())
126 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
127
128 // Try to diagnose why this special member function was implicitly
129 // deleted. This might fail, if that reason no longer applies.
131 return;
132 }
133
134 auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
135 if (Ctor && Ctor->isInheritingConstructor())
137
138 Diag(Decl->getLocation(), diag::note_availability_specified_here)
139 << Decl << 1;
140}
141
142/// Determine whether a FunctionDecl was ever declared with an
143/// explicit storage class.
145 for (auto *I : D->redecls()) {
146 if (I->getStorageClass() != SC_None)
147 return true;
148 }
149 return false;
150}
151
152/// Check whether we're in an extern inline function and referring to a
153/// variable or function with internal linkage (C11 6.7.4p3).
154///
155/// This is only a warning because we used to silently accept this code, but
156/// in many cases it will not behave correctly. This is not enabled in C++ mode
157/// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
158/// and so while there may still be user mistakes, most of the time we can't
159/// prove that there are errors.
161 const NamedDecl *D,
162 SourceLocation Loc) {
163 // This is disabled under C++; there are too many ways for this to fire in
164 // contexts where the warning is a false positive, or where it is technically
165 // correct but benign.
166 if (S.getLangOpts().CPlusPlus)
167 return;
168
169 // Check if this is an inlined function or method.
170 FunctionDecl *Current = S.getCurFunctionDecl();
171 if (!Current)
172 return;
173 if (!Current->isInlined())
174 return;
175 if (!Current->isExternallyVisible())
176 return;
177
178 // Check if the decl has internal linkage.
180 return;
181
182 // Downgrade from ExtWarn to Extension if
183 // (1) the supposedly external inline function is in the main file,
184 // and probably won't be included anywhere else.
185 // (2) the thing we're referencing is a pure function.
186 // (3) the thing we're referencing is another inline function.
187 // This last can give us false negatives, but it's better than warning on
188 // wrappers for simple C library functions.
189 const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
190 bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
191 if (!DowngradeWarning && UsedFn)
192 DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
193
194 S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
195 : diag::ext_internal_in_extern_inline)
196 << /*IsVar=*/!UsedFn << D;
197
199
200 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
201 << D;
202}
203
205 const FunctionDecl *First = Cur->getFirstDecl();
206
207 // Suggest "static" on the function, if possible.
209 SourceLocation DeclBegin = First->getSourceRange().getBegin();
210 Diag(DeclBegin, diag::note_convert_inline_to_static)
211 << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
212 }
213}
214
215/// Determine whether the use of this declaration is valid, and
216/// emit any corresponding diagnostics.
217///
218/// This routine diagnoses various problems with referencing
219/// declarations that can occur when using a declaration. For example,
220/// it might warn if a deprecated or unavailable declaration is being
221/// used, or produce an error (and return true) if a C++0x deleted
222/// function is being used.
223///
224/// \returns true if there was an error (this declaration cannot be
225/// referenced), false otherwise.
226///
228 const ObjCInterfaceDecl *UnknownObjCClass,
229 bool ObjCPropertyAccess,
230 bool AvoidPartialAvailabilityChecks,
231 ObjCInterfaceDecl *ClassReceiver,
232 bool SkipTrailingRequiresClause) {
233 SourceLocation Loc = Locs.front();
234 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
235 // If there were any diagnostics suppressed by template argument deduction,
236 // emit them now.
237 auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
238 if (Pos != SuppressedDiagnostics.end()) {
239 for (const PartialDiagnosticAt &Suppressed : Pos->second)
240 Diag(Suppressed.first, Suppressed.second);
241
242 // Clear out the list of suppressed diagnostics, so that we don't emit
243 // them again for this specialization. However, we don't obsolete this
244 // entry from the table, because we want to avoid ever emitting these
245 // diagnostics again.
246 Pos->second.clear();
247 }
248
249 // C++ [basic.start.main]p3:
250 // The function 'main' shall not be used within a program.
251 if (cast<FunctionDecl>(D)->isMain())
252 Diag(Loc, diag::ext_main_used);
253
254 diagnoseUnavailableAlignedAllocation(*cast<FunctionDecl>(D), Loc);
255 }
256
257 // See if this is an auto-typed variable whose initializer we are parsing.
258 if (ParsingInitForAutoVars.count(D)) {
259 if (isa<BindingDecl>(D)) {
260 Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
261 << D->getDeclName();
262 } else {
263 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
264 << D->getDeclName() << cast<VarDecl>(D)->getType();
265 }
266 return true;
267 }
268
269 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
270 // See if this is a deleted function.
271 if (FD->isDeleted()) {
272 auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
273 if (Ctor && Ctor->isInheritingConstructor())
274 Diag(Loc, diag::err_deleted_inherited_ctor_use)
275 << Ctor->getParent()
276 << Ctor->getInheritedConstructor().getConstructor()->getParent();
277 else {
278 StringLiteral *Msg = FD->getDeletedMessage();
279 Diag(Loc, diag::err_deleted_function_use)
280 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef());
281 }
283 return true;
284 }
285
286 // [expr.prim.id]p4
287 // A program that refers explicitly or implicitly to a function with a
288 // trailing requires-clause whose constraint-expression is not satisfied,
289 // other than to declare it, is ill-formed. [...]
290 //
291 // See if this is a function with constraints that need to be satisfied.
292 // Check this before deducing the return type, as it might instantiate the
293 // definition.
294 if (!SkipTrailingRequiresClause && FD->getTrailingRequiresClause()) {
295 ConstraintSatisfaction Satisfaction;
296 if (CheckFunctionConstraints(FD, Satisfaction, Loc,
297 /*ForOverloadResolution*/ true))
298 // A diagnostic will have already been generated (non-constant
299 // constraint expression, for example)
300 return true;
301 if (!Satisfaction.IsSatisfied) {
302 Diag(Loc,
303 diag::err_reference_to_function_with_unsatisfied_constraints)
304 << D;
305 DiagnoseUnsatisfiedConstraint(Satisfaction);
306 return true;
307 }
308 }
309
310 // If the function has a deduced return type, and we can't deduce it,
311 // then we can't use it either.
312 if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
313 DeduceReturnType(FD, Loc))
314 return true;
315
316 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc, FD))
317 return true;
318
319 }
320
321 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) {
322 // Lambdas are only default-constructible or assignable in C++2a onwards.
323 if (MD->getParent()->isLambda() &&
324 ((isa<CXXConstructorDecl>(MD) &&
325 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) ||
326 MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator())) {
327 Diag(Loc, diag::warn_cxx17_compat_lambda_def_ctor_assign)
328 << !isa<CXXConstructorDecl>(MD);
329 }
330 }
331
332 auto getReferencedObjCProp = [](const NamedDecl *D) ->
333 const ObjCPropertyDecl * {
334 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
335 return MD->findPropertyDecl();
336 return nullptr;
337 };
338 if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
339 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
340 return true;
341 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
342 return true;
343 }
344
345 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
346 // Only the variables omp_in and omp_out are allowed in the combiner.
347 // Only the variables omp_priv and omp_orig are allowed in the
348 // initializer-clause.
349 auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
350 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
351 isa<VarDecl>(D)) {
352 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
354 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
355 return true;
356 }
357
358 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
359 // List-items in map clauses on this construct may only refer to the declared
360 // variable var and entities that could be referenced by a procedure defined
361 // at the same location.
362 // [OpenMP 5.2] Also allow iterator declared variables.
363 if (LangOpts.OpenMP && isa<VarDecl>(D) &&
364 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(cast<VarDecl>(D))) {
365 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
367 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
368 return true;
369 }
370
371 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(D)) {
372 Diag(Loc, diag::err_use_of_empty_using_if_exists);
373 Diag(EmptyD->getLocation(), diag::note_empty_using_if_exists_here);
374 return true;
375 }
376
377 DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
378 AvoidPartialAvailabilityChecks, ClassReceiver);
379
380 DiagnoseUnusedOfDecl(*this, D, Loc);
381
383
384 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
385 if (getLangOpts().getFPEvalMethod() !=
388 PP.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
389 Diag(D->getLocation(),
390 diag::err_type_available_only_in_default_eval_method)
391 << D->getName();
392 }
393
394 if (auto *VD = dyn_cast<ValueDecl>(D))
395 checkTypeSupport(VD->getType(), Loc, VD);
396
397 if (LangOpts.SYCLIsDevice ||
398 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
400 if (const auto *VD = dyn_cast<VarDecl>(D))
401 if (VD->getTLSKind() != VarDecl::TLS_None)
402 targetDiag(*Locs.begin(), diag::err_thread_unsupported);
403 }
404
405 if (isa<ParmVarDecl>(D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
407 // C++ [expr.prim.req.nested] p3
408 // A local parameter shall only appear as an unevaluated operand
409 // (Clause 8) within the constraint-expression.
410 Diag(Loc, diag::err_requires_expr_parameter_referenced_in_evaluated_context)
411 << D;
412 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
413 return true;
414 }
415
416 return false;
417}
418
419/// DiagnoseSentinelCalls - This routine checks whether a call or
420/// message-send is to a declaration with the sentinel attribute, and
421/// if so, it checks that the requirements of the sentinel are
422/// satisfied.
424 ArrayRef<Expr *> Args) {
425 const SentinelAttr *Attr = D->getAttr<SentinelAttr>();
426 if (!Attr)
427 return;
428
429 // The number of formal parameters of the declaration.
430 unsigned NumFormalParams;
431
432 // The kind of declaration. This is also an index into a %select in
433 // the diagnostic.
434 enum { CK_Function, CK_Method, CK_Block } CalleeKind;
435
436 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
437 NumFormalParams = MD->param_size();
438 CalleeKind = CK_Method;
439 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
440 NumFormalParams = FD->param_size();
441 CalleeKind = CK_Function;
442 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
443 QualType Ty = VD->getType();
444 const FunctionType *Fn = nullptr;
445 if (const auto *PtrTy = Ty->getAs<PointerType>()) {
446 Fn = PtrTy->getPointeeType()->getAs<FunctionType>();
447 if (!Fn)
448 return;
449 CalleeKind = CK_Function;
450 } else if (const auto *PtrTy = Ty->getAs<BlockPointerType>()) {
451 Fn = PtrTy->getPointeeType()->castAs<FunctionType>();
452 CalleeKind = CK_Block;
453 } else {
454 return;
455 }
456
457 if (const auto *proto = dyn_cast<FunctionProtoType>(Fn))
458 NumFormalParams = proto->getNumParams();
459 else
460 NumFormalParams = 0;
461 } else {
462 return;
463 }
464
465 // "NullPos" is the number of formal parameters at the end which
466 // effectively count as part of the variadic arguments. This is
467 // useful if you would prefer to not have *any* formal parameters,
468 // but the language forces you to have at least one.
469 unsigned NullPos = Attr->getNullPos();
470 assert((NullPos == 0 || NullPos == 1) && "invalid null position on sentinel");
471 NumFormalParams = (NullPos > NumFormalParams ? 0 : NumFormalParams - NullPos);
472
473 // The number of arguments which should follow the sentinel.
474 unsigned NumArgsAfterSentinel = Attr->getSentinel();
475
476 // If there aren't enough arguments for all the formal parameters,
477 // the sentinel, and the args after the sentinel, complain.
478 if (Args.size() < NumFormalParams + NumArgsAfterSentinel + 1) {
479 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
480 Diag(D->getLocation(), diag::note_sentinel_here) << int(CalleeKind);
481 return;
482 }
483
484 // Otherwise, find the sentinel expression.
485 const Expr *SentinelExpr = Args[Args.size() - NumArgsAfterSentinel - 1];
486 if (!SentinelExpr)
487 return;
488 if (SentinelExpr->isValueDependent())
489 return;
490 if (Context.isSentinelNullExpr(SentinelExpr))
491 return;
492
493 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
494 // or 'NULL' if those are actually defined in the context. Only use
495 // 'nil' for ObjC methods, where it's much more likely that the
496 // variadic arguments form a list of object pointers.
497 SourceLocation MissingNilLoc = getLocForEndOfToken(SentinelExpr->getEndLoc());
498 std::string NullValue;
499 if (CalleeKind == CK_Method && PP.isMacroDefined("nil"))
500 NullValue = "nil";
501 else if (getLangOpts().CPlusPlus11)
502 NullValue = "nullptr";
503 else if (PP.isMacroDefined("NULL"))
504 NullValue = "NULL";
505 else
506 NullValue = "(void*) 0";
507
508 if (MissingNilLoc.isInvalid())
509 Diag(Loc, diag::warn_missing_sentinel) << int(CalleeKind);
510 else
511 Diag(MissingNilLoc, diag::warn_missing_sentinel)
512 << int(CalleeKind)
513 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
514 Diag(D->getLocation(), diag::note_sentinel_here)
515 << int(CalleeKind) << Attr->getRange();
516}
517
519 return E ? E->getSourceRange() : SourceRange();
520}
521
522//===----------------------------------------------------------------------===//
523// Standard Promotions and Conversions
524//===----------------------------------------------------------------------===//
525
526/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
528 // Handle any placeholder expressions which made it here.
529 if (E->hasPlaceholderType()) {
531 if (result.isInvalid()) return ExprError();
532 E = result.get();
533 }
534
535 QualType Ty = E->getType();
536 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
537
538 if (Ty->isFunctionType()) {
539 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
540 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
542 return ExprError();
543
545 CK_FunctionToPointerDecay).get();
546 } else if (Ty->isArrayType()) {
547 // In C90 mode, arrays only promote to pointers if the array expression is
548 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
549 // type 'array of type' is converted to an expression that has type 'pointer
550 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
551 // that has type 'array of type' ...". The relevant change is "an lvalue"
552 // (C90) to "an expression" (C99).
553 //
554 // C++ 4.2p1:
555 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
556 // T" can be converted to an rvalue of type "pointer to T".
557 //
558 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue()) {
560 CK_ArrayToPointerDecay);
561 if (Res.isInvalid())
562 return ExprError();
563 E = Res.get();
564 }
565 }
566 return E;
567}
568
570 // Check to see if we are dereferencing a null pointer. If so,
571 // and if not volatile-qualified, this is undefined behavior that the
572 // optimizer will delete, so warn about it. People sometimes try to use this
573 // to get a deterministic trap and are surprised by clang's behavior. This
574 // only handles the pattern "*null", which is a very syntactic check.
575 const auto *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts());
576 if (UO && UO->getOpcode() == UO_Deref &&
577 UO->getSubExpr()->getType()->isPointerType()) {
578 const LangAS AS =
579 UO->getSubExpr()->getType()->getPointeeType().getAddressSpace();
580 if ((!isTargetAddressSpace(AS) ||
581 (isTargetAddressSpace(AS) && toTargetAddressSpace(AS) == 0)) &&
582 UO->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
584 !UO->getType().isVolatileQualified()) {
585 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
586 S.PDiag(diag::warn_indirection_through_null)
587 << UO->getSubExpr()->getSourceRange());
588 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
589 S.PDiag(diag::note_indirection_through_null));
590 }
591 }
592}
593
594static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
595 SourceLocation AssignLoc,
596 const Expr* RHS) {
597 const ObjCIvarDecl *IV = OIRE->getDecl();
598 if (!IV)
599 return;
600
601 DeclarationName MemberName = IV->getDeclName();
603 if (!Member || !Member->isStr("isa"))
604 return;
605
606 const Expr *Base = OIRE->getBase();
607 QualType BaseType = Base->getType();
608 if (OIRE->isArrow())
609 BaseType = BaseType->getPointeeType();
610 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
611 if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
612 ObjCInterfaceDecl *ClassDeclared = nullptr;
613 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
614 if (!ClassDeclared->getSuperClass()
615 && (*ClassDeclared->ivar_begin()) == IV) {
616 if (RHS) {
617 NamedDecl *ObjectSetClass =
619 &S.Context.Idents.get("object_setClass"),
621 if (ObjectSetClass) {
622 SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getEndLoc());
623 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
625 "object_setClass(")
627 SourceRange(OIRE->getOpLoc(), AssignLoc), ",")
628 << FixItHint::CreateInsertion(RHSLocEnd, ")");
629 }
630 else
631 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
632 } else {
633 NamedDecl *ObjectGetClass =
635 &S.Context.Idents.get("object_getClass"),
637 if (ObjectGetClass)
638 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
640 "object_getClass(")
642 SourceRange(OIRE->getOpLoc(), OIRE->getEndLoc()), ")");
643 else
644 S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
645 }
646 S.Diag(IV->getLocation(), diag::note_ivar_decl);
647 }
648 }
649}
650
652 // Handle any placeholder expressions which made it here.
653 if (E->hasPlaceholderType()) {
655 if (result.isInvalid()) return ExprError();
656 E = result.get();
657 }
658
659 // C++ [conv.lval]p1:
660 // A glvalue of a non-function, non-array type T can be
661 // converted to a prvalue.
662 if (!E->isGLValue()) return E;
663
664 QualType T = E->getType();
665 assert(!T.isNull() && "r-value conversion on typeless expression?");
666
667 // lvalue-to-rvalue conversion cannot be applied to types that decay to
668 // pointers (i.e. function or array types).
670 return E;
671
672 // We don't want to throw lvalue-to-rvalue casts on top of
673 // expressions of certain types in C++.
674 if (getLangOpts().CPlusPlus &&
675 (E->getType() == Context.OverloadTy ||
676 T->isDependentType() ||
677 T->isRecordType()))
678 return E;
679
680 // The C standard is actually really unclear on this point, and
681 // DR106 tells us what the result should be but not why. It's
682 // generally best to say that void types just doesn't undergo
683 // lvalue-to-rvalue at all. Note that expressions of unqualified
684 // 'void' type are never l-values, but qualified void can be.
685 if (T->isVoidType())
686 return E;
687
688 // OpenCL usually rejects direct accesses to values of 'half' type.
689 if (getLangOpts().OpenCL &&
690 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
691 T->isHalfType()) {
692 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
693 << 0 << T;
694 return ExprError();
695 }
696
698 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
699 NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
700 &Context.Idents.get("object_getClass"),
702 if (ObjectGetClass)
703 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
704 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
706 SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
707 else
708 Diag(E->getExprLoc(), diag::warn_objc_isa_use);
709 }
710 else if (const ObjCIvarRefExpr *OIRE =
711 dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
712 DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
713
714 // C++ [conv.lval]p1:
715 // [...] If T is a non-class type, the type of the prvalue is the
716 // cv-unqualified version of T. Otherwise, the type of the
717 // rvalue is T.
718 //
719 // C99 6.3.2.1p2:
720 // If the lvalue has qualified type, the value has the unqualified
721 // version of the type of the lvalue; otherwise, the value has the
722 // type of the lvalue.
723 if (T.hasQualifiers())
724 T = T.getUnqualifiedType();
725
726 // Under the MS ABI, lock down the inheritance model now.
727 if (T->isMemberPointerType() &&
729 (void)isCompleteType(E->getExprLoc(), T);
730
732 if (Res.isInvalid())
733 return Res;
734 E = Res.get();
735
736 // Loading a __weak object implicitly retains the value, so we need a cleanup to
737 // balance that.
740
743
744 // C++ [conv.lval]p3:
745 // If T is cv std::nullptr_t, the result is a null pointer constant.
746 CastKind CK = T->isNullPtrType() ? CK_NullToPointer : CK_LValueToRValue;
747 Res = ImplicitCastExpr::Create(Context, T, CK, E, nullptr, VK_PRValue,
749
750 // C11 6.3.2.1p2:
751 // ... if the lvalue has atomic type, the value has the non-atomic version
752 // of the type of the lvalue ...
753 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
754 T = Atomic->getValueType().getUnqualifiedType();
755 Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
756 nullptr, VK_PRValue, FPOptionsOverride());
757 }
758
759 return Res;
760}
761
764 if (Res.isInvalid())
765 return ExprError();
766 Res = DefaultLvalueConversion(Res.get());
767 if (Res.isInvalid())
768 return ExprError();
769 return Res;
770}
771
772/// CallExprUnaryConversions - a special case of an unary conversion
773/// performed on a function designator of a call expression.
775 QualType Ty = E->getType();
776 ExprResult Res = E;
777 // Only do implicit cast for a function type, but not for a pointer
778 // to function type.
779 if (Ty->isFunctionType()) {
781 CK_FunctionToPointerDecay);
782 if (Res.isInvalid())
783 return ExprError();
784 }
785 Res = DefaultLvalueConversion(Res.get());
786 if (Res.isInvalid())
787 return ExprError();
788 return Res.get();
789}
790
791/// UsualUnaryConversions - Performs various conversions that are common to most
792/// operators (C99 6.3). The conversions of array and function types are
793/// sometimes suppressed. For example, the array->pointer conversion doesn't
794/// apply if the array is an argument to the sizeof or address (&) operators.
795/// In these instances, this routine should *not* be called.
797 // First, convert to an r-value.
799 if (Res.isInvalid())
800 return ExprError();
801 E = Res.get();
802
803 QualType Ty = E->getType();
804 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
805
806 LangOptions::FPEvalMethodKind EvalMethod = CurFPFeatures.getFPEvalMethod();
807 if (EvalMethod != LangOptions::FEM_Source && Ty->isFloatingType() &&
808 (getLangOpts().getFPEvalMethod() !=
811 switch (EvalMethod) {
812 default:
813 llvm_unreachable("Unrecognized float evaluation method");
814 break;
816 llvm_unreachable("Float evaluation method should be set by now");
817 break;
820 // Widen the expression to double.
821 return Ty->isComplexType()
824 CK_FloatingComplexCast)
825 : ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast);
826 break;
829 // Widen the expression to long double.
830 return Ty->isComplexType()
833 CK_FloatingComplexCast)
835 CK_FloatingCast);
836 break;
837 }
838 }
839
840 // Half FP have to be promoted to float unless it is natively supported
841 if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
842 return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
843
844 // Try to perform integral promotions if the object has a theoretically
845 // promotable type.
847 // C99 6.3.1.1p2:
848 //
849 // The following may be used in an expression wherever an int or
850 // unsigned int may be used:
851 // - an object or expression with an integer type whose integer
852 // conversion rank is less than or equal to the rank of int
853 // and unsigned int.
854 // - A bit-field of type _Bool, int, signed int, or unsigned int.
855 //
856 // If an int can represent all values of the original type, the
857 // value is converted to an int; otherwise, it is converted to an
858 // unsigned int. These are called the integer promotions. All
859 // other types are unchanged by the integer promotions.
860
862 if (!PTy.isNull()) {
863 E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
864 return E;
865 }
868 E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
869 return E;
870 }
871 }
872 return E;
873}
874
875/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
876/// do not have a prototype. Arguments that have type float or __fp16
877/// are promoted to double. All other argument types are converted by
878/// UsualUnaryConversions().
880 QualType Ty = E->getType();
881 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
882
884 if (Res.isInvalid())
885 return ExprError();
886 E = Res.get();
887
888 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
889 // promote to double.
890 // Note that default argument promotion applies only to float (and
891 // half/fp16); it does not apply to _Float16.
892 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
893 if (BTy && (BTy->getKind() == BuiltinType::Half ||
894 BTy->getKind() == BuiltinType::Float)) {
895 if (getLangOpts().OpenCL &&
896 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
897 if (BTy->getKind() == BuiltinType::Half) {
898 E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
899 }
900 } else {
901 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
902 }
903 }
904 if (BTy &&
905 getLangOpts().getExtendIntArgs() ==
910 E = (Ty->isUnsignedIntegerType())
911 ? ImpCastExprToType(E, Context.UnsignedLongLongTy, CK_IntegralCast)
912 .get()
913 : ImpCastExprToType(E, Context.LongLongTy, CK_IntegralCast).get();
915 "Unexpected typesize for LongLongTy");
916 }
917
918 // C++ performs lvalue-to-rvalue conversion as a default argument
919 // promotion, even on class types, but note:
920 // C++11 [conv.lval]p2:
921 // When an lvalue-to-rvalue conversion occurs in an unevaluated
922 // operand or a subexpression thereof the value contained in the
923 // referenced object is not accessed. Otherwise, if the glvalue
924 // has a class type, the conversion copy-initializes a temporary
925 // of type T from the glvalue and the result of the conversion
926 // is a prvalue for the temporary.
927 // FIXME: add some way to gate this entire thing for correctness in
928 // potentially potentially evaluated contexts.
932 E->getExprLoc(), E);
933 if (Temp.isInvalid())
934 return ExprError();
935 E = Temp.get();
936 }
937
938 return E;
939}
940
941/// Determine the degree of POD-ness for an expression.
942/// Incomplete types are considered POD, since this check can be performed
943/// when we're in an unevaluated context.
945 if (Ty->isIncompleteType()) {
946 // C++11 [expr.call]p7:
947 // After these conversions, if the argument does not have arithmetic,
948 // enumeration, pointer, pointer to member, or class type, the program
949 // is ill-formed.
950 //
951 // Since we've already performed array-to-pointer and function-to-pointer
952 // decay, the only such type in C++ is cv void. This also handles
953 // initializer lists as variadic arguments.
954 if (Ty->isVoidType())
955 return VAK_Invalid;
956
957 if (Ty->isObjCObjectType())
958 return VAK_Invalid;
959 return VAK_Valid;
960 }
961
963 return VAK_Invalid;
964
965 if (Context.getTargetInfo().getTriple().isWasm() &&
967 return VAK_Invalid;
968 }
969
970 if (Ty.isCXX98PODType(Context))
971 return VAK_Valid;
972
973 // C++11 [expr.call]p7:
974 // Passing a potentially-evaluated argument of class type (Clause 9)
975 // having a non-trivial copy constructor, a non-trivial move constructor,
976 // or a non-trivial destructor, with no corresponding parameter,
977 // is conditionally-supported with implementation-defined semantics.
980 if (!Record->hasNonTrivialCopyConstructor() &&
981 !Record->hasNonTrivialMoveConstructor() &&
982 !Record->hasNonTrivialDestructor())
983 return VAK_ValidInCXX11;
984
985 if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
986 return VAK_Valid;
987
988 if (Ty->isObjCObjectType())
989 return VAK_Invalid;
990
991 if (getLangOpts().MSVCCompat)
992 return VAK_MSVCUndefined;
993
994 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
995 // permitted to reject them. We should consider doing so.
996 return VAK_Undefined;
997}
998
1000 // Don't allow one to pass an Objective-C interface to a vararg.
1001 const QualType &Ty = E->getType();
1002 VarArgKind VAK = isValidVarArgType(Ty);
1003
1004 // Complain about passing non-POD types through varargs.
1005 switch (VAK) {
1006 case VAK_ValidInCXX11:
1008 E->getBeginLoc(), nullptr,
1009 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg) << Ty << CT);
1010 [[fallthrough]];
1011 case VAK_Valid:
1012 if (Ty->isRecordType()) {
1013 // This is unlikely to be what the user intended. If the class has a
1014 // 'c_str' member function, the user probably meant to call that.
1015 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1016 PDiag(diag::warn_pass_class_arg_to_vararg)
1017 << Ty << CT << hasCStrMethod(E) << ".c_str()");
1018 }
1019 break;
1020
1021 case VAK_Undefined:
1022 case VAK_MSVCUndefined:
1023 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1024 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
1025 << getLangOpts().CPlusPlus11 << Ty << CT);
1026 break;
1027
1028 case VAK_Invalid:
1030 Diag(E->getBeginLoc(),
1031 diag::err_cannot_pass_non_trivial_c_struct_to_vararg)
1032 << Ty << CT;
1033 else if (Ty->isObjCObjectType())
1034 DiagRuntimeBehavior(E->getBeginLoc(), nullptr,
1035 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
1036 << Ty << CT);
1037 else
1038 Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg)
1039 << isa<InitListExpr>(E) << Ty << CT;
1040 break;
1041 }
1042}
1043
1044/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1045/// will create a trap if the resulting type is not a POD type.
1047 FunctionDecl *FDecl) {
1048 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
1049 // Strip the unbridged-cast placeholder expression off, if applicable.
1050 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
1051 (CT == VariadicMethod ||
1052 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
1053 E = stripARCUnbridgedCast(E);
1054
1055 // Otherwise, do normal placeholder checking.
1056 } else {
1057 ExprResult ExprRes = CheckPlaceholderExpr(E);
1058 if (ExprRes.isInvalid())
1059 return ExprError();
1060 E = ExprRes.get();
1061 }
1062 }
1063
1065 if (ExprRes.isInvalid())
1066 return ExprError();
1067
1068 // Copy blocks to the heap.
1069 if (ExprRes.get()->getType()->isBlockPointerType())
1070 maybeExtendBlockObject(ExprRes);
1071
1072 E = ExprRes.get();
1073
1074 // Diagnostics regarding non-POD argument types are
1075 // emitted along with format string checking in Sema::CheckFunctionCall().
1077 // Turn this into a trap.
1078 CXXScopeSpec SS;
1079 SourceLocation TemplateKWLoc;
1080 UnqualifiedId Name;
1081 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
1082 E->getBeginLoc());
1083 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
1084 /*HasTrailingLParen=*/true,
1085 /*IsAddressOfOperand=*/false);
1086 if (TrapFn.isInvalid())
1087 return ExprError();
1088
1090 std::nullopt, E->getEndLoc());
1091 if (Call.isInvalid())
1092 return ExprError();
1093
1094 ExprResult Comma =
1095 ActOnBinOp(TUScope, E->getBeginLoc(), tok::comma, Call.get(), E);
1096 if (Comma.isInvalid())
1097 return ExprError();
1098 return Comma.get();
1099 }
1100
1101 if (!getLangOpts().CPlusPlus &&
1103 diag::err_call_incomplete_argument))
1104 return ExprError();
1105
1106 return E;
1107}
1108
1109/// Convert complex integers to complex floats and real integers to
1110/// real floats as required for complex arithmetic. Helper function of
1111/// UsualArithmeticConversions()
1112///
1113/// \return false if the integer expression is an integer type and is
1114/// successfully converted to the (complex) float type.
1116 ExprResult &ComplexExpr,
1117 QualType IntTy,
1118 QualType ComplexTy,
1119 bool SkipCast) {
1120 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1121 if (SkipCast) return false;
1122 if (IntTy->isIntegerType()) {
1123 QualType fpTy = ComplexTy->castAs<ComplexType>()->getElementType();
1124 IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1125 } else {
1126 assert(IntTy->isComplexIntegerType());
1127 IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1128 CK_IntegralComplexToFloatingComplex);
1129 }
1130 return false;
1131}
1132
1133// This handles complex/complex, complex/float, or float/complex.
1134// When both operands are complex, the shorter operand is converted to the
1135// type of the longer, and that is the type of the result. This corresponds
1136// to what is done when combining two real floating-point operands.
1137// The fun begins when size promotion occur across type domains.
1138// From H&S 6.3.4: When one operand is complex and the other is a real
1139// floating-point type, the less precise type is converted, within it's
1140// real or complex domain, to the precision of the other type. For example,
1141// when combining a "long double" with a "double _Complex", the
1142// "double _Complex" is promoted to "long double _Complex".
1144 QualType ShorterType,
1145 QualType LongerType,
1146 bool PromotePrecision) {
1147 bool LongerIsComplex = isa<ComplexType>(LongerType.getCanonicalType());
1149 LongerIsComplex ? LongerType : S.Context.getComplexType(LongerType);
1150
1151 if (PromotePrecision) {
1152 if (isa<ComplexType>(ShorterType.getCanonicalType())) {
1153 Shorter =
1154 S.ImpCastExprToType(Shorter.get(), Result, CK_FloatingComplexCast);
1155 } else {
1156 if (LongerIsComplex)
1157 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1158 Shorter = S.ImpCastExprToType(Shorter.get(), LongerType, CK_FloatingCast);
1159 }
1160 }
1161 return Result;
1162}
1163
1164/// Handle arithmetic conversion with complex types. Helper function of
1165/// UsualArithmeticConversions()
1167 ExprResult &RHS, QualType LHSType,
1168 QualType RHSType, bool IsCompAssign) {
1169 // Handle (complex) integer types.
1170 if (!handleComplexIntegerToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1171 /*SkipCast=*/false))
1172 return LHSType;
1173 if (!handleComplexIntegerToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1174 /*SkipCast=*/IsCompAssign))
1175 return RHSType;
1176
1177 // Compute the rank of the two types, regardless of whether they are complex.
1178 int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1179 if (Order < 0)
1180 // Promote the precision of the LHS if not an assignment.
1181 return handleComplexFloatConversion(S, LHS, LHSType, RHSType,
1182 /*PromotePrecision=*/!IsCompAssign);
1183 // Promote the precision of the RHS unless it is already the same as the LHS.
1184 return handleComplexFloatConversion(S, RHS, RHSType, LHSType,
1185 /*PromotePrecision=*/Order > 0);
1186}
1187
1188/// Handle arithmetic conversion from integer to float. Helper function
1189/// of UsualArithmeticConversions()
1191 ExprResult &IntExpr,
1192 QualType FloatTy, QualType IntTy,
1193 bool ConvertFloat, bool ConvertInt) {
1194 if (IntTy->isIntegerType()) {
1195 if (ConvertInt)
1196 // Convert intExpr to the lhs floating point type.
1197 IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1198 CK_IntegralToFloating);
1199 return FloatTy;
1200 }
1201
1202 // Convert both sides to the appropriate complex float.
1203 assert(IntTy->isComplexIntegerType());
1204 QualType result = S.Context.getComplexType(FloatTy);
1205
1206 // _Complex int -> _Complex float
1207 if (ConvertInt)
1208 IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1209 CK_IntegralComplexToFloatingComplex);
1210
1211 // float -> _Complex float
1212 if (ConvertFloat)
1213 FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1214 CK_FloatingRealToComplex);
1215
1216 return result;
1217}
1218
1219/// Handle arithmethic conversion with floating point types. Helper
1220/// function of UsualArithmeticConversions()
1222 ExprResult &RHS, QualType LHSType,
1223 QualType RHSType, bool IsCompAssign) {
1224 bool LHSFloat = LHSType->isRealFloatingType();
1225 bool RHSFloat = RHSType->isRealFloatingType();
1226
1227 // N1169 4.1.4: If one of the operands has a floating type and the other
1228 // operand has a fixed-point type, the fixed-point operand
1229 // is converted to the floating type [...]
1230 if (LHSType->isFixedPointType() || RHSType->isFixedPointType()) {
1231 if (LHSFloat)
1232 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FixedPointToFloating);
1233 else if (!IsCompAssign)
1234 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FixedPointToFloating);
1235 return LHSFloat ? LHSType : RHSType;
1236 }
1237
1238 // If we have two real floating types, convert the smaller operand
1239 // to the bigger result.
1240 if (LHSFloat && RHSFloat) {
1241 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1242 if (order > 0) {
1243 RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1244 return LHSType;
1245 }
1246
1247 assert(order < 0 && "illegal float comparison");
1248 if (!IsCompAssign)
1249 LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1250 return RHSType;
1251 }
1252
1253 if (LHSFloat) {
1254 // Half FP has to be promoted to float unless it is natively supported
1255 if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1256 LHSType = S.Context.FloatTy;
1257
1258 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1259 /*ConvertFloat=*/!IsCompAssign,
1260 /*ConvertInt=*/ true);
1261 }
1262 assert(RHSFloat);
1263 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1264 /*ConvertFloat=*/ true,
1265 /*ConvertInt=*/!IsCompAssign);
1266}
1267
1268/// Diagnose attempts to convert between __float128, __ibm128 and
1269/// long double if there is no support for such conversion.
1270/// Helper function of UsualArithmeticConversions().
1271static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1272 QualType RHSType) {
1273 // No issue if either is not a floating point type.
1274 if (!LHSType->isFloatingType() || !RHSType->isFloatingType())
1275 return false;
1276
1277 // No issue if both have the same 128-bit float semantics.
1278 auto *LHSComplex = LHSType->getAs<ComplexType>();
1279 auto *RHSComplex = RHSType->getAs<ComplexType>();
1280
1281 QualType LHSElem = LHSComplex ? LHSComplex->getElementType() : LHSType;
1282 QualType RHSElem = RHSComplex ? RHSComplex->getElementType() : RHSType;
1283
1284 const llvm::fltSemantics &LHSSem = S.Context.getFloatTypeSemantics(LHSElem);
1285 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(RHSElem);
1286
1287 if ((&LHSSem != &llvm::APFloat::PPCDoubleDouble() ||
1288 &RHSSem != &llvm::APFloat::IEEEquad()) &&
1289 (&LHSSem != &llvm::APFloat::IEEEquad() ||
1290 &RHSSem != &llvm::APFloat::PPCDoubleDouble()))
1291 return false;
1292
1293 return true;
1294}
1295
1296typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1297
1298namespace {
1299/// These helper callbacks are placed in an anonymous namespace to
1300/// permit their use as function template parameters.
1301ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1302 return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1303}
1304
1305ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1306 return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1307 CK_IntegralComplexCast);
1308}
1309}
1310
1311/// Handle integer arithmetic conversions. Helper function of
1312/// UsualArithmeticConversions()
1313template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1315 ExprResult &RHS, QualType LHSType,
1316 QualType RHSType, bool IsCompAssign) {
1317 // The rules for this case are in C99 6.3.1.8
1318 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1319 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1320 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1321 if (LHSSigned == RHSSigned) {
1322 // Same signedness; use the higher-ranked type
1323 if (order >= 0) {
1324 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1325 return LHSType;
1326 } else if (!IsCompAssign)
1327 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1328 return RHSType;
1329 } else if (order != (LHSSigned ? 1 : -1)) {
1330 // The unsigned type has greater than or equal rank to the
1331 // signed type, so use the unsigned type
1332 if (RHSSigned) {
1333 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1334 return LHSType;
1335 } else if (!IsCompAssign)
1336 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1337 return RHSType;
1338 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1339 // The two types are different widths; if we are here, that
1340 // means the signed type is larger than the unsigned type, so
1341 // use the signed type.
1342 if (LHSSigned) {
1343 RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1344 return LHSType;
1345 } else if (!IsCompAssign)
1346 LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1347 return RHSType;
1348 } else {
1349 // The signed type is higher-ranked than the unsigned type,
1350 // but isn't actually any bigger (like unsigned int and long
1351 // on most 32-bit systems). Use the unsigned type corresponding
1352 // to the signed type.
1353 QualType result =
1354 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1355 RHS = (*doRHSCast)(S, RHS.get(), result);
1356 if (!IsCompAssign)
1357 LHS = (*doLHSCast)(S, LHS.get(), result);
1358 return result;
1359 }
1360}
1361
1362/// Handle conversions with GCC complex int extension. Helper function
1363/// of UsualArithmeticConversions()
1365 ExprResult &RHS, QualType LHSType,
1366 QualType RHSType,
1367 bool IsCompAssign) {
1368 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1369 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1370
1371 if (LHSComplexInt && RHSComplexInt) {
1372 QualType LHSEltType = LHSComplexInt->getElementType();
1373 QualType RHSEltType = RHSComplexInt->getElementType();
1374 QualType ScalarType =
1375 handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1376 (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1377
1378 return S.Context.getComplexType(ScalarType);
1379 }
1380
1381 if (LHSComplexInt) {
1382 QualType LHSEltType = LHSComplexInt->getElementType();
1383 QualType ScalarType =
1384 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1385 (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1387 RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1388 CK_IntegralRealToComplex);
1389
1390 return ComplexType;
1391 }
1392
1393 assert(RHSComplexInt);
1394
1395 QualType RHSEltType = RHSComplexInt->getElementType();
1396 QualType ScalarType =
1397 handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1398 (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1400
1401 if (!IsCompAssign)
1402 LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1403 CK_IntegralRealToComplex);
1404 return ComplexType;
1405}
1406
1407/// Return the rank of a given fixed point or integer type. The value itself
1408/// doesn't matter, but the values must be increasing with proper increasing
1409/// rank as described in N1169 4.1.1.
1410static unsigned GetFixedPointRank(QualType Ty) {
1411 const auto *BTy = Ty->getAs<BuiltinType>();
1412 assert(BTy && "Expected a builtin type.");
1413
1414 switch (BTy->getKind()) {
1415 case BuiltinType::ShortFract:
1416 case BuiltinType::UShortFract:
1417 case BuiltinType::SatShortFract:
1418 case BuiltinType::SatUShortFract:
1419 return 1;
1420 case BuiltinType::Fract:
1421 case BuiltinType::UFract:
1422 case BuiltinType::SatFract:
1423 case BuiltinType::SatUFract:
1424 return 2;
1425 case BuiltinType::LongFract:
1426 case BuiltinType::ULongFract:
1427 case BuiltinType::SatLongFract:
1428 case BuiltinType::SatULongFract:
1429 return 3;
1430 case BuiltinType::ShortAccum:
1431 case BuiltinType::UShortAccum:
1432 case BuiltinType::SatShortAccum:
1433 case BuiltinType::SatUShortAccum:
1434 return 4;
1435 case BuiltinType::Accum:
1436 case BuiltinType::UAccum:
1437 case BuiltinType::SatAccum:
1438 case BuiltinType::SatUAccum:
1439 return 5;
1440 case BuiltinType::LongAccum:
1441 case BuiltinType::ULongAccum:
1442 case BuiltinType::SatLongAccum:
1443 case BuiltinType::SatULongAccum:
1444 return 6;
1445 default:
1446 if (BTy->isInteger())
1447 return 0;
1448 llvm_unreachable("Unexpected fixed point or integer type");
1449 }
1450}
1451
1452/// handleFixedPointConversion - Fixed point operations between fixed
1453/// point types and integers or other fixed point types do not fall under
1454/// usual arithmetic conversion since these conversions could result in loss
1455/// of precsision (N1169 4.1.4). These operations should be calculated with
1456/// the full precision of their result type (N1169 4.1.6.2.1).
1458 QualType RHSTy) {
1459 assert((LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) &&
1460 "Expected at least one of the operands to be a fixed point type");
1461 assert((LHSTy->isFixedPointOrIntegerType() ||
1462 RHSTy->isFixedPointOrIntegerType()) &&
1463 "Special fixed point arithmetic operation conversions are only "
1464 "applied to ints or other fixed point types");
1465
1466 // If one operand has signed fixed-point type and the other operand has
1467 // unsigned fixed-point type, then the unsigned fixed-point operand is
1468 // converted to its corresponding signed fixed-point type and the resulting
1469 // type is the type of the converted operand.
1470 if (RHSTy->isSignedFixedPointType() && LHSTy->isUnsignedFixedPointType())
1472 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1474
1475 // The result type is the type with the highest rank, whereby a fixed-point
1476 // conversion rank is always greater than an integer conversion rank; if the
1477 // type of either of the operands is a saturating fixedpoint type, the result
1478 // type shall be the saturating fixed-point type corresponding to the type
1479 // with the highest rank; the resulting value is converted (taking into
1480 // account rounding and overflow) to the precision of the resulting type.
1481 // Same ranks between signed and unsigned types are resolved earlier, so both
1482 // types are either signed or both unsigned at this point.
1483 unsigned LHSTyRank = GetFixedPointRank(LHSTy);
1484 unsigned RHSTyRank = GetFixedPointRank(RHSTy);
1485
1486 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1487
1489 ResultTy = S.Context.getCorrespondingSaturatedType(ResultTy);
1490
1491 return ResultTy;
1492}
1493
1494/// Check that the usual arithmetic conversions can be performed on this pair of
1495/// expressions that might be of enumeration type.
1497 SourceLocation Loc,
1498 Sema::ArithConvKind ACK) {
1499 // C++2a [expr.arith.conv]p1:
1500 // If one operand is of enumeration type and the other operand is of a
1501 // different enumeration type or a floating-point type, this behavior is
1502 // deprecated ([depr.arith.conv.enum]).
1503 //
1504 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1505 // Eventually we will presumably reject these cases (in C++23 onwards?).
1507 R = RHS->getEnumCoercedType(S.Context);
1508 bool LEnum = L->isUnscopedEnumerationType(),
1509 REnum = R->isUnscopedEnumerationType();
1510 bool IsCompAssign = ACK == Sema::ACK_CompAssign;
1511 if ((!IsCompAssign && LEnum && R->isFloatingType()) ||
1512 (REnum && L->isFloatingType())) {
1513 S.Diag(Loc, S.getLangOpts().CPlusPlus26
1514 ? diag::err_arith_conv_enum_float_cxx26
1515 : S.getLangOpts().CPlusPlus20
1516 ? diag::warn_arith_conv_enum_float_cxx20
1517 : diag::warn_arith_conv_enum_float)
1518 << LHS->getSourceRange() << RHS->getSourceRange() << (int)ACK << LEnum
1519 << L << R;
1520 } else if (!IsCompAssign && LEnum && REnum &&
1522 unsigned DiagID;
1523 // In C++ 26, usual arithmetic conversions between 2 different enum types
1524 // are ill-formed.
1525 if (S.getLangOpts().CPlusPlus26)
1526 DiagID = diag::err_conv_mixed_enum_types_cxx26;
1527 else if (!L->castAs<EnumType>()->getDecl()->hasNameForLinkage() ||
1528 !R->castAs<EnumType>()->getDecl()->hasNameForLinkage()) {
1529 // If either enumeration type is unnamed, it's less likely that the
1530 // user cares about this, but this situation is still deprecated in
1531 // C++2a. Use a different warning group.
1532 DiagID = S.getLangOpts().CPlusPlus20
1533 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1534 : diag::warn_arith_conv_mixed_anon_enum_types;
1535 } else if (ACK == Sema::ACK_Conditional) {
1536 // Conditional expressions are separated out because they have
1537 // historically had a different warning flag.
1538 DiagID = S.getLangOpts().CPlusPlus20
1539 ? diag::warn_conditional_mixed_enum_types_cxx20
1540 : diag::warn_conditional_mixed_enum_types;
1541 } else if (ACK == Sema::ACK_Comparison) {
1542 // Comparison expressions are separated out because they have
1543 // historically had a different warning flag.
1544 DiagID = S.getLangOpts().CPlusPlus20
1545 ? diag::warn_comparison_mixed_enum_types_cxx20
1546 : diag::warn_comparison_mixed_enum_types;
1547 } else {
1548 DiagID = S.getLangOpts().CPlusPlus20
1549 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1550 : diag::warn_arith_conv_mixed_enum_types;
1551 }
1552 S.Diag(Loc, DiagID) << LHS->getSourceRange() << RHS->getSourceRange()
1553 << (int)ACK << L << R;
1554 }
1555}
1556
1557/// UsualArithmeticConversions - Performs various conversions that are common to
1558/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1559/// routine returns the first non-arithmetic type found. The client is
1560/// responsible for emitting appropriate error diagnostics.
1562 SourceLocation Loc,
1563 ArithConvKind ACK) {
1564 checkEnumArithmeticConversions(*this, LHS.get(), RHS.get(), Loc, ACK);
1565
1566 if (ACK != ACK_CompAssign) {
1567 LHS = UsualUnaryConversions(LHS.get());
1568 if (LHS.isInvalid())
1569 return QualType();
1570 }
1571
1572 RHS = UsualUnaryConversions(RHS.get());
1573 if (RHS.isInvalid())
1574 return QualType();
1575
1576 // For conversion purposes, we ignore any qualifiers.
1577 // For example, "const float" and "float" are equivalent.
1578 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
1579 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
1580
1581 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1582 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1583 LHSType = AtomicLHS->getValueType();
1584
1585 // If both types are identical, no conversion is needed.
1586 if (Context.hasSameType(LHSType, RHSType))
1587 return Context.getCommonSugaredType(LHSType, RHSType);
1588
1589 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1590 // The caller can deal with this (e.g. pointer + int).
1591 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1592 return QualType();
1593
1594 // Apply unary and bitfield promotions to the LHS's type.
1595 QualType LHSUnpromotedType = LHSType;
1596 if (Context.isPromotableIntegerType(LHSType))
1597 LHSType = Context.getPromotedIntegerType(LHSType);
1598 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1599 if (!LHSBitfieldPromoteTy.isNull())
1600 LHSType = LHSBitfieldPromoteTy;
1601 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1602 LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1603
1604 // If both types are identical, no conversion is needed.
1605 if (Context.hasSameType(LHSType, RHSType))
1606 return Context.getCommonSugaredType(LHSType, RHSType);
1607
1608 // At this point, we have two different arithmetic types.
1609
1610 // Diagnose attempts to convert between __ibm128, __float128 and long double
1611 // where such conversions currently can't be handled.
1612 if (unsupportedTypeConversion(*this, LHSType, RHSType))
1613 return QualType();
1614
1615 // Handle complex types first (C99 6.3.1.8p1).
1616 if (LHSType->isComplexType() || RHSType->isComplexType())
1617 return handleComplexConversion(*this, LHS, RHS, LHSType, RHSType,
1618 ACK == ACK_CompAssign);
1619
1620 // Now handle "real" floating types (i.e. float, double, long double).
1621 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1622 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1623 ACK == ACK_CompAssign);
1624
1625 // Handle GCC complex int extension.
1626 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1627 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1628 ACK == ACK_CompAssign);
1629
1630 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1631 return handleFixedPointConversion(*this, LHSType, RHSType);
1632
1633 // Finally, we have two differing integer types.
1634 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1635 (*this, LHS, RHS, LHSType, RHSType, ACK == ACK_CompAssign);
1636}
1637
1638//===----------------------------------------------------------------------===//
1639// Semantic Analysis for various Expression Types
1640//===----------------------------------------------------------------------===//
1641
1642
1644 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1645 bool PredicateIsExpr, void *ControllingExprOrType,
1646 ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs) {
1647 unsigned NumAssocs = ArgTypes.size();
1648 assert(NumAssocs == ArgExprs.size());
1649
1650 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1651 for (unsigned i = 0; i < NumAssocs; ++i) {
1652 if (ArgTypes[i])
1653 (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1654 else
1655 Types[i] = nullptr;
1656 }
1657
1658 // If we have a controlling type, we need to convert it from a parsed type
1659 // into a semantic type and then pass that along.
1660 if (!PredicateIsExpr) {
1661 TypeSourceInfo *ControllingType;
1662 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType),
1663 &ControllingType);
1664 assert(ControllingType && "couldn't get the type out of the parser");
1665 ControllingExprOrType = ControllingType;
1666 }
1667
1669 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1670 llvm::ArrayRef(Types, NumAssocs), ArgExprs);
1671 delete [] Types;
1672 return ER;
1673}
1674
1676 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1677 bool PredicateIsExpr, void *ControllingExprOrType,
1679 unsigned NumAssocs = Types.size();
1680 assert(NumAssocs == Exprs.size());
1681 assert(ControllingExprOrType &&
1682 "Must have either a controlling expression or a controlling type");
1683
1684 Expr *ControllingExpr = nullptr;
1685 TypeSourceInfo *ControllingType = nullptr;
1686 if (PredicateIsExpr) {
1687 // Decay and strip qualifiers for the controlling expression type, and
1688 // handle placeholder type replacement. See committee discussion from WG14
1689 // DR423.
1693 reinterpret_cast<Expr *>(ControllingExprOrType));
1694 if (R.isInvalid())
1695 return ExprError();
1696 ControllingExpr = R.get();
1697 } else {
1698 // The extension form uses the type directly rather than converting it.
1699 ControllingType = reinterpret_cast<TypeSourceInfo *>(ControllingExprOrType);
1700 if (!ControllingType)
1701 return ExprError();
1702 }
1703
1704 bool TypeErrorFound = false,
1705 IsResultDependent = ControllingExpr
1706 ? ControllingExpr->isTypeDependent()
1707 : ControllingType->getType()->isDependentType(),
1708 ContainsUnexpandedParameterPack =
1709 ControllingExpr
1710 ? ControllingExpr->containsUnexpandedParameterPack()
1711 : ControllingType->getType()->containsUnexpandedParameterPack();
1712
1713 // The controlling expression is an unevaluated operand, so side effects are
1714 // likely unintended.
1715 if (!inTemplateInstantiation() && !IsResultDependent && ControllingExpr &&
1716 ControllingExpr->HasSideEffects(Context, false))
1717 Diag(ControllingExpr->getExprLoc(),
1718 diag::warn_side_effects_unevaluated_context);
1719
1720 for (unsigned i = 0; i < NumAssocs; ++i) {
1721 if (Exprs[i]->containsUnexpandedParameterPack())
1722 ContainsUnexpandedParameterPack = true;
1723
1724 if (Types[i]) {
1725 if (Types[i]->getType()->containsUnexpandedParameterPack())
1726 ContainsUnexpandedParameterPack = true;
1727
1728 if (Types[i]->getType()->isDependentType()) {
1729 IsResultDependent = true;
1730 } else {
1731 // We relax the restriction on use of incomplete types and non-object
1732 // types with the type-based extension of _Generic. Allowing incomplete
1733 // objects means those can be used as "tags" for a type-safe way to map
1734 // to a value. Similarly, matching on function types rather than
1735 // function pointer types can be useful. However, the restriction on VM
1736 // types makes sense to retain as there are open questions about how
1737 // the selection can be made at compile time.
1738 //
1739 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1740 // complete object type other than a variably modified type."
1741 unsigned D = 0;
1742 if (ControllingExpr && Types[i]->getType()->isIncompleteType())
1743 D = diag::err_assoc_type_incomplete;
1744 else if (ControllingExpr && !Types[i]->getType()->isObjectType())
1745 D = diag::err_assoc_type_nonobject;
1746 else if (Types[i]->getType()->isVariablyModifiedType())
1747 D = diag::err_assoc_type_variably_modified;
1748 else if (ControllingExpr) {
1749 // Because the controlling expression undergoes lvalue conversion,
1750 // array conversion, and function conversion, an association which is
1751 // of array type, function type, or is qualified can never be
1752 // reached. We will warn about this so users are less surprised by
1753 // the unreachable association. However, we don't have to handle
1754 // function types; that's not an object type, so it's handled above.
1755 //
1756 // The logic is somewhat different for C++ because C++ has different
1757 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1758 // If T is a non-class type, the type of the prvalue is the cv-
1759 // unqualified version of T. Otherwise, the type of the prvalue is T.
1760 // The result of these rules is that all qualified types in an
1761 // association in C are unreachable, and in C++, only qualified non-
1762 // class types are unreachable.
1763 //
1764 // NB: this does not apply when the first operand is a type rather
1765 // than an expression, because the type form does not undergo
1766 // conversion.
1767 unsigned Reason = 0;
1768 QualType QT = Types[i]->getType();
1769 if (QT->isArrayType())
1770 Reason = 1;
1771 else if (QT.hasQualifiers() &&
1772 (!LangOpts.CPlusPlus || !QT->isRecordType()))
1773 Reason = 2;
1774
1775 if (Reason)
1776 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1777 diag::warn_unreachable_association)
1778 << QT << (Reason - 1);
1779 }
1780
1781 if (D != 0) {
1782 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1783 << Types[i]->getTypeLoc().getSourceRange()
1784 << Types[i]->getType();
1785 TypeErrorFound = true;
1786 }
1787
1788 // C11 6.5.1.1p2 "No two generic associations in the same generic
1789 // selection shall specify compatible types."
1790 for (unsigned j = i+1; j < NumAssocs; ++j)
1791 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1792 Context.typesAreCompatible(Types[i]->getType(),
1793 Types[j]->getType())) {
1794 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1795 diag::err_assoc_compatible_types)
1796 << Types[j]->getTypeLoc().getSourceRange()
1797 << Types[j]->getType()
1798 << Types[i]->getType();
1799 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1800 diag::note_compat_assoc)
1801 << Types[i]->getTypeLoc().getSourceRange()
1802 << Types[i]->getType();
1803 TypeErrorFound = true;
1804 }
1805 }
1806 }
1807 }
1808 if (TypeErrorFound)
1809 return ExprError();
1810
1811 // If we determined that the generic selection is result-dependent, don't
1812 // try to compute the result expression.
1813 if (IsResultDependent) {
1814 if (ControllingExpr)
1815 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingExpr,
1816 Types, Exprs, DefaultLoc, RParenLoc,
1817 ContainsUnexpandedParameterPack);
1818 return GenericSelectionExpr::Create(Context, KeyLoc, ControllingType, Types,
1819 Exprs, DefaultLoc, RParenLoc,
1820 ContainsUnexpandedParameterPack);
1821 }
1822
1823 SmallVector<unsigned, 1> CompatIndices;
1824 unsigned DefaultIndex = -1U;
1825 // Look at the canonical type of the controlling expression in case it was a
1826 // deduced type like __auto_type. However, when issuing diagnostics, use the
1827 // type the user wrote in source rather than the canonical one.
1828 for (unsigned i = 0; i < NumAssocs; ++i) {
1829 if (!Types[i])
1830 DefaultIndex = i;
1831 else if (ControllingExpr &&
1833 ControllingExpr->getType().getCanonicalType(),
1834 Types[i]->getType()))
1835 CompatIndices.push_back(i);
1836 else if (ControllingType &&
1838 ControllingType->getType().getCanonicalType(),
1839 Types[i]->getType()))
1840 CompatIndices.push_back(i);
1841 }
1842
1843 auto GetControllingRangeAndType = [](Expr *ControllingExpr,
1844 TypeSourceInfo *ControllingType) {
1845 // We strip parens here because the controlling expression is typically
1846 // parenthesized in macro definitions.
1847 if (ControllingExpr)
1848 ControllingExpr = ControllingExpr->IgnoreParens();
1849
1850 SourceRange SR = ControllingExpr
1851 ? ControllingExpr->getSourceRange()
1852 : ControllingType->getTypeLoc().getSourceRange();
1853 QualType QT = ControllingExpr ? ControllingExpr->getType()
1854 : ControllingType->getType();
1855
1856 return std::make_pair(SR, QT);
1857 };
1858
1859 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1860 // type compatible with at most one of the types named in its generic
1861 // association list."
1862 if (CompatIndices.size() > 1) {
1863 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1864 SourceRange SR = P.first;
1865 Diag(SR.getBegin(), diag::err_generic_sel_multi_match)
1866 << SR << P.second << (unsigned)CompatIndices.size();
1867 for (unsigned I : CompatIndices) {
1868 Diag(Types[I]->getTypeLoc().getBeginLoc(),
1869 diag::note_compat_assoc)
1870 << Types[I]->getTypeLoc().getSourceRange()
1871 << Types[I]->getType();
1872 }
1873 return ExprError();
1874 }
1875
1876 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1877 // its controlling expression shall have type compatible with exactly one of
1878 // the types named in its generic association list."
1879 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1880 auto P = GetControllingRangeAndType(ControllingExpr, ControllingType);
1881 SourceRange SR = P.first;
1882 Diag(SR.getBegin(), diag::err_generic_sel_no_match) << SR << P.second;
1883 return ExprError();
1884 }
1885
1886 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1887 // type name that is compatible with the type of the controlling expression,
1888 // then the result expression of the generic selection is the expression
1889 // in that generic association. Otherwise, the result expression of the
1890 // generic selection is the expression in the default generic association."
1891 unsigned ResultIndex =
1892 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1893
1894 if (ControllingExpr) {
1896 Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1897 ContainsUnexpandedParameterPack, ResultIndex);
1898 }
1900 Context, KeyLoc, ControllingType, Types, Exprs, DefaultLoc, RParenLoc,
1901 ContainsUnexpandedParameterPack, ResultIndex);
1902}
1903
1905 switch (Kind) {
1906 default:
1907 llvm_unreachable("unexpected TokenKind");
1908 case tok::kw___func__:
1909 return PredefinedIdentKind::Func; // [C99 6.4.2.2]
1910 case tok::kw___FUNCTION__:
1912 case tok::kw___FUNCDNAME__:
1913 return PredefinedIdentKind::FuncDName; // [MS]
1914 case tok::kw___FUNCSIG__:
1915 return PredefinedIdentKind::FuncSig; // [MS]
1916 case tok::kw_L__FUNCTION__:
1917 return PredefinedIdentKind::LFunction; // [MS]
1918 case tok::kw_L__FUNCSIG__:
1919 return PredefinedIdentKind::LFuncSig; // [MS]
1920 case tok::kw___PRETTY_FUNCTION__:
1922 }
1923}
1924
1925/// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1926/// to determine the value of a PredefinedExpr. This can be either a
1927/// block, lambda, captured statement, function, otherwise a nullptr.
1929 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(DC))
1930 DC = DC->getParent();
1931 return cast_or_null<Decl>(DC);
1932}
1933
1934/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1935/// location of the token and the offset of the ud-suffix within it.
1937 unsigned Offset) {
1938 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1939 S.getLangOpts());
1940}
1941
1942/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1943/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1945 IdentifierInfo *UDSuffix,
1946 SourceLocation UDSuffixLoc,
1947 ArrayRef<Expr*> Args,
1948 SourceLocation LitEndLoc) {
1949 assert(Args.size() <= 2 && "too many arguments for literal operator");
1950
1951 QualType ArgTy[2];
1952 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1953 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1954 if (ArgTy[ArgIdx]->isArrayType())
1955 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1956 }
1957
1958 DeclarationName OpName =
1960 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1961 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1962
1963 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1964 if (S.LookupLiteralOperator(Scope, R, llvm::ArrayRef(ArgTy, Args.size()),
1965 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1966 /*AllowStringTemplatePack*/ false,
1967 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1968 return ExprError();
1969
1970 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1971}
1972
1974 // StringToks needs backing storage as it doesn't hold array elements itself
1975 std::vector<Token> ExpandedToks;
1976 if (getLangOpts().MicrosoftExt)
1977 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
1978
1979 StringLiteralParser Literal(StringToks, PP,
1981 if (Literal.hadError)
1982 return ExprError();
1983
1984 SmallVector<SourceLocation, 4> StringTokLocs;
1985 for (const Token &Tok : StringToks)
1986 StringTokLocs.push_back(Tok.getLocation());
1987
1989 Context, Literal.GetString(), StringLiteralKind::Unevaluated, false, {},
1990 &StringTokLocs[0], StringTokLocs.size());
1991
1992 if (!Literal.getUDSuffix().empty()) {
1993 SourceLocation UDSuffixLoc =
1994 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1995 Literal.getUDSuffixOffset());
1996 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1997 }
1998
1999 return Lit;
2000}
2001
2002std::vector<Token>
2004 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
2005 // local macros that expand to string literals that may be concatenated.
2006 // These macros are expanded here (in Sema), because StringLiteralParser
2007 // (in Lex) doesn't know the enclosing function (because it hasn't been
2008 // parsed yet).
2009 assert(getLangOpts().MicrosoftExt);
2010
2011 // Note: Although function local macros are defined only inside functions,
2012 // we ensure a valid `CurrentDecl` even outside of a function. This allows
2013 // expansion of macros into empty string literals without additional checks.
2014 Decl *CurrentDecl = getPredefinedExprDecl(CurContext);
2015 if (!CurrentDecl)
2016 CurrentDecl = Context.getTranslationUnitDecl();
2017
2018 std::vector<Token> ExpandedToks;
2019 ExpandedToks.reserve(Toks.size());
2020 for (const Token &Tok : Toks) {
2021 if (!isFunctionLocalStringLiteralMacro(Tok.getKind(), getLangOpts())) {
2022 assert(tok::isStringLiteral(Tok.getKind()));
2023 ExpandedToks.emplace_back(Tok);
2024 continue;
2025 }
2026 if (isa<TranslationUnitDecl>(CurrentDecl))
2027 Diag(Tok.getLocation(), diag::ext_predef_outside_function);
2028 // Stringify predefined expression
2029 Diag(Tok.getLocation(), diag::ext_string_literal_from_predefined)
2030 << Tok.getKind();
2031 SmallString<64> Str;
2032 llvm::raw_svector_ostream OS(Str);
2033 Token &Exp = ExpandedToks.emplace_back();
2034 Exp.startToken();
2035 if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
2036 Tok.getKind() == tok::kw_L__FUNCSIG__) {
2037 OS << 'L';
2038 Exp.setKind(tok::wide_string_literal);
2039 } else {
2040 Exp.setKind(tok::string_literal);
2041 }
2042 OS << '"'
2044 getPredefinedExprKind(Tok.getKind()), CurrentDecl))
2045 << '"';
2046 PP.CreateString(OS.str(), Exp, Tok.getLocation(), Tok.getEndLoc());
2047 }
2048 return ExpandedToks;
2049}
2050
2051/// ActOnStringLiteral - The specified tokens were lexed as pasted string
2052/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
2053/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
2054/// multiple tokens. However, the common case is that StringToks points to one
2055/// string.
2056///
2059 assert(!StringToks.empty() && "Must have at least one string!");
2060
2061 // StringToks needs backing storage as it doesn't hold array elements itself
2062 std::vector<Token> ExpandedToks;
2063 if (getLangOpts().MicrosoftExt)
2064 StringToks = ExpandedToks = ExpandFunctionLocalPredefinedMacros(StringToks);
2065
2066 StringLiteralParser Literal(StringToks, PP);
2067 if (Literal.hadError)
2068 return ExprError();
2069
2070 SmallVector<SourceLocation, 4> StringTokLocs;
2071 for (const Token &Tok : StringToks)
2072 StringTokLocs.push_back(Tok.getLocation());
2073
2074 QualType CharTy = Context.CharTy;
2076 if (Literal.isWide()) {
2077 CharTy = Context.getWideCharType();
2079 } else if (Literal.isUTF8()) {
2080 if (getLangOpts().Char8)
2081 CharTy = Context.Char8Ty;
2083 } else if (Literal.isUTF16()) {
2084 CharTy = Context.Char16Ty;
2086 } else if (Literal.isUTF32()) {
2087 CharTy = Context.Char32Ty;
2089 } else if (Literal.isPascal()) {
2090 CharTy = Context.UnsignedCharTy;
2091 }
2092
2093 // Warn on initializing an array of char from a u8 string literal; this
2094 // becomes ill-formed in C++2a.
2096 !getLangOpts().Char8 && Kind == StringLiteralKind::UTF8) {
2097 Diag(StringTokLocs.front(), diag::warn_cxx20_compat_utf8_string);
2098
2099 // Create removals for all 'u8' prefixes in the string literal(s). This
2100 // ensures C++2a compatibility (but may change the program behavior when
2101 // built by non-Clang compilers for which the execution character set is
2102 // not always UTF-8).
2103 auto RemovalDiag = PDiag(diag::note_cxx20_compat_utf8_string_remove_u8);
2104 SourceLocation RemovalDiagLoc;
2105 for (const Token &Tok : StringToks) {
2106 if (Tok.getKind() == tok::utf8_string_literal) {
2107 if (RemovalDiagLoc.isInvalid())
2108 RemovalDiagLoc = Tok.getLocation();
2110 Tok.getLocation(),
2111 Lexer::AdvanceToTokenCharacter(Tok.getLocation(), 2,
2113 }
2114 }
2115 Diag(RemovalDiagLoc, RemovalDiag);
2116 }
2117
2118 QualType StrTy =
2119 Context.getStringLiteralArrayType(CharTy, Literal.GetNumStringChars());
2120
2121 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2122 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
2123 Kind, Literal.Pascal, StrTy,
2124 &StringTokLocs[0],
2125 StringTokLocs.size());
2126 if (Literal.getUDSuffix().empty())
2127 return Lit;
2128
2129 // We're building a user-defined literal.
2130 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2131 SourceLocation UDSuffixLoc =
2132 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
2133 Literal.getUDSuffixOffset());
2134
2135 // Make sure we're allowed user-defined literals here.
2136 if (!UDLScope)
2137 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
2138
2139 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2140 // operator "" X (str, len)
2141 QualType SizeType = Context.getSizeType();
2142
2143 DeclarationName OpName =
2145 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2146 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2147
2148 QualType ArgTy[] = {
2149 Context.getArrayDecayedType(StrTy), SizeType
2150 };
2151
2152 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2153 switch (LookupLiteralOperator(UDLScope, R, ArgTy,
2154 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2155 /*AllowStringTemplatePack*/ true,
2156 /*DiagnoseMissing*/ true, Lit)) {
2157
2158 case LOLR_Cooked: {
2159 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
2160 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
2161 StringTokLocs[0]);
2162 Expr *Args[] = { Lit, LenArg };
2163
2164 return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
2165 }
2166
2167 case LOLR_Template: {
2168 TemplateArgumentListInfo ExplicitArgs;
2169 TemplateArgument Arg(Lit);
2170 TemplateArgumentLocInfo ArgInfo(Lit);
2171 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2172 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2173 StringTokLocs.back(), &ExplicitArgs);
2174 }
2175
2177 TemplateArgumentListInfo ExplicitArgs;
2178
2179 unsigned CharBits = Context.getIntWidth(CharTy);
2180 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2181 llvm::APSInt Value(CharBits, CharIsUnsigned);
2182
2183 TemplateArgument TypeArg(CharTy);
2185 ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
2186
2187 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2188 Value = Lit->getCodeUnit(I);
2189 TemplateArgument Arg(Context, Value, CharTy);
2191 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2192 }
2193 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt,
2194 StringTokLocs.back(), &ExplicitArgs);
2195 }
2196 case LOLR_Raw:
2198 llvm_unreachable("unexpected literal operator lookup result");
2199 case LOLR_Error:
2200 return ExprError();
2201 }
2202 llvm_unreachable("unexpected literal operator lookup result");
2203}
2204
2207 SourceLocation Loc,
2208 const CXXScopeSpec *SS) {
2209 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2210 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2211}
2212
2215 const DeclarationNameInfo &NameInfo,
2216 const CXXScopeSpec *SS, NamedDecl *FoundD,
2217 SourceLocation TemplateKWLoc,
2218 const TemplateArgumentListInfo *TemplateArgs) {
2221 return BuildDeclRefExpr(D, Ty, VK, NameInfo, NNS, FoundD, TemplateKWLoc,
2222 TemplateArgs);
2223}
2224
2225// CUDA/HIP: Check whether a captured reference variable is referencing a
2226// host variable in a device or host device lambda.
2228 VarDecl *VD) {
2229 if (!S.getLangOpts().CUDA || !VD->hasInit())
2230 return false;
2231 assert(VD->getType()->isReferenceType());
2232
2233 // Check whether the reference variable is referencing a host variable.
2234 auto *DRE = dyn_cast<DeclRefExpr>(VD->getInit());
2235 if (!DRE)
2236 return false;
2237 auto *Referee = dyn_cast<VarDecl>(DRE->getDecl());
2238 if (!Referee || !Referee->hasGlobalStorage() ||
2239 Referee->hasAttr<CUDADeviceAttr>())
2240 return false;
2241
2242 // Check whether the current function is a device or host device lambda.
2243 // Check whether the reference variable is a capture by getDeclContext()
2244 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2245 auto *MD = dyn_cast_or_null<CXXMethodDecl>(S.CurContext);
2246 if (MD && MD->getParent()->isLambda() &&
2247 MD->getOverloadedOperator() == OO_Call && MD->hasAttr<CUDADeviceAttr>() &&
2248 VD->getDeclContext() != MD)
2249 return true;
2250
2251 return false;
2252}
2253
2255 // A declaration named in an unevaluated operand never constitutes an odr-use.
2257 return NOUR_Unevaluated;
2258
2259 // C++2a [basic.def.odr]p4:
2260 // A variable x whose name appears as a potentially-evaluated expression e
2261 // is odr-used by e unless [...] x is a reference that is usable in
2262 // constant expressions.
2263 // CUDA/HIP:
2264 // If a reference variable referencing a host variable is captured in a
2265 // device or host device lambda, the value of the referee must be copied
2266 // to the capture and the reference variable must be treated as odr-use
2267 // since the value of the referee is not known at compile time and must
2268 // be loaded from the captured.
2269 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2270 if (VD->getType()->isReferenceType() &&
2271 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2273 VD->isUsableInConstantExpressions(Context))
2274 return NOUR_Constant;
2275 }
2276
2277 // All remaining non-variable cases constitute an odr-use. For variables, we
2278 // need to wait and see how the expression is used.
2279 return NOUR_None;
2280}
2281
2282/// BuildDeclRefExpr - Build an expression that references a
2283/// declaration that does not require a closure capture.
2286 const DeclarationNameInfo &NameInfo,
2287 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2288 SourceLocation TemplateKWLoc,
2289 const TemplateArgumentListInfo *TemplateArgs) {
2290 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(D) &&
2291 NeedToCaptureVariable(D, NameInfo.getLoc());
2292
2294 Context, NNS, TemplateKWLoc, D, RefersToCapturedVariable, NameInfo, Ty,
2295 VK, FoundD, TemplateArgs, getNonOdrUseReasonInCurrentContext(D));
2297
2298 // C++ [except.spec]p17:
2299 // An exception-specification is considered to be needed when:
2300 // - in an expression, the function is the unique lookup result or
2301 // the selected member of a set of overloaded functions.
2302 //
2303 // We delay doing this until after we've built the function reference and
2304 // marked it as used so that:
2305 // a) if the function is defaulted, we get errors from defining it before /
2306 // instead of errors from computing its exception specification, and
2307 // b) if the function is a defaulted comparison, we can use the body we
2308 // build when defining it as input to the exception specification
2309 // computation rather than computing a new body.
2310 if (const auto *FPT = Ty->getAs<FunctionProtoType>()) {
2311 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
2312 if (const auto *NewFPT = ResolveExceptionSpec(NameInfo.getLoc(), FPT))
2314 }
2315 }
2316
2317 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2319 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2321
2322 const auto *FD = dyn_cast<FieldDecl>(D);
2323 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D))
2324 FD = IFD->getAnonField();
2325 if (FD) {
2326 UnusedPrivateFields.remove(FD);
2327 // Just in case we're building an illegal pointer-to-member.
2328 if (FD->isBitField())
2330 }
2331
2332 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2333 // designates a bit-field.
2334 if (const auto *BD = dyn_cast<BindingDecl>(D))
2335 if (const auto *BE = BD->getBinding())
2336 E->setObjectKind(BE->getObjectKind());
2337
2338 return E;
2339}
2340
2341/// Decomposes the given name into a DeclarationNameInfo, its location, and
2342/// possibly a list of template arguments.
2343///
2344/// If this produces template arguments, it is permitted to call
2345/// DecomposeTemplateName.
2346///
2347/// This actually loses a lot of source location information for
2348/// non-standard name kinds; we should consider preserving that in
2349/// some way.
2350void
2353 DeclarationNameInfo &NameInfo,
2354 const TemplateArgumentListInfo *&TemplateArgs) {
2355 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
2356 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
2357 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
2358
2359 ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
2360 Id.TemplateId->NumArgs);
2361 translateTemplateArguments(TemplateArgsPtr, Buffer);
2362
2363 TemplateName TName = Id.TemplateId->Template.get();
2364 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2365 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
2366 TemplateArgs = &Buffer;
2367 } else {
2368 NameInfo = GetNameFromUnqualifiedId(Id);
2369 TemplateArgs = nullptr;
2370 }
2371}
2372
2374 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2376 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2377 DeclContext *Ctx =
2378 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
2379 if (!TC) {
2380 // Emit a special diagnostic for failed member lookups.
2381 // FIXME: computing the declaration context might fail here (?)
2382 if (Ctx)
2383 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
2384 << SS.getRange();
2385 else
2386 SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
2387 return;
2388 }
2389
2390 std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
2391 bool DroppedSpecifier =
2392 TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
2393 unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
2394 ? diag::note_implicit_param_decl
2395 : diag::note_previous_decl;
2396 if (!Ctx)
2397 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
2398 SemaRef.PDiag(NoteID));
2399 else
2400 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
2401 << Typo << Ctx << DroppedSpecifier
2402 << SS.getRange(),
2403 SemaRef.PDiag(NoteID));
2404}
2405
2406/// Diagnose a lookup that found results in an enclosing class during error
2407/// recovery. This usually indicates that the results were found in a dependent
2408/// base class that could not be searched as part of a template definition.
2409/// Always issues a diagnostic (though this may be only a warning in MS
2410/// compatibility mode).
2411///
2412/// Return \c true if the error is unrecoverable, or \c false if the caller
2413/// should attempt to recover using these lookup results.
2415 // During a default argument instantiation the CurContext points
2416 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2417 // function parameter list, hence add an explicit check.
2418 bool isDefaultArgument =
2419 !CodeSynthesisContexts.empty() &&
2420 CodeSynthesisContexts.back().Kind ==
2422 const auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
2423 bool isInstance = CurMethod && CurMethod->isInstance() &&
2424 R.getNamingClass() == CurMethod->getParent() &&
2425 !isDefaultArgument;
2426
2427 // There are two ways we can find a class-scope declaration during template
2428 // instantiation that we did not find in the template definition: if it is a
2429 // member of a dependent base class, or if it is declared after the point of
2430 // use in the same class. Distinguish these by comparing the class in which
2431 // the member was found to the naming class of the lookup.
2432 unsigned DiagID = diag::err_found_in_dependent_base;
2433 unsigned NoteID = diag::note_member_declared_at;
2435 DiagID = getLangOpts().MSVCCompat ? diag::ext_found_later_in_class
2436 : diag::err_found_later_in_class;
2437 } else if (getLangOpts().MSVCCompat) {
2438 DiagID = diag::ext_found_in_dependent_base;
2439 NoteID = diag::note_dependent_member_use;
2440 }
2441
2442 if (isInstance) {
2443 // Give a code modification hint to insert 'this->'.
2444 Diag(R.getNameLoc(), DiagID)
2445 << R.getLookupName()
2446 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
2448 } else {
2449 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2450 // they're not shadowed).
2451 Diag(R.getNameLoc(), DiagID) << R.getLookupName();
2452 }
2453
2454 for (const NamedDecl *D : R)
2455 Diag(D->getLocation(), NoteID);
2456
2457 // Return true if we are inside a default argument instantiation
2458 // and the found name refers to an instance member function, otherwise
2459 // the caller will try to create an implicit member call and this is wrong
2460 // for default arguments.
2461 //
2462 // FIXME: Is this special case necessary? We could allow the caller to
2463 // diagnose this.
2464 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
2465 Diag(R.getNameLoc(), diag::err_member_call_without_object) << 0;
2466 return true;
2467 }
2468
2469 // Tell the callee to try to recover.
2470 return false;
2471}
2472
2473/// Diagnose an empty lookup.
2474///
2475/// \return false if new lookup candidates were found
2478 TemplateArgumentListInfo *ExplicitTemplateArgs,
2479 ArrayRef<Expr *> Args, DeclContext *LookupCtx,
2480 TypoExpr **Out) {
2481 DeclarationName Name = R.getLookupName();
2482
2483 unsigned diagnostic = diag::err_undeclared_var_use;
2484 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
2485 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
2486 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
2487 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
2488 diagnostic = diag::err_undeclared_use;
2489 diagnostic_suggest = diag::err_undeclared_use_suggest;
2490 }
2491
2492 // If the original lookup was an unqualified lookup, fake an
2493 // unqualified lookup. This is useful when (for example) the
2494 // original lookup would not have found something because it was a
2495 // dependent name.
2496 DeclContext *DC =
2497 LookupCtx ? LookupCtx : (SS.isEmpty() ? CurContext : nullptr);
2498 while (DC) {
2499 if (isa<CXXRecordDecl>(DC)) {
2500 LookupQualifiedName(R, DC);
2501
2502 if (!R.empty()) {
2503 // Don't give errors about ambiguities in this lookup.
2505
2506 // If there's a best viable function among the results, only mention
2507 // that one in the notes.
2508 OverloadCandidateSet Candidates(R.getNameLoc(),
2510 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, Candidates);
2512 if (Candidates.BestViableFunction(*this, R.getNameLoc(), Best) ==
2513 OR_Success) {
2514 R.clear();
2515 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
2516 R.resolveKind();
2517 }
2518
2520 }
2521
2522 R.clear();
2523 }
2524
2525 DC = DC->getLookupParent();
2526 }
2527
2528 // We didn't find anything, so try to correct for a typo.
2529 TypoCorrection Corrected;
2530 if (S && Out) {
2531 SourceLocation TypoLoc = R.getNameLoc();
2532 assert(!ExplicitTemplateArgs &&
2533 "Diagnosing an empty lookup with explicit template args!");
2534 *Out = CorrectTypoDelayed(
2535 R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
2536 [=](const TypoCorrection &TC) {
2537 emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
2538 diagnostic, diagnostic_suggest);
2539 },
2540 nullptr, CTK_ErrorRecovery, LookupCtx);
2541 if (*Out)
2542 return true;
2543 } else if (S && (Corrected =
2545 &SS, CCC, CTK_ErrorRecovery, LookupCtx))) {
2546 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
2547 bool DroppedSpecifier =
2548 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
2549 R.setLookupName(Corrected.getCorrection());
2550
2551 bool AcceptableWithRecovery = false;
2552 bool AcceptableWithoutRecovery = false;
2553 NamedDecl *ND = Corrected.getFoundDecl();
2554 if (ND) {
2555 if (Corrected.isOverloaded()) {
2559 for (NamedDecl *CD : Corrected) {
2560 if (FunctionTemplateDecl *FTD =
2561 dyn_cast<FunctionTemplateDecl>(CD))
2563 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2564 Args, OCS);
2565 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
2566 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2568 Args, OCS);
2569 }
2570 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
2571 case OR_Success:
2572 ND = Best->FoundDecl;
2573 Corrected.setCorrectionDecl(ND);
2574 break;
2575 default:
2576 // FIXME: Arbitrarily pick the first declaration for the note.
2577 Corrected.setCorrectionDecl(ND);
2578 break;
2579 }
2580 }
2581 R.addDecl(ND);
2582 if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2583 CXXRecordDecl *Record = nullptr;
2584 if (Corrected.getCorrectionSpecifier()) {
2585 const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2586 Record = Ty->getAsCXXRecordDecl();
2587 }
2588 if (!Record)
2589 Record = cast<CXXRecordDecl>(
2592 }
2593
2594 auto *UnderlyingND = ND->getUnderlyingDecl();
2595 AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2596 isa<FunctionTemplateDecl>(UnderlyingND);
2597 // FIXME: If we ended up with a typo for a type name or
2598 // Objective-C class name, we're in trouble because the parser
2599 // is in the wrong place to recover. Suggest the typo
2600 // correction, but don't make it a fix-it since we're not going
2601 // to recover well anyway.
2602 AcceptableWithoutRecovery = isa<TypeDecl>(UnderlyingND) ||
2603 getAsTypeTemplateDecl(UnderlyingND) ||
2604 isa<ObjCInterfaceDecl>(UnderlyingND);
2605 } else {
2606 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2607 // because we aren't able to recover.
2608 AcceptableWithoutRecovery = true;
2609 }
2610
2611 if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2612 unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2613 ? diag::note_implicit_param_decl
2614 : diag::note_previous_decl;
2615 if (SS.isEmpty())
2616 diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2617 PDiag(NoteID), AcceptableWithRecovery);
2618 else
2619 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2620 << Name << computeDeclContext(SS, false)
2621 << DroppedSpecifier << SS.getRange(),
2622 PDiag(NoteID), AcceptableWithRecovery);
2623
2624 // Tell the callee whether to try to recover.
2625 return !AcceptableWithRecovery;
2626 }
2627 }
2628 R.clear();
2629
2630 // Emit a special diagnostic for failed member lookups.
2631 // FIXME: computing the declaration context might fail here (?)
2632 if (!SS.isEmpty()) {
2633 Diag(R.getNameLoc(), diag::err_no_member)
2634 << Name << computeDeclContext(SS, false)
2635 << SS.getRange();
2636 return true;
2637 }
2638
2639 // Give up, we can't recover.
2640 Diag(R.getNameLoc(), diagnostic) << Name;
2641 return true;
2642}
2643
2644/// In Microsoft mode, if we are inside a template class whose parent class has
2645/// dependent base classes, and we can't resolve an unqualified identifier, then
2646/// assume the identifier is a member of a dependent base class. We can only
2647/// recover successfully in static methods, instance methods, and other contexts
2648/// where 'this' is available. This doesn't precisely match MSVC's
2649/// instantiation model, but it's close enough.
2650static Expr *
2652 DeclarationNameInfo &NameInfo,
2653 SourceLocation TemplateKWLoc,
2654 const TemplateArgumentListInfo *TemplateArgs) {
2655 // Only try to recover from lookup into dependent bases in static methods or
2656 // contexts where 'this' is available.
2657 QualType ThisType = S.getCurrentThisType();
2658 const CXXRecordDecl *RD = nullptr;
2659 if (!ThisType.isNull())
2660 RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2661 else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2662 RD = MD->getParent();
2663 if (!RD || !RD->hasDefinition() || !RD->hasAnyDependentBases())
2664 return nullptr;
2665
2666 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2667 // is available, suggest inserting 'this->' as a fixit.
2668 SourceLocation Loc = NameInfo.getLoc();
2669 auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2670 DB << NameInfo.getName() << RD;
2671
2672 if (!ThisType.isNull()) {
2673 DB << FixItHint::CreateInsertion(Loc, "this->");
2675 Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2676 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2677 /*FirstQualifierFoundInScope=*/nullptr, NameInfo, TemplateArgs);
2678 }
2679
2680 // Synthesize a fake NNS that points to the derived class. This will
2681 // perform name lookup during template instantiation.
2682 CXXScopeSpec SS;
2683 auto *NNS =
2684 NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2685 SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2687 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2688 TemplateArgs);
2689}
2690
2693 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2694 bool HasTrailingLParen, bool IsAddressOfOperand,
2696 bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2697 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2698 "cannot be direct & operand and have a trailing lparen");
2699 if (SS.isInvalid())
2700 return ExprError();
2701
2702 TemplateArgumentListInfo TemplateArgsBuffer;
2703
2704 // Decompose the UnqualifiedId into the following data.
2705 DeclarationNameInfo NameInfo;
2706 const TemplateArgumentListInfo *TemplateArgs;
2707 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2708
2709 DeclarationName Name = NameInfo.getName();
2710 IdentifierInfo *II = Name.getAsIdentifierInfo();
2711 SourceLocation NameLoc = NameInfo.getLoc();
2712
2713 if (II && II->isEditorPlaceholder()) {
2714 // FIXME: When typed placeholders are supported we can create a typed
2715 // placeholder expression node.
2716 return ExprError();
2717 }
2718
2719 // C++ [temp.dep.expr]p3:
2720 // An id-expression is type-dependent if it contains:
2721 // -- an identifier that was declared with a dependent type,
2722 // (note: handled after lookup)
2723 // -- a template-id that is dependent,
2724 // (note: handled in BuildTemplateIdExpr)
2725 // -- a conversion-function-id that specifies a dependent type,
2726 // -- a nested-name-specifier that contains a class-name that
2727 // names a dependent type.
2728 // Determine whether this is a member of an unknown specialization;
2729 // we need to handle these differently.
2730 bool DependentID = false;
2731 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2732 Name.getCXXNameType()->isDependentType()) {
2733 DependentID = true;
2734 } else if (SS.isSet()) {
2735 if (DeclContext *DC = computeDeclContext(SS, false)) {
2736 if (RequireCompleteDeclContext(SS, DC))
2737 return ExprError();
2738 } else {
2739 DependentID = true;
2740 }
2741 }
2742
2743 if (DependentID)
2744 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2745 IsAddressOfOperand, TemplateArgs);
2746
2747 // BoundsSafety: This specially handles arguments of bounds attributes
2748 // appertains to a type of C struct field such that the name lookup
2749 // within a struct finds the member name, which is not the case for other
2750 // contexts in C.
2751 if (isBoundsAttrContext() && !getLangOpts().CPlusPlus && S->isClassScope()) {
2752 // See if this is reference to a field of struct.
2753 LookupResult R(*this, NameInfo, LookupMemberName);
2754 // LookupParsedName handles a name lookup from within anonymous struct.
2755 if (LookupParsedName(R, S, &SS)) {
2756 if (auto *VD = dyn_cast<ValueDecl>(R.getFoundDecl())) {
2757 QualType type = VD->getType().getNonReferenceType();
2758 // This will eventually be translated into MemberExpr upon
2759 // the use of instantiated struct fields.
2760 return BuildDeclRefExpr(VD, type, VK_LValue, NameLoc);
2761 }
2762 }
2763 }
2764
2765 // Perform the required lookup.
2766 LookupResult R(*this, NameInfo,
2770 if (TemplateKWLoc.isValid() || TemplateArgs) {
2771 // Lookup the template name again to correctly establish the context in
2772 // which it was found. This is really unfortunate as we already did the
2773 // lookup to determine that it was a template name in the first place. If
2774 // this becomes a performance hit, we can work harder to preserve those
2775 // results until we get here but it's likely not worth it.
2776 bool MemberOfUnknownSpecialization;
2777 AssumedTemplateKind AssumedTemplate;
2778 if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2779 MemberOfUnknownSpecialization, TemplateKWLoc,
2780 &AssumedTemplate))
2781 return ExprError();
2782
2783 if (MemberOfUnknownSpecialization ||
2785 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2786 IsAddressOfOperand, TemplateArgs);
2787 } else {
2788 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2789 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2790
2791 // If the result might be in a dependent base class, this is a dependent
2792 // id-expression.
2794 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2795 IsAddressOfOperand, TemplateArgs);
2796
2797 // If this reference is in an Objective-C method, then we need to do
2798 // some special Objective-C lookup, too.
2799 if (IvarLookupFollowUp) {
2800 ExprResult E(LookupInObjCMethod(R, S, II, true));
2801 if (E.isInvalid())
2802 return ExprError();
2803
2804 if (Expr *Ex = E.getAs<Expr>())
2805 return Ex;
2806 }
2807 }
2808
2809 if (R.isAmbiguous())
2810 return ExprError();
2811
2812 // This could be an implicitly declared function reference if the language
2813 // mode allows it as a feature.
2814 if (R.empty() && HasTrailingLParen && II &&
2815 getLangOpts().implicitFunctionsAllowed()) {
2816 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2817 if (D) R.addDecl(D);
2818 }
2819
2820 // Determine whether this name might be a candidate for
2821 // argument-dependent lookup.
2822 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2823
2824 if (R.empty() && !ADL) {
2825 if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2826 if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2827 TemplateKWLoc, TemplateArgs))
2828 return E;
2829 }
2830
2831 // Don't diagnose an empty lookup for inline assembly.
2832 if (IsInlineAsmIdentifier)
2833 return ExprError();
2834
2835 // If this name wasn't predeclared and if this is not a function
2836 // call, diagnose the problem.
2837 TypoExpr *TE = nullptr;
2838 DefaultFilterCCC DefaultValidator(II, SS.isValid() ? SS.getScopeRep()
2839 : nullptr);
2840 DefaultValidator.IsAddressOfOperand = IsAddressOfOperand;
2841 assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2842 "Typo correction callback misconfigured");
2843 if (CCC) {
2844 // Make sure the callback knows what the typo being diagnosed is.
2845 CCC->setTypoName(II);
2846 if (SS.isValid())
2847 CCC->setTypoNNS(SS.getScopeRep());
2848 }
2849 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2850 // a template name, but we happen to have always already looked up the name
2851 // before we get here if it must be a template name.
2852 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator, nullptr,
2853 std::nullopt, nullptr, &TE)) {
2854 if (TE && KeywordReplacement) {
2855 auto &State = getTypoExprState(TE);
2856 auto BestTC = State.Consumer->getNextCorrection();
2857 if (BestTC.isKeyword()) {
2858 auto *II = BestTC.getCorrectionAsIdentifierInfo();
2859 if (State.DiagHandler)
2860 State.DiagHandler(BestTC);
2861 KeywordReplacement->startToken();
2862 KeywordReplacement->setKind(II->getTokenID());
2863 KeywordReplacement->setIdentifierInfo(II);
2864 KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2865 // Clean up the state associated with the TypoExpr, since it has
2866 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2867 clearDelayedTypo(TE);
2868 // Signal that a correction to a keyword was performed by returning a
2869 // valid-but-null ExprResult.
2870 return (Expr*)nullptr;
2871 }
2872 State.Consumer->resetCorrectionStream();
2873 }
2874 return TE ? TE : ExprError();
2875 }
2876
2877 assert(!R.empty() &&
2878 "DiagnoseEmptyLookup returned false but added no results");
2879
2880 // If we found an Objective-C instance variable, let
2881 // LookupInObjCMethod build the appropriate expression to
2882 // reference the ivar.
2883 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2884 R.clear();
2885 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2886 // In a hopelessly buggy code, Objective-C instance variable
2887 // lookup fails and no expression will be built to reference it.
2888 if (!E.isInvalid() && !E.get())
2889 return ExprError();
2890 return E;
2891 }
2892 }
2893
2894 // This is guaranteed from this point on.
2895 assert(!R.empty() || ADL);
2896
2897 // Check whether this might be a C++ implicit instance member access.
2898 // C++ [class.mfct.non-static]p3:
2899 // When an id-expression that is not part of a class member access
2900 // syntax and not used to form a pointer to member is used in the
2901 // body of a non-static member function of class X, if name lookup
2902 // resolves the name in the id-expression to a non-static non-type
2903 // member of some class C, the id-expression is transformed into a
2904 // class member access expression using (*this) as the
2905 // postfix-expression to the left of the . operator.
2906 //
2907 // But we don't actually need to do this for '&' operands if R
2908 // resolved to a function or overloaded function set, because the
2909 // expression is ill-formed if it actually works out to be a
2910 // non-static member function:
2911 //
2912 // C++ [expr.ref]p4:
2913 // Otherwise, if E1.E2 refers to a non-static member function. . .
2914 // [t]he expression can be used only as the left-hand operand of a
2915 // member function call.
2916 //
2917 // There are other safeguards against such uses, but it's important
2918 // to get this right here so that we don't end up making a
2919 // spuriously dependent expression if we're inside a dependent
2920 // instance method.
2921 if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2922 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2923 S);
2924
2925 if (TemplateArgs || TemplateKWLoc.isValid()) {
2926
2927 // In C++1y, if this is a variable template id, then check it
2928 // in BuildTemplateIdExpr().
2929 // The single lookup result must be a variable template declaration.
2930 if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2931 Id.TemplateId->Kind == TNK_Var_template) {
2932 assert(R.getAsSingle<VarTemplateDecl>() &&
2933 "There should only be one declaration found.");
2934 }
2935
2936 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2937 }
2938
2939 return BuildDeclarationNameExpr(SS, R, ADL);
2940}
2941
2942/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2943/// declaration name, generally during template instantiation.
2944/// There's a large number of things which don't need to be done along
2945/// this path.
2947 CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2948 bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2949 if (NameInfo.getName().isDependentName())
2950 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2951 NameInfo, /*TemplateArgs=*/nullptr);
2952
2953 DeclContext *DC = computeDeclContext(SS, false);
2954 if (!DC)
2955 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2956 NameInfo, /*TemplateArgs=*/nullptr);
2957
2958 if (RequireCompleteDeclContext(SS, DC))
2959 return ExprError();
2960
2961 LookupResult R(*this, NameInfo, LookupOrdinaryName);
2962 LookupQualifiedName(R, DC);
2963
2964 if (R.isAmbiguous())
2965 return ExprError();
2966
2968 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2969 NameInfo, /*TemplateArgs=*/nullptr);
2970
2971 if (R.empty()) {
2972 // Don't diagnose problems with invalid record decl, the secondary no_member
2973 // diagnostic during template instantiation is likely bogus, e.g. if a class
2974 // is invalid because it's derived from an invalid base class, then missing
2975 // members were likely supposed to be inherited.
2976 if (const auto *CD = dyn_cast<CXXRecordDecl>(DC))
2977 if (CD->isInvalidDecl())
2978 return ExprError();
2979 Diag(NameInfo.getLoc(), diag::err_no_member)
2980 << NameInfo.getName() << DC << SS.getRange();
2981 return ExprError();
2982 }
2983
2984 if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2985 // Diagnose a missing typename if this resolved unambiguously to a type in
2986 // a dependent context. If we can recover with a type, downgrade this to
2987 // a warning in Microsoft compatibility mode.
2988 unsigned DiagID = diag::err_typename_missing;
2989 if (RecoveryTSI && getLangOpts().MSVCCompat)
2990 DiagID = diag::ext_typename_missing;
2991 SourceLocation Loc = SS.getBeginLoc();
2992 auto D = Diag(Loc, DiagID);
2993 D << SS.getScopeRep() << NameInfo.getName().getAsString()
2994 << SourceRange(Loc, NameInfo.getEndLoc());
2995
2996 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2997 // context.
2998 if (!RecoveryTSI)
2999 return ExprError();
3000
3001 // Only issue the fixit if we're prepared to recover.
3002 D << FixItHint::CreateInsertion(Loc, "typename ");
3003
3004 // Recover by pretending this was an elaborated type.
3006 TypeLocBuilder TLB;
3007 TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
3008
3013
3014 *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
3015
3016 return ExprEmpty();
3017 }
3018
3019 // Defend against this resolving to an implicit member access. We usually
3020 // won't get here if this might be a legitimate a class member (we end up in
3021 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
3022 // a pointer-to-member or in an unevaluated context in C++11.
3023 if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
3025 /*TemplateKWLoc=*/SourceLocation(),
3026 R, /*TemplateArgs=*/nullptr, S);
3027
3028 return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
3029}
3030
3031/// The parser has read a name in, and Sema has detected that we're currently
3032/// inside an ObjC method. Perform some additional checks and determine if we
3033/// should form a reference to an ivar.
3034///
3035/// Ideally, most of this would be done by lookup, but there's
3036/// actually quite a lot of extra work involved.
3038 IdentifierInfo *II) {
3039 SourceLocation Loc = Lookup.getNameLoc();
3040 ObjCMethodDecl *CurMethod = getCurMethodDecl();
3041
3042 // Check for error condition which is already reported.
3043 if (!CurMethod)
3044 return DeclResult(true);
3045
3046 // There are two cases to handle here. 1) scoped lookup could have failed,
3047 // in which case we should look for an ivar. 2) scoped lookup could have
3048 // found a decl, but that decl is outside the current instance method (i.e.
3049 // a global variable). In these two cases, we do a lookup for an ivar with
3050 // this name, if the lookup sucedes, we replace it our current decl.
3051
3052 // If we're in a class method, we don't normally want to look for
3053 // ivars. But if we don't find anything else, and there's an
3054 // ivar, that's an error.
3055 bool IsClassMethod = CurMethod->isClassMethod();
3056
3057 bool LookForIvars;
3058 if (Lookup.empty())
3059 LookForIvars = true;
3060 else if (IsClassMethod)
3061 LookForIvars = false;
3062 else
3063 LookForIvars = (Lookup.isSingleResult() &&
3065 ObjCInterfaceDecl *IFace = nullptr;
3066 if (LookForIvars) {
3067 IFace = CurMethod->getClassInterface();
3068 ObjCInterfaceDecl *ClassDeclared;
3069 ObjCIvarDecl *IV = nullptr;
3070 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
3071 // Diagnose using an ivar in a class method.
3072 if (IsClassMethod) {
3073 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
3074 return DeclResult(true);
3075 }
3076
3077 // Diagnose the use of an ivar outside of the declaring class.
3079 !declaresSameEntity(ClassDeclared, IFace) &&
3080 !getLangOpts().DebuggerSupport)
3081 Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
3082
3083 // Success.
3084 return IV;
3085 }
3086 } else if (CurMethod->isInstanceMethod()) {
3087 // We should warn if a local variable hides an ivar.
3088 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
3089 ObjCInterfaceDecl *ClassDeclared;
3090 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
3091 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
3092 declaresSameEntity(IFace, ClassDeclared))
3093 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
3094 }
3095 }
3096 } else if (Lookup.isSingleResult() &&
3098 // If accessing a stand-alone ivar in a class method, this is an error.
3099 if (const ObjCIvarDecl *IV =
3100 dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl())) {
3101 Diag(Loc, diag::err_ivar_use_in_class_method) << IV->getDeclName();
3102 return DeclResult(true);
3103 }
3104 }
3105
3106 // Didn't encounter an error, didn't find an ivar.
3107 return DeclResult(false);
3108}
3109
3111 ObjCIvarDecl *IV) {
3112 ObjCMethodDecl *CurMethod = getCurMethodDecl();
3113 assert(CurMethod && CurMethod->isInstanceMethod() &&
3114 "should not reference ivar from this context");
3115
3116 ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
3117 assert(IFace && "should not reference ivar from this context");
3118
3119 // If we're referencing an invalid decl, just return this as a silent
3120 // error node. The error diagnostic was already emitted on the decl.
3121 if (IV->isInvalidDecl())
3122 return ExprError();
3123
3124 // Check if referencing a field with __attribute__((deprecated)).
3125 if (DiagnoseUseOfDecl(IV, Loc))
3126 return ExprError();
3127
3128 // FIXME: This should use a new expr for a direct reference, don't
3129 // turn this into Self->ivar, just return a BareIVarExpr or something.
3130 IdentifierInfo &II = Context.Idents.get("self");
3131 UnqualifiedId SelfName;
3132 SelfName.setImplicitSelfParam(&II);
3133 CXXScopeSpec SelfScopeSpec;
3134 SourceLocation TemplateKWLoc;
3135 ExprResult SelfExpr =
3136 ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc, SelfName,
3137 /*HasTrailingLParen=*/false,
3138 /*IsAddressOfOperand=*/false);
3139 if (SelfExpr.isInvalid())
3140 return ExprError();
3141
3142 SelfExpr = DefaultLvalueConversion(SelfExpr.get());
3143 if (SelfExpr.isInvalid())
3144 return ExprError();
3145
3146 MarkAnyDeclReferenced(Loc, IV, true);
3147
3148 ObjCMethodFamily MF = CurMethod->getMethodFamily();
3149 if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
3150 !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
3151 Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
3152
3154 ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
3155 IV->getLocation(), SelfExpr.get(), true, true);
3156
3158 if (!isUnevaluatedContext() &&
3159 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
3161 }
3162 if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
3163 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
3164 ImplicitlyRetainedSelfLocs.push_back({Loc, BD});
3165
3166 return Result;
3167}
3168
3169/// The parser has read a name in, and Sema has detected that we're currently
3170/// inside an ObjC method. Perform some additional checks and determine if we
3171/// should form a reference to an ivar. If so, build an expression referencing
3172/// that ivar.
3175 IdentifierInfo *II, bool AllowBuiltinCreation) {
3176 // FIXME: Integrate this lookup step into LookupParsedName.
3177 DeclResult Ivar = LookupIvarInObjCMethod(Lookup, S, II);
3178 if (Ivar.isInvalid())
3179 return ExprError();
3180 if (Ivar.isUsable())
3181 return BuildIvarRefExpr(S, Lookup.getNameLoc(),
3182 cast<ObjCIvarDecl>(Ivar.get()));
3183
3184 if (Lookup.empty() && II && AllowBuiltinCreation)
3185 LookupBuiltin(Lookup);
3186
3187 // Sentinel value saying that we didn't do anything special.
3188 return ExprResult(false);
3189}
3190
3191/// Cast a base object to a member's actual type.
3192///
3193/// There are two relevant checks:
3194///
3195/// C++ [class.access.base]p7:
3196///
3197/// If a class member access operator [...] is used to access a non-static
3198/// data member or non-static member function, the reference is ill-formed if
3199/// the left operand [...] cannot be implicitly converted to a pointer to the
3200/// naming class of the right operand.
3201///
3202/// C++ [expr.ref]p7:
3203///
3204/// If E2 is a non-static data member or a non-static member function, the
3205/// program is ill-formed if the class of which E2 is directly a member is an
3206/// ambiguous base (11.8) of the naming class (11.9.3) of E2.
3207///
3208/// Note that the latter check does not consider access; the access of the
3209/// "real" base class is checked as appropriate when checking the access of the
3210/// member name.
3213 NestedNameSpecifier *Qualifier,
3214 NamedDecl *FoundDecl,
3215 NamedDecl *Member) {
3216 const auto *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
3217 if (!RD)
3218 return From;
3219
3220 QualType DestRecordType;
3221 QualType DestType;
3222 QualType FromRecordType;
3223 QualType FromType = From->getType();
3224 bool PointerConversions = false;
3225 if (isa<FieldDecl>(Member)) {
3226 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
3227 auto FromPtrType = FromType->getAs<PointerType>();
3228 DestRecordType = Context.getAddrSpaceQualType(
3229 DestRecordType, FromPtrType
3230 ? FromType->getPointeeType().getAddressSpace()
3231 : FromType.getAddressSpace());
3232
3233 if (FromPtrType) {
3234 DestType = Context.getPointerType(DestRecordType);
3235 FromRecordType = FromPtrType->getPointeeType();
3236 PointerConversions = true;
3237 } else {
3238 DestType = DestRecordType;
3239 FromRecordType = FromType;
3240 }
3241 } else if (const auto *Method = dyn_cast<CXXMethodDecl>(Member)) {
3242 if (!Method->isImplicitObjectMemberFunction())
3243 return From;
3244
3245 DestType = Method->getThisType().getNonReferenceType();
3246 DestRecordType = Method->getFunctionObjectParameterType();
3247
3248 if (FromType->getAs<PointerType>()) {
3249 FromRecordType = FromType->getPointeeType();
3250 PointerConversions = true;
3251 } else {
3252 FromRecordType = FromType;
3253 DestType = DestRecordType;
3254 }
3255
3256 LangAS FromAS = FromRecordType.getAddressSpace();
3257 LangAS DestAS = DestRecordType.getAddressSpace();
3258 if (FromAS != DestAS) {
3259 QualType FromRecordTypeWithoutAS =
3260 Context.removeAddrSpaceQualType(FromRecordType);
3261 QualType FromTypeWithDestAS =
3262 Context.getAddrSpaceQualType(FromRecordTypeWithoutAS, DestAS);
3263 if (PointerConversions)
3264 FromTypeWithDestAS = Context.getPointerType(FromTypeWithDestAS);
3265 From = ImpCastExprToType(From, FromTypeWithDestAS,
3266 CK_AddressSpaceConversion, From->getValueKind())
3267 .get();
3268 }
3269 } else {
3270 // No conversion necessary.
3271 return From;
3272 }
3273
3274 if (DestType->isDependentType() || FromType->isDependentType())
3275 return From;
3276
3277 // If the unqualified types are the same, no conversion is necessary.
3278 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3279 return From;
3280
3281 SourceRange FromRange = From->getSourceRange();
3282 SourceLocation FromLoc = FromRange.getBegin();
3283
3284 ExprValueKind VK = From->getValueKind();
3285
3286 // C++ [class.member.lookup]p8:
3287 // [...] Ambiguities can often be resolved by qualifying a name with its
3288 // class name.
3289 //
3290 // If the member was a qualified name and the qualified referred to a
3291 // specific base subobject type, we'll cast to that intermediate type
3292 // first and then to the object in which the member is declared. That allows
3293 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3294 //
3295 // class Base { public: int x; };
3296 // class Derived1 : public Base { };
3297 // class Derived2 : public Base { };
3298 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3299 //
3300 // void VeryDerived::f() {
3301 // x = 17; // error: ambiguous base subobjects
3302 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3303 // }
3304 if (Qualifier && Qualifier->getAsType()) {
3305 QualType QType = QualType(Qualifier->getAsType(), 0);
3306 assert(QType->isRecordType() && "lookup done with non-record type");
3307
3308 QualType QRecordType = QualType(QType->castAs<RecordType>(), 0);
3309
3310 // In C++98, the qualifier type doesn't actually have to be a base
3311 // type of the object type, in which case we just ignore it.
3312 // Otherwise build the appropriate casts.
3313 if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
3314 CXXCastPath BasePath;
3315 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
3316 FromLoc, FromRange, &BasePath))
3317 return ExprError();
3318
3319 if (PointerConversions)
3320 QType = Context.getPointerType(QType);
3321 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
3322 VK, &BasePath).get();
3323
3324 FromType = QType;
3325 FromRecordType = QRecordType;
3326
3327 // If the qualifier type was the same as the destination type,
3328 // we're done.
3329 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
3330 return From;
3331 }
3332 }
3333
3334 CXXCastPath BasePath;
3335 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
3336 FromLoc, FromRange, &BasePath,
3337 /*IgnoreAccess=*/true))
3338 return ExprError();
3339
3340 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
3341 VK, &BasePath);
3342}
3343
3345 const LookupResult &R,
3346 bool HasTrailingLParen) {
3347 // Only when used directly as the postfix-expression of a call.
3348 if (!HasTrailingLParen)
3349 return false;
3350
3351 // Never if a scope specifier was provided.
3352 if (SS.isSet())
3353 return false;
3354
3355 // Only in C++ or ObjC++.
3356 if (!getLangOpts().CPlusPlus)
3357 return false;
3358
3359 // Turn off ADL when we find certain kinds of declarations during
3360 // normal lookup:
3361 for (const NamedDecl *D : R) {
3362 // C++0x [basic.lookup.argdep]p3:
3363 // -- a declaration of a class member
3364 // Since using decls preserve this property, we check this on the
3365 // original decl.
3366 if (D->isCXXClassMember())
3367 return false;
3368
3369 // C++0x [basic.lookup.argdep]p3:
3370 // -- a block-scope function declaration that is not a
3371 // using-declaration
3372 // NOTE: we also trigger this for function templates (in fact, we
3373 // don't check the decl type at all, since all other decl types
3374 // turn off ADL anyway).
3375 if (isa<UsingShadowDecl>(D))
3376 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3377 else if (D->getLexicalDeclContext()->isFunctionOrMethod())
3378 return false;
3379
3380 // C++0x [basic.lookup.argdep]p3:
3381 // -- a declaration that is neither a function or a function
3382 // template
3383 // And also for builtin functions.
3384 if (const auto *FDecl = dyn_cast<FunctionDecl>(D)) {
3385 // But also builtin functions.
3386 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3387 return false;
3388 } else if (!isa<FunctionTemplateDecl>(D))
3389 return false;
3390 }
3391
3392 return true;
3393}
3394
3395
3396/// Diagnoses obvious problems with the use of the given declaration
3397/// as an expression. This is only actually called for lookups that
3398/// were not overloaded, and it doesn't promise that the declaration
3399/// will in fact be used.
3401 bool AcceptInvalid) {
3402 if (D->isInvalidDecl() && !AcceptInvalid)
3403 return true;
3404
3405 if (isa<TypedefNameDecl>(D)) {
3406 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3407 return true;
3408 }
3409
3410 if (isa<ObjCInterfaceDecl>(D)) {
3411 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3412 return true;
3413 }
3414
3415 if (isa<NamespaceDecl>(D)) {
3416 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
3417 return true;
3418 }
3419
3420 return false;
3421}
3422
3423// Certain multiversion types should be treated as overloaded even when there is
3424// only one result.
3426 assert(R.isSingleResult() && "Expected only a single result");
3427 const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
3428 return FD &&
3429 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3430}
3431
3433 LookupResult &R, bool NeedsADL,
3434 bool AcceptInvalidDecl) {
3435 // If this is a single, fully-resolved result and we don't need ADL,
3436 // just build an ordinary singleton decl ref.
3437 if (!NeedsADL && R.isSingleResult() &&
3441 R.getRepresentativeDecl(), nullptr,
3442 AcceptInvalidDecl);
3443
3444 // We only need to check the declaration if there's exactly one
3445 // result, because in the overloaded case the results can only be
3446 // functions and function templates.
3448 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl(),
3449 AcceptInvalidDecl))
3450 return ExprError();
3451
3452 // Otherwise, just build an unresolved lookup expression. Suppress
3453 // any lookup-related diagnostics; we'll hash these out later, when
3454 // we've picked a target.
3456
3459 R.getLookupNameInfo(), NeedsADL, R.begin(), R.end(),
3460 /*KnownDependent=*/false);
3461
3462 return ULE;
3463}
3464
3466 SourceLocation loc,
3467 ValueDecl *var);
3468
3469/// Complete semantic analysis for a reference to the given declaration.
3471 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
3472 NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
3473 bool AcceptInvalidDecl) {
3474 assert(D && "Cannot refer to a NULL declaration");
3475 assert(!isa<FunctionTemplateDecl>(D) &&
3476 "Cannot refer unambiguously to a function template");
3477
3478 SourceLocation Loc = NameInfo.getLoc();
3479 if (CheckDeclInExpr(*this, Loc, D, AcceptInvalidDecl)) {
3480 // Recovery from invalid cases (e.g. D is an invalid Decl).
3481 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3482 // diagnostics, as invalid decls use int as a fallback type.
3483 return CreateRecoveryExpr(NameInfo.getBeginLoc(), NameInfo.getEndLoc(), {});
3484 }
3485
3486 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
3487 // Specifically diagnose references to class templates that are missing
3488 // a template argument list.
3490 return ExprError();
3491 }
3492
3493 // Make sure that we're referring to a value.
3494 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(D)) {
3495 Diag(Loc, diag::err_ref_non_value) << D << SS.getRange();
3496 Diag(D->getLocation(), diag::note_declared_at);
3497 return ExprError();
3498 }
3499
3500 // Check whether this declaration can be used. Note that we suppress
3501 // this check when we're going to perform argument-dependent lookup
3502 // on this function name, because this might not be the function
3503 // that overload resolution actually selects.
3504 if (DiagnoseUseOfDecl(D, Loc))
3505 return ExprError();
3506
3507 auto *VD = cast<ValueDecl>(D);
3508
3509 // Only create DeclRefExpr's for valid Decl's.
3510 if (VD->isInvalidDecl() && !AcceptInvalidDecl)
3511 return ExprError();
3512
3513 // Handle members of anonymous structs and unions. If we got here,
3514 // and the reference is to a class member indirect field, then this
3515 // must be the subject of a pointer-to-member expression.
3516 if (auto *IndirectField = dyn_cast<IndirectFieldDecl>(VD);
3517 IndirectField && !IndirectField->isCXXClassMember())
3519 IndirectField);
3520
3521 QualType type = VD->getType();
3522 if (type.isNull())
3523 return ExprError();
3524 ExprValueKind valueKind = VK_PRValue;
3525
3526 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3527 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3528 // is expanded by some outer '...' in the context of the use.
3529 type = type.getNonPackExpansionType();
3530
3531 switch (D->getKind()) {
3532 // Ignore all the non-ValueDecl kinds.
3533#define ABSTRACT_DECL(kind)
3534#define VALUE(type, base)
3535#define DECL(type, base) case Decl::type:
3536#include "clang/AST/DeclNodes.inc"
3537 llvm_unreachable("invalid value decl kind");
3538
3539 // These shouldn't make it here.
3540 case Decl::ObjCAtDefsField:
3541 llvm_unreachable("forming non-member reference to ivar?");
3542
3543 // Enum constants are always r-values and never references.
3544 // Unresolved using declarations are dependent.
3545 case Decl::EnumConstant:
3546 case Decl::UnresolvedUsingValue:
3547 case Decl::OMPDeclareReduction:
3548 case Decl::OMPDeclareMapper:
3549 valueKind = VK_PRValue;
3550 break;
3551
3552 // Fields and indirect fields that got here must be for
3553 // pointer-to-member expressions; we just call them l-values for
3554 // internal consistency, because this subexpression doesn't really
3555 // exist in the high-level semantics.
3556 case Decl::Field:
3557 case Decl::IndirectField:
3558 case Decl::ObjCIvar:
3559 assert((getLangOpts().CPlusPlus || isBoundsAttrContext()) &&
3560 "building reference to field in C?");
3561
3562 // These can't have reference type in well-formed programs, but
3563 // for internal consistency we do this anyway.
3564 type = type.getNonReferenceType();
3565 valueKind = VK_LValue;
3566 break;
3567
3568 // Non-type template parameters are either l-values or r-values
3569 // depending on the type.
3570 case Decl::NonTypeTemplateParm: {
3571 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3572 type = reftype->getPointeeType();
3573 valueKind = VK_LValue; // even if the parameter is an r-value reference
3574 break;
3575 }
3576
3577 // [expr.prim.id.unqual]p2:
3578 // If the entity is a template parameter object for a template
3579 // parameter of type T, the type of the expression is const T.
3580 // [...] The expression is an lvalue if the entity is a [...] template
3581 // parameter object.
3582 if (type->isRecordType()) {
3583 type = type.getUnqualifiedType().withConst();
3584 valueKind = VK_LValue;
3585 break;
3586 }
3587
3588 // For non-references, we need to strip qualifiers just in case
3589 // the template parameter was declared as 'const int' or whatever.
3590 valueKind = VK_PRValue;
3591 type = type.getUnqualifiedType();
3592 break;
3593 }
3594
3595 case Decl::Var:
3596 case Decl::VarTemplateSpecialization:
3597 case Decl::VarTemplatePartialSpecialization:
3598 case Decl::Decomposition:
3599 case Decl::OMPCapturedExpr:
3600 // In C, "extern void blah;" is valid and is an r-value.
3601 if (!getLangOpts().CPlusPlus && !type.hasQualifiers() &&
3602 type->isVoidType()) {
3603 valueKind = VK_PRValue;
3604 break;
3605 }
3606 [[fallthrough]];
3607
3608 case Decl::ImplicitParam:
3609 case Decl::ParmVar: {
3610 // These are always l-values.
3611 valueKind = VK_LValue;
3612 type = type.getNonReferenceType();
3613
3614 // FIXME: Does the addition of const really only apply in
3615 // potentially-evaluated contexts? Since the variable isn't actually
3616 // captured in an unevaluated context, it seems that the answer is no.
3617 if (!isUnevaluatedContext()) {
3618 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3619 if (!CapturedType.isNull())
3620 type = CapturedType;
3621 }
3622
3623 break;
3624 }
3625
3626 case Decl::Binding:
3627 // These are always lvalues.
3628 valueKind = VK_LValue;
3629 type = type.getNonReferenceType();
3630 break;
3631
3632 case Decl::Function: {
3633 if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3636 valueKind = VK_PRValue;
3637 break;
3638 }
3639 }
3640
3641 const FunctionType *fty = type->castAs<FunctionType>();
3642
3643 // If we're referring to a function with an __unknown_anytype
3644 // result type, make the entire expression __unknown_anytype.
3645 if (fty->getReturnType() == Context.UnknownAnyTy) {
3647 valueKind = VK_PRValue;
3648 break;
3649 }
3650
3651 // Functions are l-values in C++.
3652 if (getLangOpts().CPlusPlus) {
3653 valueKind = VK_LValue;
3654 break;
3655 }
3656
3657 // C99 DR 316 says that, if a function type comes from a
3658 // function definition (without a prototype), that type is only
3659 // used for checking compatibility. Therefore, when referencing
3660 // the function, we pretend that we don't have the full function
3661 // type.
3662 if (!cast<FunctionDecl>(VD)->hasPrototype() && isa<FunctionProtoType>(fty))
3664 fty->getExtInfo());
3665
3666 // Functions are r-values in C.
3667 valueKind = VK_PRValue;
3668 break;
3669 }
3670
3671 case Decl::CXXDeductionGuide:
3672 llvm_unreachable("building reference to deduction guide");
3673
3674 case Decl::MSProperty:
3675 case Decl::MSGuid:
3676 case Decl::TemplateParamObject:
3677 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3678 // capture in OpenMP, or duplicated between host and device?
3679 valueKind = VK_LValue;
3680 break;
3681
3682 case Decl::UnnamedGlobalConstant:
3683 valueKind = VK_LValue;
3684 break;
3685
3686 case Decl::CXXMethod:
3687 // If we're referring to a method with an __unknown_anytype
3688 // result type, make the entire expression __unknown_anytype.
3689 // This should only be possible with a type written directly.
3690 if (const FunctionProtoType *proto =
3691 dyn_cast<FunctionProtoType>(VD->getType()))
3692 if (proto->getReturnType() == Context.UnknownAnyTy) {
3694 valueKind = VK_PRValue;
3695 break;
3696 }
3697
3698 // C++ methods are l-values if static, r-values if non-static.
3699 if (cast<CXXMethodDecl>(VD)->isStatic()) {
3700 valueKind = VK_LValue;
3701 break;
3702 }
3703 [[fallthrough]];
3704
3705 case Decl::CXXConversion:
3706 case Decl::CXXDestructor:
3707 case Decl::CXXConstructor:
3708 valueKind = VK_PRValue;
3709 break;
3710 }
3711
3712 auto *E =
3713 BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3714 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs);
3715 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3716 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3717 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3718 // diagnostics).
3719 if (VD->isInvalidDecl() && E)
3720 return CreateRecoveryExpr(E->getBeginLoc(), E->getEndLoc(), {E});
3721 return E;
3722}
3723
3724static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3726 Target.resize(CharByteWidth * (Source.size() + 1));
3727 char *ResultPtr = &Target[0];
3728 const llvm::UTF8 *ErrorPtr;
3729 bool success =
3730 llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3731 (void)success;
3732 assert(success);
3733 Target.resize(ResultPtr - &Target[0]);
3734}
3735
3738 Decl *currentDecl = getPredefinedExprDecl(CurContext);
3739 if (!currentDecl) {
3740 Diag(Loc, diag::ext_predef_outside_function);
3741 currentDecl = Context.getTranslationUnitDecl();
3742 }
3743
3744 QualType ResTy;
3745 StringLiteral *SL = nullptr;
3746 if (cast<DeclContext>(currentDecl)->isDependentContext())
3747 ResTy = Context.DependentTy;
3748 else {
3749 // Pre-defined identifiers are of type char[x], where x is the length of
3750 // the string.
3751 bool ForceElaboratedPrinting =
3752 IK == PredefinedIdentKind::Function && getLangOpts().MSVCCompat;
3753 auto Str =
3754 PredefinedExpr::ComputeName(IK, currentDecl, ForceElaboratedPrinting);
3755 unsigned Length = Str.length();
3756
3757 llvm::APInt LengthI(32, Length + 1);
3760 ResTy =
3762 SmallString<32> RawChars;
3764 Str, RawChars);
3765 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3767 /*IndexTypeQuals*/ 0);
3769 /*Pascal*/ false, ResTy, Loc);
3770 } else {
3772 ResTy = Context.getConstantArrayType(ResTy, LengthI, nullptr,
3774 /*IndexTypeQuals*/ 0);
3776 /*Pascal*/ false, ResTy, Loc);
3777 }
3778 }
3779
3780 return PredefinedExpr::Create(Context, Loc, ResTy, IK, LangOpts.MicrosoftExt,
3781 SL);
3782}
3783
3785 return BuildPredefinedExpr(Loc, getPredefinedExprKind(Kind));
3786}
3787
3789 SmallString<16> CharBuffer;
3790 bool Invalid = false;
3791 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3792 if (Invalid)
3793 return ExprError();
3794
3795 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3796 PP, Tok.getKind());
3797 if (Literal.hadError())
3798 return ExprError();
3799
3800 QualType Ty;
3801 if (Literal.isWide())
3802 Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3803 else if (Literal.isUTF8() && getLangOpts().C23)
3804 Ty = Context.UnsignedCharTy; // u8'x' -> unsigned char in C23
3805 else if (Literal.isUTF8() && getLangOpts().Char8)
3806 Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3807 else if (Literal.isUTF16())
3808 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3809 else if (Literal.isUTF32())
3810 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3811 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3812 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
3813 else
3814 Ty = Context.CharTy; // 'x' -> char in C++;
3815 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3816
3818 if (Literal.isWide())
3820 else if (Literal.isUTF16())
3822 else if (Literal.isUTF32())
3824 else if (Literal.isUTF8())
3826
3827 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3828 Tok.getLocation());
3829
3830 if (Literal.getUDSuffix().empty())
3831 return Lit;
3832
3833 // We're building a user-defined literal.
3834 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3835 SourceLocation UDSuffixLoc =
3836 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3837
3838 // Make sure we're allowed user-defined literals here.
3839 if (!UDLScope)
3840 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3841
3842 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3843 // operator "" X (ch)
3844 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3845 Lit, Tok.getLocation());
3846}
3847
3849 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3850 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3851 Context.IntTy, Loc);
3852}
3853
3855 QualType Ty, SourceLocation Loc) {
3856 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3857
3858 using llvm::APFloat;
3859 APFloat Val(Format);
3860
3861 APFloat::opStatus result = Literal.GetFloatValue(Val);
3862
3863 // Overflow is always an error, but underflow is only an error if
3864 // we underflowed to zero (APFloat reports denormals as underflow).
3865 if ((result & APFloat::opOverflow) ||
3866 ((result & APFloat::opUnderflow) && Val.isZero())) {
3867 unsigned diagnostic;
3868 SmallString<20> buffer;
3869 if (result & APFloat::opOverflow) {
3870 diagnostic = diag::warn_float_overflow;
3871 APFloat::getLargest(Format).toString(buffer);
3872 } else {
3873 diagnostic = diag::warn_float_underflow;
3874 APFloat::getSmallest(Format).toString(buffer);
3875 }
3876
3877 S.Diag(Loc, diagnostic)
3878 << Ty
3879 << StringRef(buffer.data(), buffer.size());
3880 }
3881
3882 bool isExact = (result == APFloat::opOK);
3883 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3884}
3885
3886bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero) {
3887 assert(E && "Invalid expression");
3888
3889 if (E->isValueDependent())
3890 return false;
3891
3892 QualType QT = E->getType();
3893 if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3894 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3895 return true;
3896 }
3897
3898 llvm::APSInt ValueAPS;
3900
3901 if (R.isInvalid())
3902 return true;
3903
3904 // GCC allows the value of unroll count to be 0.
3905 // https://gcc.gnu.org/onlinedocs/gcc/Loop-Specific-Pragmas.html says
3906 // "The values of 0 and 1 block any unrolling of the loop."
3907 // The values doesn't have to be strictly positive in '#pragma GCC unroll' and
3908 // '#pragma unroll' cases.
3909 bool ValueIsPositive =
3910 AllowZero ? ValueAPS.isNonNegative() : ValueAPS.isStrictlyPositive();
3911 if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3912 Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3913 << toString(ValueAPS, 10) << ValueIsPositive;
3914 return true;
3915 }
3916
3917 return false;
3918}
3919
3921 // Fast path for a single digit (which is quite common). A single digit
3922 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3923 if (Tok.getLength() == 1) {
3924 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3925 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3926 }
3927
3928 SmallString<128> SpellingBuffer;
3929 // NumericLiteralParser wants to overread by one character. Add padding to
3930 // the buffer in case the token is copied to the buffer. If getSpelling()
3931 // returns a StringRef to the memory buffer, it should have a null char at
3932 // the EOF, so it is also safe.
3933 SpellingBuffer.resize(Tok.getLength() + 1);
3934
3935 // Get the spelling of the token, which eliminates trigraphs, etc.
3936 bool Invalid = false;
3937 StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3938 if (Invalid)
3939 return ExprError();
3940
3941 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3944 if (Literal.hadError)
3945 return ExprError();
3946
3947 if (Literal.hasUDSuffix()) {
3948 // We're building a user-defined literal.
3949 const IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3950 SourceLocation UDSuffixLoc =
3951 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3952
3953 // Make sure we're allowed user-defined literals here.
3954 if (!UDLScope)
3955 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3956
3957 QualType CookedTy;
3958 if (Literal.isFloatingLiteral()) {
3959 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3960 // long double, the literal is treated as a call of the form
3961 // operator "" X (f L)
3962 CookedTy = Context.LongDoubleTy;
3963 } else {
3964 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3965 // unsigned long long, the literal is treated as a call of the form
3966 // operator "" X (n ULL)
3967 CookedTy = Context.UnsignedLongLongTy;
3968 }
3969
3970 DeclarationName OpName =
3972 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3973 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3974
3975 SourceLocation TokLoc = Tok.getLocation();
3976
3977 // Perform literal operator lookup to determine if we're building a raw
3978 // literal or a cooked one.
3979 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3980 switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3981 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3982 /*AllowStringTemplatePack*/ false,
3983 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3985 // Lookup failure for imaginary constants isn't fatal, there's still the
3986 // GNU extension producing _Complex types.
3987 break;
3988 case LOLR_Error:
3989 return ExprError();
3990 case LOLR_Cooked: {
3991 Expr *Lit;
3992 if (Literal.isFloatingLiteral()) {
3993 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3994 } else {
3995 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3996 if (Literal.GetIntegerValue(ResultVal))
3997 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3998 << /* Unsigned */ 1;
3999 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
4000 Tok.getLocation());
4001 }
4002 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
4003 }
4004
4005 case LOLR_Raw: {
4006 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
4007 // literal is treated as a call of the form
4008 // operator "" X ("n")
4009 unsigned Length = Literal.getUDSuffixOffset();
4012 llvm::APInt(32, Length + 1), nullptr, ArraySizeModifier::Normal, 0);
4013 Expr *Lit =
4014 StringLiteral::Create(Context, StringRef(TokSpelling.data(), Length),
4016 /*Pascal*/ false, StrTy, &TokLoc, 1);
4017 return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
4018 }
4019
4020 case LOLR_Template: {
4021 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
4022 // template), L is treated as a call fo the form
4023 // operator "" X <'c1', 'c2', ... 'ck'>()
4024 // where n is the source character sequence c1 c2 ... ck.
4025 TemplateArgumentListInfo ExplicitArgs;
4026 unsigned CharBits = Context.getIntWidth(Context.CharTy);
4027 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
4028 llvm::APSInt Value(CharBits, CharIsUnsigned);
4029 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
4030 Value = TokSpelling[I];
4033 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
4034 }
4035 return BuildLiteralOperatorCall(R, OpNameInfo, std::nullopt, TokLoc,
4036 &ExplicitArgs);
4037 }
4039 llvm_unreachable("unexpected literal operator lookup result");
4040 }
4041 }
4042
4043 Expr *Res;
4044
4045 if (Literal.isFixedPointLiteral()) {
4046 QualType Ty;
4047
4048 if (Literal.isAccum) {
4049 if (Literal.isHalf) {
4050 Ty = Context.ShortAccumTy;
4051 } else if (Literal.isLong) {
4052 Ty = Context.LongAccumTy;
4053 } else {
4054 Ty = Context.AccumTy;
4055 }
4056 } else if (Literal.isFract) {
4057 if (Literal.isHalf) {
4058 Ty = Context.ShortFractTy;
4059 } else if (Literal.isLong) {
4060 Ty = Context.LongFractTy;
4061 } else {
4062 Ty = Context.FractTy;
4063 }
4064 }
4065
4066 if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
4067
4068 bool isSigned = !Literal.isUnsigned;
4069 unsigned scale = Context.getFixedPointScale(Ty);
4070 unsigned bit_width = Context.getTypeInfo(Ty).Width;
4071
4072 llvm::APInt Val(bit_width, 0, isSigned);
4073 bool Overflowed = Literal.GetFixedPointValue(Val, scale);
4074 bool ValIsZero = Val.isZero() && !Overflowed;
4075
4076 auto MaxVal = Context.getFixedPointMax(Ty).getValue();
4077 if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
4078 // Clause 6.4.4 - The value of a constant shall be in the range of
4079 // representable values for its type, with exception for constants of a
4080 // fract type with a value of exactly 1; such a constant shall denote
4081 // the maximal value for the type.
4082 --Val;
4083 else if (Val.ugt(MaxVal) || Overflowed)
4084 Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
4085
4087 Tok.getLocation(), scale);
4088 } else if (Literal.isFloatingLiteral()) {
4089 QualType Ty;
4090 if (Literal.isHalf){
4091 if (getLangOpts().HLSL ||
4092 getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
4093 Ty = Context.HalfTy;
4094 else {
4095 Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
4096 return ExprError();
4097 }
4098 } else if (Literal.isFloat)
4099 Ty = Context.FloatTy;
4100 else if (Literal.isLong)
4102 else if (Literal.isFloat16)
4103 Ty = Context.Float16Ty;
4104 else if (Literal.isFloat128)
4105 Ty = Context.Float128Ty;
4106 else
4107 Ty = Context.DoubleTy;
4108
4109 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
4110
4111 if (Ty == Context.DoubleTy) {
4112 if (getLangOpts().SinglePrecisionConstants) {
4113 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4114 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4115 }
4116 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4117 "cl_khr_fp64", getLangOpts())) {
4118 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4119 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4121 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
4122 }
4123 }
4124 } else if (!Literal.isIntegerLiteral()) {
4125 return ExprError();
4126 } else {
4127 QualType Ty;
4128
4129 // 'z/uz' literals are a C++23 feature.
4130 if (Literal.isSizeT)
4133 ? diag::warn_cxx20_compat_size_t_suffix
4134 : diag::ext_cxx23_size_t_suffix
4135 : diag::err_cxx23_size_t_suffix);
4136
4137 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4138 // but we do not currently support the suffix in C++ mode because it's not
4139 // entirely clear whether WG21 will prefer this suffix to return a library
4140 // type such as std::bit_int instead of returning a _BitInt. '__wb/__uwb'
4141 // literals are a C++ extension.
4142 if (Literal.isBitInt)
4143 PP.Diag(Tok.getLocation(),
4144 getLangOpts().CPlusPlus ? diag::ext_cxx_bitint_suffix
4145 : getLangOpts().C23 ? diag::warn_c23_compat_bitint_suffix
4146 : diag::ext_c23_bitint_suffix);
4147
4148 // Get the value in the widest-possible width. What is "widest" depends on
4149 // whether the literal is a bit-precise integer or not. For a bit-precise
4150 // integer type, try to scan the source to determine how many bits are
4151 // needed to represent the value. This may seem a bit expensive, but trying
4152 // to get the integer value from an overly-wide APInt is *extremely*
4153 // expensive, so the naive approach of assuming
4154 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4155 unsigned BitsNeeded =
4156 Literal.isBitInt ? llvm::APInt::getSufficientBitsNeeded(
4157 Literal.getLiteralDigits(), Literal.getRadix())
4159 llvm::APInt ResultVal(BitsNeeded, 0);
4160
4161 if (Literal.GetIntegerValue(ResultVal)) {
4162 // If this value didn't fit into uintmax_t, error and force to ull.
4163 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4164 << /* Unsigned */ 1;
4166 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
4167 "long long is not intmax_t?");
4168 } else {
4169 // If this value fits into a ULL, try to figure out what else it fits into
4170 // according to the rules of C99 6.4.4.1p5.
4171
4172 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4173 // be an unsigned int.
4174 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
4175
4176 // Check from smallest to largest, picking the smallest type we can.
4177 unsigned Width = 0;
4178
4179 // Microsoft specific integer suffixes are explicitly sized.
4180 if (Literal.MicrosoftInteger) {
4181 if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
4182 Width = 8;
4183 Ty = Context.CharTy;
4184 } else {
4185 Width = Literal.MicrosoftInteger;
4186 Ty = Context.getIntTypeForBitwidth(Width,
4187 /*Signed=*/!Literal.isUnsigned);
4188 }
4189 }
4190
4191 // Bit-precise integer literals are automagically-sized based on the
4192 // width required by the literal.
4193 if (Literal.isBitInt) {
4194 // The signed version has one more bit for the sign value. There are no
4195 // zero-width bit-precise integers, even if the literal value is 0.
4196 Width = std::max(ResultVal.getActiveBits(), 1u) +
4197 (Literal.isUnsigned ? 0u : 1u);
4198
4199 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4200 // and reset the type to the largest supported width.
4201 unsigned int MaxBitIntWidth =
4203 if (Width > MaxBitIntWidth) {
4204 Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
4205 << Literal.isUnsigned;
4206 Width = MaxBitIntWidth;
4207 }
4208
4209 // Reset the result value to the smaller APInt and select the correct
4210 // type to be used. Note, we zext even for signed values because the
4211 // literal itself is always an unsigned value (a preceeding - is a
4212 // unary operator, not part of the literal).
4213 ResultVal = ResultVal.zextOrTrunc(Width);
4214 Ty = Context.getBitIntType(Literal.isUnsigned, Width);
4215 }
4216
4217 // Check C++23 size_t literals.
4218 if (Literal.isSizeT) {
4219 assert(!Literal.MicrosoftInteger &&
4220 "size_t literals can't be Microsoft literals");
4221 unsigned SizeTSize = Context.getTargetInfo().getTypeWidth(
4223
4224 // Does it fit in size_t?
4225 if (ResultVal.isIntN(SizeTSize)) {
4226 // Does it fit in ssize_t?
4227 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4229 else if (AllowUnsigned)
4230 Ty = Context.getSizeType();
4231 Width = SizeTSize;
4232 }
4233 }
4234
4235 if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong &&
4236 !Literal.isSizeT) {
4237 // Are int/unsigned possibilities?
4238 unsigned IntSize = Context.getTargetInfo().getIntWidth();
4239
4240 // Does it fit in a unsigned int?
4241 if (ResultVal.isIntN(IntSize)) {
4242 // Does it fit in a signed int?
4243 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
4244 Ty = Context.IntTy;
4245 else if (AllowUnsigned)
4247 Width = IntSize;
4248 }
4249 }
4250
4251 // Are long/unsigned long possibilities?
4252 if (Ty.isNull() && !Literal.isLongLong && !Literal.isSizeT) {
4253 unsigned LongSize = Context.getTargetInfo().getLongWidth();
4254
4255 // Does it fit in a unsigned long?
4256 if (ResultVal.isIntN(LongSize)) {
4257 // Does it fit in a signed long?
4258 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
4259 Ty = Context.LongTy;
4260 else if (AllowUnsigned)
4262 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4263 // is compatible.
4264 else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
4265 const unsigned LongLongSize =
4267 Diag(Tok.getLocation(),
4269 ? Literal.isLong
4270 ? diag::warn_old_implicitly_unsigned_long_cxx
4271 : /*C++98 UB*/ diag::
4272 ext_old_implicitly_unsigned_long_cxx
4273 : diag::warn_old_implicitly_unsigned_long)
4274 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
4275 : /*will be ill-formed*/ 1);
4277 }
4278 Width = LongSize;
4279 }
4280 }
4281
4282 // Check long long if needed.
4283 if (Ty.isNull() && !Literal.isSizeT) {
4284 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
4285
4286 // Does it fit in a unsigned long long?
4287 if (ResultVal.isIntN(LongLongSize)) {
4288 // Does it fit in a signed long long?
4289 // To be compatible with MSVC, hex integer literals ending with the
4290 // LL or i64 suffix are always signed in Microsoft mode.
4291 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
4292 (getLangOpts().MSVCCompat && Literal.isLongLong)))
4293 Ty = Context.LongLongTy;
4294 else if (AllowUnsigned)
4296 Width = LongLongSize;
4297
4298 // 'long long' is a C99 or C++11 feature, whether the literal
4299 // explicitly specified 'long long' or we needed the extra width.
4300 if (getLangOpts().CPlusPlus)
4301 Diag(Tok.getLocation(), getLangOpts().CPlusPlus11
4302 ? diag::warn_cxx98_compat_longlong
4303 : diag::ext_cxx11_longlong);
4304 else if (!getLangOpts().C99)
4305 Diag(Tok.getLocation(), diag::ext_c99_longlong);
4306 }
4307 }
4308
4309 // If we still couldn't decide a type, we either have 'size_t' literal
4310 // that is out of range, or a decimal literal that does not fit in a
4311 // signed long long and has no U suffix.
4312 if (Ty.isNull()) {
4313 if (Literal.isSizeT)
4314 Diag(Tok.getLocation(), diag::err_size_t_literal_too_large)
4315 << Literal.isUnsigned;
4316 else
4317 Diag(Tok.getLocation(),
4318 diag::ext_integer_literal_too_large_for_signed);
4321 }
4322
4323 if (ResultVal.getBitWidth() != Width)
4324 ResultVal = ResultVal.trunc(Width);
4325 }
4326 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
4327 }
4328
4329 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4330 if (Literal.isImaginary) {
4331 Res = new (Context) ImaginaryLiteral(Res,
4333
4334 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4335 }
4336 return Res;
4337}
4338
4340 assert(E && "ActOnParenExpr() missing expr");
4341 QualType ExprTy = E->getType();
4342 if (getLangOpts().ProtectParens && CurFPFeatures.getAllowFPReassociate() &&
4343 !E->isLValue() && ExprTy->hasFloatingRepresentation())
4344 return BuildBuiltinCallExpr(R, Builtin::BI__arithmetic_fence, E);
4345 return new (Context) ParenExpr(L, R, E);
4346}
4347
4349 SourceLocation Loc,
4350 SourceRange ArgRange) {
4351 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4352 // scalar or vector data type argument..."
4353 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4354 // type (C99 6.2.5p18) or void.
4355 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
4356 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
4357 << T << ArgRange;
4358 return true;
4359 }
4360
4361 assert((T->isVoidType() || !T->isIncompleteType()) &&
4362 "Scalar types should always be complete");
4363 return false;
4364}
4365
4367 SourceLocation Loc,
4368 SourceRange ArgRange) {
4369 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4370 if (!T->isVectorType() && !T->isSizelessVectorType())
4371 return S.Diag(Loc, diag::err_builtin_non_vector_type)
4372 << ""
4373 << "__builtin_vectorelements" << T << ArgRange;
4374
4375 return false;
4376}
4377
4379 SourceLocation Loc,
4380 SourceRange ArgRange,
4381 UnaryExprOrTypeTrait TraitKind) {
4382 // Invalid types must be hard errors for SFINAE in C++.
4383 if (S.LangOpts.CPlusPlus)
4384 return true;
4385
4386 // C99 6.5.3.4p1:
4387 if (T->isFunctionType() &&
4388 (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
4389 TraitKind == UETT_PreferredAlignOf)) {
4390 // sizeof(function)/alignof(function) is allowed as an extension.
4391 S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
4392 << getTraitSpelling(TraitKind) << ArgRange;
4393 return false;
4394 }
4395
4396 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4397 // this is an error (OpenCL v1.1 s6.3.k)
4398 if (T->isVoidType()) {
4399 unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
4400 : diag::ext_sizeof_alignof_void_type;
4401 S.Diag(Loc, DiagID) << getTraitSpelling(TraitKind) << ArgRange;
4402 return false;
4403 }
4404
4405 return true;
4406}
4407
4409 SourceLocation Loc,
4410 SourceRange ArgRange,
4411 UnaryExprOrTypeTrait TraitKind) {
4412 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4413 // runtime doesn't allow it.
4415 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
4416 << T << (TraitKind == UETT_SizeOf)
4417 << ArgRange;
4418 return true;
4419 }
4420
4421 return false;
4422}
4423
4424/// Check whether E is a pointer from a decayed array type (the decayed
4425/// pointer type is equal to T) and emit a warning if it is.
4427 const Expr *E) {
4428 // Don't warn if the operation changed the type.
4429 if (T != E->getType())
4430 return;
4431
4432 // Now look for array decays.
4433 const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
4434 if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
4435 return;
4436
4437 S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
4438 << ICE->getType()
4439 << ICE->getSubExpr()->getType();
4440}
4441
4442/// Check the constraints on expression operands to unary type expression
4443/// and type traits.
4444///
4445/// Completes any types necessary and validates the constraints on the operand
4446/// expression. The logic mostly mirrors the type-based overload, but may modify
4447/// the expression as it completes the type for that expression through template
4448/// instantiation, etc.
4450 UnaryExprOrTypeTrait ExprKind) {
4451 QualType ExprTy = E->getType();
4452 assert(!ExprTy->isReferenceType());
4453
4454 bool IsUnevaluatedOperand =
4455 (ExprKind == UETT_SizeOf || ExprKind == UETT_DataSizeOf ||
4456 ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4457 ExprKind == UETT_VecStep);
4458 if (IsUnevaluatedOperand) {
4460 if (Result.isInvalid())
4461 return true;
4462 E = Result.get();
4463 }
4464
4465 // The operand for sizeof and alignof is in an unevaluated expression context,
4466 // so side effects could result in unintended consequences.
4467 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4468 // used to build SFINAE gadgets.
4469 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4470 if (IsUnevaluatedOperand && !inTemplateInstantiation() &&
4472 !E->getType()->isVariableArrayType() &&
4473 E->HasSideEffects(Context, false))
4474 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
4475
4476 if (ExprKind == UETT_VecStep)
4477 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
4478 E->getSourceRange());
4479
4480 if (ExprKind == UETT_VectorElements)
4481 return CheckVectorElementsTraitOperandType(*this, ExprTy, E->getExprLoc(),
4482 E->getSourceRange());
4483
4484 // Explicitly list some types as extensions.
4485 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
4486 E->getSourceRange(), ExprKind))
4487 return false;
4488
4489 // WebAssembly tables are always illegal operands to unary expressions and
4490 // type traits.
4491 if (Context.getTargetInfo().getTriple().isWasm() &&
4493 Diag(E->getExprLoc(), diag::err_wasm_table_invalid_uett_operand)
4494 << getTraitSpelling(ExprKind);
4495 return true;
4496 }
4497
4498 // 'alignof' applied to an expression only requires the base element type of
4499 // the expression to be complete. 'sizeof' requires the expression's type to
4500 // be complete (and will attempt to complete it if it's an array of unknown
4501 // bound).
4502 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4505 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4506 getTraitSpelling(ExprKind), E->getSourceRange()))
4507 return true;
4508 } else {
4510 E, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4511 getTraitSpelling(ExprKind), E->getSourceRange()))
4512 return true;
4513 }
4514
4515 // Completing the expression's type may have changed it.
4516 ExprTy = E->getType();
4517 assert(!ExprTy->isReferenceType());
4518
4519 if (ExprTy->isFunctionType()) {
4520 Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
4521 << getTraitSpelling(ExprKind) << E->getSourceRange();
4522 return true;
4523 }
4524
4525 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
4526 E->getSourceRange(), ExprKind))
4527 return true;
4528
4529 if (ExprKind == UETT_SizeOf) {
4530 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4531 if (const auto *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
4532 QualType OType = PVD->getOriginalType();
4533 QualType Type = PVD->getType();
4534 if (Type->isPointerType() && OType->isArrayType()) {
4535 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
4536 << Type << OType;
4537 Diag(PVD->getLocation(), diag::note_declared_at);
4538 }
4539 }
4540 }
4541
4542 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4543 // decays into a pointer and returns an unintended result. This is most
4544 // likely a typo for "sizeof(array) op x".
4545 if (const auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
4546 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4547 BO->getLHS());
4548 warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
4549 BO->getRHS());
4550 }
4551 }
4552
4553 return false;
4554}
4555
4556static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
4557 // Cannot know anything else if the expression is dependent.
4558 if (E->isTypeDependent())
4559 return false;
4560
4561 if (E->getObjectKind() == OK_BitField) {
4562 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
4563 << 1 << E->getSourceRange();
4564 return true;
4565 }
4566
4567 ValueDecl *D = nullptr;
4568 Expr *Inner = E->IgnoreParens();
4569 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Inner)) {
4570 D = DRE->getDecl();
4571 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Inner)) {
4572 D = ME->getMemberDecl();
4573 }
4574
4575 // If it's a field, require the containing struct to have a
4576 // complete definition so that we can compute the layout.
4577 //
4578 // This can happen in C++11 onwards, either by naming the member
4579 // in a way that is not transformed into a member access expression
4580 // (in an unevaluated operand, for instance), or by naming the member
4581 // in a trailing-return-type.
4582 //
4583 // For the record, since __alignof__ on expressions is a GCC
4584 // extension, GCC seems to permit this but always gives the
4585 // nonsensical answer 0.
4586 //
4587 // We don't really need the layout here --- we could instead just
4588 // directly check for all the appropriate alignment-lowing
4589 // attributes --- but that would require duplicating a lot of
4590 // logic that just isn't worth duplicating for such a marginal
4591 // use-case.
4592 if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
4593 // Fast path this check, since we at least know the record has a
4594 // definition if we can find a member of it.
4595 if (!FD->getParent()->isCompleteDefinition()) {
4596 S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
4597 << E->getSourceRange();
4598 return true;
4599 }
4600
4601 // Otherwise, if it's a field, and the field doesn't have
4602 // reference type, then it must have a complete type (or be a
4603 // flexible array member, which we explicitly want to
4604 // white-list anyway), which makes the following checks trivial.
4605 if (!FD->getType()->isReferenceType())
4606 return false;
4607 }
4608
4609 return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
4610}
4611
4613 E = E->IgnoreParens();
4614
4615 // Cannot know anything else if the expression is dependent.
4616 if (E->isTypeDependent())
4617 return false;
4618
4619 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4620}
4621
4623 CapturingScopeInfo *CSI) {
4624 assert(T->isVariablyModifiedType());
4625 assert(CSI != nullptr);
4626
4627 // We're going to walk down into the type and look for VLA expressions.
4628 do {
4629 const Type *Ty = T.getTypePtr();
4630 switch (Ty->getTypeClass()) {
4631#define TYPE(Class, Base)
4632#define ABSTRACT_TYPE(Class, Base)
4633#define NON_CANONICAL_TYPE(Class, Base)
4634#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4635#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4636#include "clang/AST/TypeNodes.inc"
4637 T = QualType();
4638 break;
4639 // These types are never variably-modified.
4640 case Type::Builtin:
4641 case Type::Complex:
4642 case Type::Vector:
4643 case Type::ExtVector:
4644 case Type::ConstantMatrix:
4645 case Type::Record:
4646 case Type::Enum:
4647 case Type::TemplateSpecialization:
4648 case Type::ObjCObject:
4649 case Type::ObjCInterface:
4650 case Type::ObjCObjectPointer:
4651 case Type::ObjCTypeParam:
4652 case Type::Pipe:
4653 case Type::BitInt:
4654 llvm_unreachable("type class is never variably-modified!");
4655 case Type::Elaborated:
4656 T = cast<ElaboratedType>(Ty)->getNamedType();
4657 break;
4658 case Type::Adjusted:
4659 T = cast<AdjustedType>(Ty)->getOriginalType();
4660 break;
4661 case Type::Decayed:
4662 T = cast<DecayedType>(Ty)->getPointeeType();
4663 break;
4664 case Type::ArrayParameter:
4665 T = cast<ArrayParameterType>(Ty)->getElementType();
4666 break;
4667 case Type::Pointer:
4668 T = cast<PointerType>(Ty)->getPointeeType();
4669 break;
4670 case Type::BlockPointer:
4671 T = cast<BlockPointerType>(Ty)->getPointeeType();
4672 break;
4673 case Type::LValueReference:
4674 case Type::RValueReference:
4675 T = cast<ReferenceType>(Ty)->getPointeeType();
4676 break;
4677 case Type::MemberPointer:
4678 T = cast<MemberPointerType>(Ty)->getPointeeType();
4679 break;
4680 case Type::ConstantArray:
4681 case Type::IncompleteArray:
4682 // Losing element qualification here is fine.
4683 T = cast<ArrayType>(Ty)->getElementType();
4684 break;
4685 case Type::VariableArray: {
4686 // Losing element qualification here is fine.
4687 const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4688
4689 // Unknown size indication requires no size computation.
4690 // Otherwise, evaluate and record it.
4691 auto Size = VAT->getSizeExpr();
4692 if (Size && !CSI->isVLATypeCaptured(VAT) &&
4693 (isa<CapturedRegionScopeInfo>(CSI) || isa<LambdaScopeInfo>(CSI)))
4694 CSI->addVLATypeCapture(Size->getExprLoc(), VAT, Context.getSizeType());
4695
4696 T = VAT->getElementType();
4697 break;
4698 }
4699 case Type::FunctionProto:
4700 case Type::FunctionNoProto:
4701 T = cast<FunctionType>(Ty)->getReturnType();
4702 break;
4703 case Type::Paren:
4704 case Type::TypeOf:
4705 case Type::UnaryTransform:
4706 case Type::Attributed:
4707 case Type::BTFTagAttributed:
4708 case Type::SubstTemplateTypeParm:
4709 case Type::MacroQualified:
4710 case Type::CountAttributed:
4711 // Keep walking after single level desugaring.
4712 T = T.getSingleStepDesugaredType(Context);
4713 break;
4714 case Type::Typedef:
4715 T = cast<TypedefType>(Ty)->desugar();
4716 break;
4717 case Type::Decltype:
4718 T = cast<DecltypeType>(Ty)->desugar();
4719 break;
4720 case Type::PackIndexing:
4721 T = cast<PackIndexingType>(Ty)->desugar();
4722 break;
4723 case Type::Using:
4724 T = cast<UsingType>(Ty)->desugar();
4725 break;
4726 case Type::Auto:
4727 case Type::DeducedTemplateSpecialization:
4728 T = cast<DeducedType>(Ty)->getDeducedType();
4729 break;
4730 case Type::TypeOfExpr:
4731 T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4732 break;
4733 case Type::Atomic:
4734 T = cast<AtomicType>(Ty)->getValueType();
4735 break;
4736 }
4737 } while (!T.isNull() && T->isVariablyModifiedType());
4738}
4739
4740/// Check the constraints on operands to unary expression and type
4741/// traits.
4742///
4743/// This will complete any types necessary, and validate the various constraints
4744/// on those operands.
4745///
4746/// The UsualUnaryConversions() function is *not* called by this routine.
4747/// C99 6.3.2.1p[2-4] all state:
4748/// Except when it is the operand of the sizeof operator ...
4749///
4750/// C++ [expr.sizeof]p4
4751/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4752/// standard conversions are not applied to the operand of sizeof.
4753///
4754/// This policy is followed for all of the unary trait expressions.
4756 SourceLocation OpLoc,
4757 SourceRange ExprRange,
4758 UnaryExprOrTypeTrait ExprKind,
4759 StringRef KWName) {
4760 if (ExprType->isDependentType())
4761 return false;
4762
4763 // C++ [expr.sizeof]p2:
4764 // When applied to a reference or a reference type, the result
4765 // is the size of the referenced type.
4766 // C++11 [expr.alignof]p3:
4767 // When alignof is applied to a reference type, the result
4768 // shall be the alignment of the referenced type.
4769 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
4770 ExprType = Ref->getPointeeType();
4771
4772 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4773 // When alignof or _Alignof is applied to an array type, the result
4774 // is the alignment of the element type.
4775 if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
4776 ExprKind == UETT_OpenMPRequiredSimdAlign)
4777 ExprType = Context.getBaseElementType(ExprType);
4778
4779 if (ExprKind == UETT_VecStep)
4780 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
4781
4782 if (ExprKind == UETT_VectorElements)
4783 return CheckVectorElementsTraitOperandType(*this, ExprType, OpLoc,
4784 ExprRange);
4785
4786 // Explicitly list some types as extensions.
4787 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
4788 ExprKind))
4789 return false;
4790
4792 OpLoc, ExprType, diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4793 KWName, ExprRange))
4794 return true;
4795
4796 if (ExprType->isFunctionType()) {
4797 Diag(OpLoc, diag::err_sizeof_alignof_function_type) << KWName << ExprRange;
4798 return true;
4799 }
4800
4801 // WebAssembly tables are always illegal operands to unary expressions and
4802 // type traits.
4803 if (Context.getTargetInfo().getTriple().isWasm() &&
4804 ExprType->isWebAssemblyTableType()) {
4805 Diag(OpLoc, diag::err_wasm_table_invalid_uett_operand)
4806 << getTraitSpelling(ExprKind);
4807 return true;
4808 }
4809
4810 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
4811 ExprKind))
4812 return true;
4813
4814 if (ExprType->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4815 if (auto *TT = ExprType->getAs<TypedefType>()) {
4816 for (auto I = FunctionScopes.rbegin(),
4817 E = std::prev(FunctionScopes.rend());
4818 I != E; ++I) {
4819 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4820 if (CSI == nullptr)
4821 break;
4822 DeclContext *DC = nullptr;
4823 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4824 DC = LSI->CallOperator;
4825 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4826 DC = CRSI->TheCapturedDecl;
4827 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4828 DC = BSI->TheDecl;
4829 if (DC) {
4830 if (DC->containsDecl(TT->getDecl()))
4831 break;
4832 captureVariablyModifiedType(Context, ExprType, CSI);
4833 }
4834 }
4835 }
4836 }
4837
4838 return false;
4839}
4840
4841/// Build a sizeof or alignof expression given a type operand.
4843 SourceLocation OpLoc,
4844 UnaryExprOrTypeTrait ExprKind,
4845 SourceRange R) {
4846 if (!TInfo)
4847 return ExprError();
4848
4849 QualType T = TInfo->getType();
4850
4851 if (!T->isDependentType() &&
4852 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind,
4853 getTraitSpelling(ExprKind)))
4854 return ExprError();
4855
4856 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4857 // properly deal with VLAs in nested calls of sizeof and typeof.
4858 if (isUnevaluatedContext() && ExprKind == UETT_SizeOf &&
4859 TInfo->getType()->isVariablyModifiedType())
4860 TInfo = TransformToPotentiallyEvaluated(TInfo);
4861
4862 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4863 return new (Context) UnaryExprOrTypeTraitExpr(
4864 ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4865}
4866
4867/// Build a sizeof or alignof expression given an expression
4868/// operand.
4871 UnaryExprOrTypeTrait ExprKind) {
4873 if (PE.isInvalid())
4874 return ExprError();
4875
4876 E = PE.get();
4877
4878 // Verify that the operand is valid.
4879 bool isInvalid = false;
4880 if (E->isTypeDependent()) {
4881 // Delay type-checking for type-dependent expressions.
4882 } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4883 isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4884 } else if (ExprKind == UETT_VecStep) {
4886 } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4887 Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4888 isInvalid = true;
4889 } else if (E->refersToBitField()) { // C99 6.5.3.4p1.
4890 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4891 isInvalid = true;
4892 } else if (ExprKind == UETT_VectorElements) {
4893 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_VectorElements);
4894 } else {
4896 }
4897
4898 if (isInvalid)
4899 return ExprError();
4900
4901 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4903 if (PE.isInvalid()) return ExprError();
4904 E = PE.get();
4905 }
4906
4907 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4908 return new (Context) UnaryExprOrTypeTraitExpr(
4909 ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4910}
4911
4912/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4913/// expr and the same for @c alignof and @c __alignof
4914/// Note that the ArgRange is invalid if isType is false.
4917 UnaryExprOrTypeTrait ExprKind, bool IsType,
4918 void *TyOrEx, SourceRange ArgRange) {
4919 // If error parsing type, ignore.
4920 if (!TyOrEx) return ExprError();
4921
4922 if (IsType) {
4923 TypeSourceInfo *TInfo;
4924 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4925 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4926 }
4927
4928 Expr *ArgEx = (Expr *)TyOrEx;
4929 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4930 return Result;
4931}
4932
4934 SourceLocation OpLoc, SourceRange R) {
4935 if (!TInfo)
4936 return true;
4937 return CheckUnaryExprOrTypeTraitOperand(TInfo->getType(), OpLoc, R,
4938 UETT_AlignOf, KWName);
4939}
4940
4941/// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
4942/// _Alignas(type-name) .
4943/// [dcl.align] An alignment-specifier of the form
4944/// alignas(type-id) has the same effect as alignas(alignof(type-id)).
4945///
4946/// [N1570 6.7.5] _Alignas(type-name) is equivalent to
4947/// _Alignas(_Alignof(type-name)).
4949 SourceLocation OpLoc, SourceRange R) {
4950 TypeSourceInfo *TInfo;
4952 &TInfo);
4953 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4954}
4955
4957 bool IsReal) {
4958 if (V.get()->isTypeDependent())
4959 return S.Context.DependentTy;
4960
4961 // _Real and _Imag are only l-values for normal l-values.
4962 if (V.get()->getObjectKind() != OK_Ordinary) {
4963 V = S.DefaultLvalueConversion(V.get());
4964 if (V.isInvalid())
4965 return QualType();
4966 }
4967
4968 // These operators return the element type of a complex type.
4969 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4970 return CT->getElementType();
4971
4972 // Otherwise they pass through real integer and floating point types here.
4973 if (V.get()->getType()->isArithmeticType())
4974 return V.get()->getType();
4975
4976 // Test for placeholders.
4977 ExprResult PR = S.CheckPlaceholderExpr(V.get());
4978 if (PR.isInvalid()) return QualType();
4979 if (PR.get() != V.get()) {
4980 V = PR;
4981 return CheckRealImagOperand(S, V, Loc, IsReal);
4982 }
4983
4984 // Reject anything else.
4985 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4986 << (IsReal ? "__real" : "__imag");
4987 return QualType();
4988}
4989
4990
4991
4994 tok::TokenKind Kind, Expr *Input) {
4996 switch (Kind) {
4997 default: llvm_unreachable("Unknown unary op!");
4998 case tok::plusplus: Opc = UO_PostInc; break;
4999 case tok::minusminus: Opc = UO_PostDec; break;
5000 }
5001
5002 // Since this might is a postfix expression, get rid of ParenListExprs.
5004 if (Result.isInvalid()) return ExprError();
5005 Input = Result.get();
5006
5007 return BuildUnaryOp(S, OpLoc, Opc, Input);
5008}
5009
5010/// Diagnose if arithmetic on the given ObjC pointer is illegal.
5011///
5012/// \return true on error
5014 SourceLocation opLoc,
5015 Expr *op) {
5016 assert(op->getType()->isObjCObjectPointerType());
5018 !S.LangOpts.ObjCSubscriptingLegacyRuntime)
5019 return false;
5020
5021 S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
5022 << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
5023 << op->getSourceRange();
5024 return true;
5025}
5026
5028 auto *BaseNoParens = Base->IgnoreParens();
5029 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
5030 return MSProp->getPropertyDecl()->getType()->isArrayType();
5031 return isa<MSPropertySubscriptExpr>(BaseNoParens);
5032}
5033
5034// Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
5035// Typically this is DependentTy, but can sometimes be more precise.
5036//
5037// There are cases when we could determine a non-dependent type:
5038// - LHS and RHS may have non-dependent types despite being type-dependent
5039// (e.g. unbounded array static members of the current instantiation)
5040// - one may be a dependent-sized array with known element type
5041// - one may be a dependent-typed valid index (enum in current instantiation)
5042//
5043// We *always* return a dependent type, in such cases it is DependentTy.
5044// This avoids creating type-dependent expressions with non-dependent types.
5045// FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5047 const ASTContext &Ctx) {
5048 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5049 QualType LTy = LHS->getType(), RTy = RHS->getType();
5051 if (RTy->isIntegralOrUnscopedEnumerationType()) {
5052 if (const PointerType *PT = LTy->getAs<PointerType>())
5053 Result = PT->getPointeeType();
5054 else if (const ArrayType *AT = LTy->getAsArrayTypeUnsafe())
5055 Result = AT->getElementType();
5056 } else if (LTy->isIntegralOrUnscopedEnumerationType()) {
5057 if (const PointerType *PT = RTy->getAs<PointerType>())
5058 Result = PT->getPointeeType();
5059 else if (const ArrayType *AT = RTy->getAsArrayTypeUnsafe())
5060 Result = AT->getElementType();
5061 }
5062 // Ensure we return a dependent type.
5063 return Result->isDependentType() ? Result : Ctx.DependentTy;
5064}
5065
5067 SourceLocation lbLoc,
5068 MultiExprArg ArgExprs,
5069 SourceLocation rbLoc) {
5070
5071 if (base && !base->getType().isNull() &&
5072 base->hasPlaceholderType(BuiltinType::OMPArraySection))
5073 return OpenMP().ActOnOMPArraySectionExpr(base, lbLoc, ArgExprs.front(),
5075 /*Length*/ nullptr,
5076 /*Stride=*/nullptr, rbLoc);
5077
5078 // Since this might be a postfix expression, get rid of ParenListExprs.
5079 if (isa<ParenListExpr>(base)) {
5081 if (result.isInvalid())
5082 return ExprError();
5083 base = result.get();
5084 }
5085
5086 // Check if base and idx form a MatrixSubscriptExpr.
5087 //
5088 // Helper to check for comma expressions, which are not allowed as indices for
5089 // matrix subscript expressions.
5090 auto CheckAndReportCommaError = [this, base, rbLoc](Expr *E) {
5091 if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isCommaOp()) {
5092 Diag(E->getExprLoc(), diag::err_matrix_subscript_comma)
5093 << SourceRange(base->getBeginLoc(), rbLoc);
5094 return true;
5095 }
5096 return false;
5097 };
5098 // The matrix subscript operator ([][])is considered a single operator.
5099 // Separating the index expressions by parenthesis is not allowed.
5100 if (base && !base->getType().isNull() &&
5101 base->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx) &&
5102 !isa<MatrixSubscriptExpr>(base)) {
5103 Diag(base->getExprLoc(), diag::err_matrix_separate_incomplete_index)
5104 << SourceRange(base->getBeginLoc(), rbLoc);
5105 return ExprError();
5106 }
5107 // If the base is a MatrixSubscriptExpr, try to create a new
5108 // MatrixSubscriptExpr.
5109 auto *matSubscriptE = dyn_cast<MatrixSubscriptExpr>(base);
5110 if (matSubscriptE) {
5111 assert(ArgExprs.size() == 1);
5112 if (CheckAndReportCommaError(ArgExprs.front()))
5113 return ExprError();
5114
5115 assert(matSubscriptE->isIncomplete() &&
5116 "base has to be an incomplete matrix subscript");
5117 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE->getBase(),
5118 matSubscriptE->getRowIdx(),
5119 ArgExprs.front(), rbLoc);
5120 }
5121 if (base->getType()->isWebAssemblyTableType()) {
5122 Diag(base->getExprLoc(), diag::err_wasm_table_art)
5123 << SourceRange(base->getBeginLoc(), rbLoc) << 3;
5124 return ExprError();
5125 }
5126
5127 // Handle any non-overload placeholder types in the base and index
5128 // expressions. We can't handle overloads here because the other
5129 // operand might be an overloadable type, in which case the overload
5130 // resolution for the operator overload should get the first crack
5131 // at the overload.
5132 bool IsMSPropertySubscript = false;
5133 if (base->getType()->isNonOverloadPlaceholderType()) {
5134 IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
5135 if (!IsMSPropertySubscript) {
5136 ExprResult result = CheckPlaceholderExpr(base);
5137 if (result.isInvalid())
5138 return ExprError();
5139 base = result.get();
5140 }
5141 }
5142
5143 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5144 if (base->getType()->isMatrixType()) {
5145 assert(ArgExprs.size() == 1);
5146 if (CheckAndReportCommaError(ArgExprs.front()))
5147 return ExprError();
5148
5149 return CreateBuiltinMatrixSubscriptExpr(base, ArgExprs.front(), nullptr,
5150 rbLoc);
5151 }
5152
5153 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5154 Expr *idx = ArgExprs[0];
5155 if ((isa<BinaryOperator>(idx) && cast<BinaryOperator>(idx)->isCommaOp()) ||
5156 (isa<CXXOperatorCallExpr>(idx) &&
5157 cast<CXXOperatorCallExpr>(idx)->getOperator() == OO_Comma)) {
5158 Diag(idx->getExprLoc(), diag::warn_deprecated_comma_subscript)
5159 << SourceRange(base->getBeginLoc(), rbLoc);
5160 }
5161 }
5162
5163 if (ArgExprs.size() == 1 &&
5164 ArgExprs[0]->getType()->isNonOverloadPlaceholderType()) {
5165 ExprResult result = CheckPlaceholderExpr(ArgExprs[0]);
5166 if (result.isInvalid())
5167 return ExprError();
5168 ArgExprs[0] = result.get();
5169 } else {
5170 if (CheckArgsForPlaceholders(ArgExprs))
5171 return ExprError();
5172 }
5173
5174 // Build an unanalyzed expression if either operand is type-dependent.
5175 if (getLangOpts().CPlusPlus && ArgExprs.size() == 1 &&
5176 (base->isTypeDependent() ||
5178 !isa<PackExpansionExpr>(ArgExprs[0])) {
5179 return new (Context) ArraySubscriptExpr(
5180 base, ArgExprs.front(),
5181 getDependentArraySubscriptType(base, ArgExprs.front(), getASTContext()),
5182 VK_LValue, OK_Ordinary, rbLoc);
5183 }
5184
5185 // MSDN, property (C++)
5186 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5187 // This attribute can also be used in the declaration of an empty array in a
5188 // class or structure definition. For example:
5189 // __declspec(property(get=GetX, put=PutX)) int x[];
5190 // The above statement indicates that x[] can be used with one or more array
5191 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5192 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5193 if (IsMSPropertySubscript) {
5194 assert(ArgExprs.size() == 1);
5195 // Build MS property subscript expression if base is MS property reference
5196 // or MS property subscript.
5197 return new (Context)
5198 MSPropertySubscriptExpr(base, ArgExprs.front(), Context.PseudoObjectTy,
5199 VK_LValue, OK_Ordinary, rbLoc);
5200 }
5201
5202 // Use C++ overloaded-operator rules if either operand has record
5203 // type. The spec says to do this if either type is *overloadable*,
5204 // but enum types can't declare subscript operators or conversion
5205 // operators, so there's nothing interesting for overload resolution
5206 // to do if there aren't any record types involved.
5207 //
5208 // ObjC pointers have their own subscripting logic that is not tied
5209 // to overload resolution and so should not take this path.
5210 if (getLangOpts().CPlusPlus && !base->getType()->isObjCObjectPointerType() &&
5211 ((base->getType()->isRecordType() ||
5212 (ArgExprs.size() != 1 || isa<PackExpansionExpr>(ArgExprs[0]) ||
5213 ArgExprs[0]->getType()->isRecordType())))) {
5214 return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, ArgExprs);
5215 }
5216
5217 ExprResult Res =
5218 CreateBuiltinArraySubscriptExpr(base, lbLoc, ArgExprs.front(), rbLoc);
5219
5220 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
5221 CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
5222
5223 return Res;
5224}
5225
5228 InitializationKind Kind =
5230 InitializationSequence InitSeq(*this, Entity, Kind, E);
5231 return InitSeq.Perform(*this, Entity, Kind, E);
5232}
5233
5235 Expr *ColumnIdx,
5236 SourceLocation RBLoc) {
5238 if (BaseR.isInvalid())
5239 return BaseR;
5240 Base = BaseR.get();
5241
5242 ExprResult RowR = CheckPlaceholderExpr(RowIdx);
5243 if (RowR.isInvalid())
5244 return RowR;
5245 RowIdx = RowR.get();
5246
5247 if (!ColumnIdx)
5248 return new (Context) MatrixSubscriptExpr(
5249 Base, RowIdx, ColumnIdx, Context.IncompleteMatrixIdxTy, RBLoc);
5250
5251 // Build an unanalyzed expression if any of the operands is type-dependent.
5252 if (Base->isTypeDependent() || RowIdx->isTypeDependent() ||
5253 ColumnIdx->isTypeDependent())
5254 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5255 Context.DependentTy, RBLoc);
5256
5257 ExprResult ColumnR = CheckPlaceholderExpr(ColumnIdx);
5258 if (ColumnR.isInvalid())
5259 return ColumnR;
5260 ColumnIdx = ColumnR.get();
5261
5262 // Check that IndexExpr is an integer expression. If it is a constant
5263 // expression, check that it is less than Dim (= the number of elements in the
5264 // corresponding dimension).
5265 auto IsIndexValid = [&](Expr *IndexExpr, unsigned Dim,
5266 bool IsColumnIdx) -> Expr * {
5267 if (!IndexExpr->getType()->isIntegerType() &&
5268 !IndexExpr->isTypeDependent()) {
5269 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_not_integer)
5270 << IsColumnIdx;
5271 return nullptr;
5272 }
5273
5274 if (std::optional<llvm::APSInt> Idx =
5275 IndexExpr->getIntegerConstantExpr(Context)) {
5276 if ((*Idx < 0 || *Idx >= Dim)) {
5277 Diag(IndexExpr->getBeginLoc(), diag::err_matrix_index_outside_range)
5278 << IsColumnIdx << Dim;
5279 return nullptr;
5280 }
5281 }
5282
5283 ExprResult ConvExpr =
5285 assert(!ConvExpr.isInvalid() &&
5286 "should be able to convert any integer type to size type");
5287 return ConvExpr.get();
5288 };
5289
5290 auto *MTy = Base->getType()->getAs<ConstantMatrixType>();
5291 RowIdx = IsIndexValid(RowIdx, MTy->getNumRows(), false);
5292 ColumnIdx = IsIndexValid(ColumnIdx, MTy->getNumColumns(), true);
5293 if (!RowIdx || !ColumnIdx)
5294 return ExprError();
5295
5296 return new (Context) MatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
5297 MTy->getElementType(), RBLoc);
5298}
5299
5300void Sema::CheckAddressOfNoDeref(const Expr *E) {
5301 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5302 const Expr *StrippedExpr = E->IgnoreParenImpCasts();
5303
5304 // For expressions like `&(*s).b`, the base is recorded and what should be
5305 // checked.
5306 const MemberExpr *Member = nullptr;
5307 while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
5308 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5309
5310 LastRecord.PossibleDerefs.erase(StrippedExpr);
5311}
5312
5313void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5315 return;
5316
5317 QualType ResultTy = E->getType();
5318 ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
5319
5320 // Bail if the element is an array since it is not memory access.
5321 if (isa<ArrayType>(ResultTy))
5322 return;
5323
5324 if (ResultTy->hasAttr(attr::NoDeref)) {
5325 LastRecord.PossibleDerefs.insert(E);
5326 return;
5327 }
5328
5329 // Check if the base type is a pointer to a member access of a struct
5330 // marked with noderef.
5331 const Expr *Base = E->getBase();
5332 QualType BaseTy = Base->getType();
5333 if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
5334 // Not a pointer access
5335 return;
5336
5337 const MemberExpr *Member = nullptr;
5338 while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
5339 Member->isArrow())
5340 Base = Member->getBase();
5341
5342 if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
5343 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5344 LastRecord.PossibleDerefs.insert(E);
5345 }
5346}
5347
5350 Expr *Idx, SourceLocation RLoc) {
5351 Expr *LHSExp = Base;
5352 Expr *RHSExp = Idx;
5353
5356
5357 // Per C++ core issue 1213, the result is an xvalue if either operand is
5358 // a non-lvalue array, and an lvalue otherwise.
5359 if (getLangOpts().CPlusPlus11) {
5360 for (auto *Op : {LHSExp, RHSExp}) {
5361 Op = Op->IgnoreImplicit();
5362 if (Op->getType()->isArrayType() && !Op->isLValue())
5363 VK = VK_XValue;
5364 }
5365 }
5366
5367 // Perform default conversions.
5368 if (!LHSExp->getType()->getAs<VectorType>()) {
5370 if (Result.isInvalid())
5371 return ExprError();
5372 LHSExp = Result.get();
5373 }
5375 if (Result.isInvalid())
5376 return ExprError();
5377 RHSExp = Result.get();
5378
5379 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
5380
5381 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5382 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5383 // in the subscript position. As a result, we need to derive the array base
5384 // and index from the expression types.
5385 Expr *BaseExpr, *IndexExpr;
5386 QualType ResultType;
5387 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
5388 BaseExpr = LHSExp;
5389 IndexExpr = RHSExp;
5390 ResultType =
5392 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
5393 BaseExpr = LHSExp;
5394 IndexExpr = RHSExp;
5395 ResultType = PTy->getPointeeType();
5396 } else if (const ObjCObjectPointerType *PTy =
5397 LHSTy->getAs<ObjCObjectPointerType>()) {
5398 BaseExpr = LHSExp;
5399 IndexExpr = RHSExp;
5400
5401 // Use custom logic if this should be the pseudo-object subscript
5402 // expression.
5404 return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
5405 nullptr);
5406
5407 ResultType = PTy->getPointeeType();
5408 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
5409 // Handle the uncommon case of "123[Ptr]".
5410 BaseExpr = RHSExp;
5411 IndexExpr = LHSExp;
5412 ResultType = PTy->getPointeeType();
5413 } else if (const ObjCObjectPointerType *PTy =
5414 RHSTy->getAs<ObjCObjectPointerType>()) {
5415 // Handle the uncommon case of "123[Ptr]".
5416 BaseExpr = RHSExp;
5417 IndexExpr = LHSExp;
5418 ResultType = PTy->getPointeeType();
5420 Diag(LLoc, diag::err_subscript_nonfragile_interface)
5421 << ResultType << BaseExpr->getSourceRange();
5422 return ExprError();
5423 }
5424 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
5425 BaseExpr = LHSExp; // vectors: V[123]
5426 IndexExpr = RHSExp;
5427 // We apply C++ DR1213 to vector subscripting too.
5428 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5429 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5430 if (Materialized.isInvalid())
5431 return ExprError();
5432 LHSExp = Materialized.get();
5433 }
5434 VK = LHSExp->getValueKind();
5435 if (VK != VK_PRValue)
5436 OK = OK_VectorComponent;
5437
5438 ResultType = VTy->getElementType();
5439 QualType BaseType = BaseExpr->getType();
5440 Qualifiers BaseQuals = BaseType.getQualifiers();
5441 Qualifiers MemberQuals = ResultType.getQualifiers();
5442 Qualifiers Combined = BaseQuals + MemberQuals;
5443 if (Combined != MemberQuals)
5444 ResultType = Context.getQualifiedType(ResultType, Combined);
5445 } else if (LHSTy->isBuiltinType() &&
5446 LHSTy->getAs<BuiltinType>()->isSveVLSBuiltinType()) {
5447 const BuiltinType *BTy = LHSTy->getAs<BuiltinType>();
5448 if (BTy->isSVEBool())
5449 return ExprError(Diag(LLoc, diag::err_subscript_svbool_t)
5450 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5451
5452 BaseExpr = LHSExp;
5453 IndexExpr = RHSExp;
5454 if (getLangOpts().CPlusPlus11 && LHSExp->isPRValue()) {
5455 ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
5456 if (Materialized.isInvalid())
5457 return ExprError();
5458 LHSExp = Materialized.get();
5459 }
5460 VK = LHSExp->getValueKind();
5461 if (VK != VK_PRValue)
5462 OK = OK_VectorComponent;
5463
5464 ResultType = BTy->getSveEltType(Context);
5465
5466 QualType BaseType = BaseExpr->getType();
5467 Qualifiers BaseQuals = BaseType.getQualifiers();
5468 Qualifiers MemberQuals = ResultType.getQualifiers();
5469 Qualifiers Combined = BaseQuals + MemberQuals;
5470 if (Combined != MemberQuals)
5471 ResultType = Context.getQualifiedType(ResultType, Combined);
5472 } else if (LHSTy->isArrayType()) {
5473 // If we see an array that wasn't promoted by
5474 // DefaultFunctionArrayLvalueConversion, it must be an array that
5475 // wasn't promoted because of the C90 rule that doesn't
5476 // allow promoting non-lvalue arrays. Warn, then
5477 // force the promotion here.
5478 Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5479 << LHSExp->getSourceRange();
5480 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
5481 CK_ArrayToPointerDecay).get();
5482 LHSTy = LHSExp->getType();
5483
5484 BaseExpr = LHSExp;
5485 IndexExpr = RHSExp;
5486 ResultType = LHSTy->castAs<PointerType>()->getPointeeType();
5487 } else if (RHSTy->isArrayType()) {
5488 // Same as previous, except for 123[f().a] case
5489 Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
5490 << RHSExp->getSourceRange();
5491 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
5492 CK_ArrayToPointerDecay).get();
5493 RHSTy = RHSExp->getType();
5494
5495 BaseExpr = RHSExp;
5496 IndexExpr = LHSExp;
5497 ResultType = RHSTy->castAs<PointerType>()->getPointeeType();
5498 } else {
5499 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
5500 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
5501 }
5502 // C99 6.5.2.1p1
5503 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
5504 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
5505 << IndexExpr->getSourceRange());
5506
5507 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
5508 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U)) &&
5509 !IndexExpr->isTypeDependent()) {
5510 std::optional<llvm::APSInt> IntegerContantExpr =
5512 if (!IntegerContantExpr.has_value() ||
5513 IntegerContantExpr.value().isNegative())
5514 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
5515 }
5516
5517 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5518 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5519 // type. Note that Functions are not objects, and that (in C99 parlance)
5520 // incomplete types are not object types.
5521 if (ResultType->isFunctionType()) {
5522 Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
5523 << ResultType << BaseExpr->getSourceRange();
5524 return ExprError();
5525 }
5526
5527 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
5528 // GNU extension: subscripting on pointer to void
5529 Diag(LLoc, diag::ext_gnu_subscript_void_type)
5530 << BaseExpr->getSourceRange();
5531
5532 // C forbids expressions of unqualified void type from being l-values.
5533 // See IsCForbiddenLValueType.
5534 if (!ResultType.hasQualifiers())
5535 VK = VK_PRValue;
5536 } else if (!ResultType->isDependentType() &&
5537 !ResultType.isWebAssemblyReferenceType() &&
5539 LLoc, ResultType,
5540 diag::err_subscript_incomplete_or_sizeless_type, BaseExpr))
5541 return ExprError();
5542
5543 assert(VK == VK_PRValue || LangOpts.CPlusPlus ||
5544 !ResultType.isCForbiddenLValueType());
5545
5547 FunctionScopes.size() > 1) {
5548 if (auto *TT =
5549 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5550 for (auto I = FunctionScopes.rbegin(),
5551 E = std::prev(FunctionScopes.rend());
5552 I != E; ++I) {
5553 auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
5554 if (CSI == nullptr)
5555 break;
5556 DeclContext *DC = nullptr;
5557 if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
5558 DC = LSI->CallOperator;
5559 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
5560 DC = CRSI->TheCapturedDecl;
5561 else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
5562 DC = BSI->TheDecl;
5563 if (DC) {
5564 if (DC->containsDecl(TT->getDecl()))
5565 break;
5567 Context, LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5568 }
5569 }
5570 }
5571 }
5572
5573 return new (Context)
5574 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5575}
5576
5578 ParmVarDecl *Param, Expr *RewrittenInit,
5579 bool SkipImmediateInvocations) {
5580 if (Param->hasUnparsedDefaultArg()) {
5581 assert(!RewrittenInit && "Should not have a rewritten init expression yet");
5582 // If we've already cleared out the location for the default argument,
5583 // that means we're parsing it right now.
5584 if (!UnparsedDefaultArgLocs.count(Param)) {
5585 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
5586 Diag(CallLoc, diag::note_recursive_default_argument_used_here);
5587 Param->setInvalidDecl();
5588 return true;
5589 }
5590
5591 Diag(CallLoc, diag::err_use_of_default_argument_to_function_declared_later)
5592 << FD << cast<CXXRecordDecl>(FD->getDeclContext());
5594 diag::note_default_argument_declared_here);
5595 return true;
5596 }
5597
5598 if (Param->hasUninstantiatedDefaultArg()) {
5599 assert(!RewrittenInit && "Should not have a rewitten init expression yet");
5600 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5601 return true;
5602 }
5603
5604 Expr *Init = RewrittenInit ? RewrittenInit : Param->getInit();
5605 assert(Init && "default argument but no initializer?");
5606
5607 // If the default expression creates temporaries, we need to
5608 // push them to the current stack of expression temporaries so they'll
5609 // be properly destroyed.
5610 // FIXME: We should really be rebuilding the default argument with new
5611 // bound temporaries; see the comment in PR5810.
5612 // We don't need to do that with block decls, though, because
5613 // blocks in default argument expression can never capture anything.
5614 if (auto *InitWithCleanup = dyn_cast<ExprWithCleanups>(Init)) {
5615 // Set the "needs cleanups" bit regardless of whether there are
5616 // any explicit objects.
5617 Cleanup.setExprNeedsCleanups(InitWithCleanup->cleanupsHaveSideEffects());
5618 // Append all the objects to the cleanup list. Right now, this
5619 // should always be a no-op, because blocks in default argument
5620 // expressions should never be able to capture anything.
5621 assert(!InitWithCleanup->getNumObjects() &&
5622 "default argument expression has capturing blocks?");
5623 }
5624 // C++ [expr.const]p15.1:
5625 // An expression or conversion is in an immediate function context if it is
5626 // potentially evaluated and [...] its innermost enclosing non-block scope
5627 // is a function parameter scope of an immediate function.
5629 *this,
5633 Param);
5634 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5635 SkipImmediateInvocations;
5636 runWithSufficientStackSpace(CallLoc, [&] {
5637 MarkDeclarationsReferencedInExpr(Init, /*SkipLocalVariables=*/true);
5638 });
5639 return false;
5640}
5641
5642struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
5644 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {}
5645
5646 bool HasImmediateCalls = false;
5647 bool shouldVisitImplicitCode() const { return true; }
5648
5650 if (const FunctionDecl *FD = E->getDirectCallee())
5651 HasImmediateCalls |= FD->isImmediateFunction();
5653 }
5654
5656 if (const FunctionDecl *FD = E->getConstructor())
5657 HasImmediateCalls |= FD->isImmediateFunction();
5659 }
5660
5661 // SourceLocExpr are not immediate invocations
5662 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5663 // need to be rebuilt so that they refer to the correct SourceLocation and
5664 // DeclContext.
5666 HasImmediateCalls = true;
5668 }
5669
5670 // A nested lambda might have parameters with immediate invocations
5671 // in their default arguments.
5672 // The compound statement is not visited (as it does not constitute a
5673 // subexpression).
5674 // FIXME: We should consider visiting and transforming captures
5675 // with init expressions.
5677 return VisitCXXMethodDecl(E->getCallOperator());
5678 }
5679
5681 return TraverseStmt(E->getExpr());
5682 }
5683
5685 return TraverseStmt(E->getExpr());
5686 }
5687};
5688
5690 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5692 : TreeTransform(SemaRef) {}
5693
5694 // Lambda can only have immediate invocations in the default
5695 // args of their parameters, which is transformed upon calling the closure.
5696 // The body is not a subexpression, so we have nothing to do.
5697 // FIXME: Immediate calls in capture initializers should be transformed.
5700
5701 // Make sure we don't rebuild the this pointer as it would
5702 // cause it to incorrectly point it to the outermost class
5703 // in the case of nested struct initialization.
5705};
5706
5708 FunctionDecl *FD, ParmVarDecl *Param,
5709 Expr *Init) {
5710 assert(Param->hasDefaultArg() && "can't build nonexistent default arg");
5711
5712 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5713 bool InLifetimeExtendingContext = isInLifetimeExtendingContext();
5714 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5715 InitializationContext =
5717 if (!InitializationContext.has_value())
5718 InitializationContext.emplace(CallLoc, Param, CurContext);
5719
5720 if (!Init && !Param->hasUnparsedDefaultArg()) {
5721 // Mark that we are replacing a default argument first.
5722 // If we are instantiating a template we won't have to
5723 // retransform immediate calls.
5724 // C++ [expr.const]p15.1:
5725 // An expression or conversion is in an immediate function context if it
5726 // is potentially evaluated and [...] its innermost enclosing non-block
5727 // scope is a function parameter scope of an immediate function.
5729 *this,
5733 Param);
5734
5735 if (Param->hasUninstantiatedDefaultArg()) {
5736 if (InstantiateDefaultArgument(CallLoc, FD, Param))
5737 return ExprError();
5738 }
5739 // CWG2631
5740 // An immediate invocation that is not evaluated where it appears is
5741 // evaluated and checked for whether it is a constant expression at the
5742 // point where the enclosing initializer is used in a function call.
5744 if (!NestedDefaultChecking)
5745 V.TraverseDecl(Param);
5746
5747 // Rewrite the call argument that was created from the corresponding
5748 // parameter's default argument.
5749 if (V.HasImmediateCalls || InLifetimeExtendingContext) {
5750 if (V.HasImmediateCalls)
5751 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
5752 CallLoc, Param, CurContext};
5753 // Pass down lifetime extending flag, and collect temporaries in
5754 // CreateMaterializeTemporaryExpr when we rewrite the call argument.
5757 ExprResult Res;
5758 runWithSufficientStackSpace(CallLoc, [&] {
5759 Res = Immediate.TransformInitializer(Param->getInit(),
5760 /*NotCopy=*/false);
5761 });
5762 if (Res.isInvalid())
5763 return ExprError();
5764 Res = ConvertParamDefaultArgument(Param, Res.get(),
5765 Res.get()->getBeginLoc());
5766 if (Res.isInvalid())
5767 return ExprError();
5768 Init = Res.get();
5769 }
5770 }
5771
5773 CallLoc, FD, Param, Init,
5774 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5775 return ExprError();
5776
5777 return CXXDefaultArgExpr::Create(Context, InitializationContext->Loc, Param,
5778 Init, InitializationContext->Context);
5779}
5780
5782 assert(Field->hasInClassInitializer());
5783
5784 // If we might have already tried and failed to instantiate, don't try again.
5785 if (Field->isInvalidDecl())
5786 return ExprError();
5787
5788 CXXThisScopeRAII This(*this, Field->getParent(), Qualifiers());
5789
5790 auto *ParentRD = cast<CXXRecordDecl>(Field->getParent());
5791
5792 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5793 InitializationContext =
5795 if (!InitializationContext.has_value())
5796 InitializationContext.emplace(Loc, Field, CurContext);
5797
5798 Expr *Init = nullptr;
5799
5800 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5801
5804
5805 if (!Field->getInClassInitializer()) {
5806 // Maybe we haven't instantiated the in-class initializer. Go check the
5807 // pattern FieldDecl to see if it has one.
5808 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
5809 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5811 ClassPattern->lookup(Field->getDeclName());
5812
5813 FieldDecl *Pattern = nullptr;
5814 for (auto *L : Lookup) {
5815 if ((Pattern = dyn_cast<FieldDecl>(L)))
5816 break;
5817 }
5818 assert(Pattern && "We must have set the Pattern!");
5819 if (!Pattern->hasInClassInitializer() ||
5820 InstantiateInClassInitializer(Loc, Field, Pattern,
5822 Field->setInvalidDecl();
5823 return ExprError();
5824 }
5825 }
5826 }
5827
5828 // CWG2631
5829 // An immediate invocation that is not evaluated where it appears is
5830 // evaluated and checked for whether it is a constant expression at the
5831 // point where the enclosing initializer is used in a [...] a constructor
5832 // definition, or an aggregate initialization.
5834 if (!NestedDefaultChecking)
5835 V.TraverseDecl(Field);
5836 if (V.HasImmediateCalls) {
5837 ExprEvalContexts.back().DelayedDefaultInitializationContext = {Loc, Field,
5838 CurContext};
5839 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5840 NestedDefaultChecking;
5841
5843 ExprResult Res;
5845 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5846 /*CXXDirectInit=*/false);
5847 });
5848 if (!Res.isInvalid())
5849 Res = ConvertMemberDefaultInitExpression(Field, Res.get(), Loc);
5850 if (Res.isInvalid()) {
5851 Field->setInvalidDecl();
5852 return ExprError();
5853 }
5854 Init = Res.get();
5855 }
5856
5857 if (Field->getInClassInitializer()) {
5858 Expr *E = Init ? Init : Field->getInClassInitializer();
5859 if (!NestedDefaultChecking)
5861 MarkDeclarationsReferencedInExpr(E, /*SkipLocalVariables=*/false);
5862 });
5863 // C++11 [class.base.init]p7:
5864 // The initialization of each base and member constitutes a
5865 // full-expression.
5866 ExprResult Res = ActOnFinishFullExpr(E, /*DiscardedValue=*/false);
5867 if (Res.isInvalid()) {
5868 Field->setInvalidDecl();
5869 return ExprError();
5870 }
5871 Init = Res.get();
5872
5873 return CXXDefaultInitExpr::Create(Context, InitializationContext->Loc,
5874 Field, InitializationContext->Context,
5875 Init);
5876 }
5877
5878 // DR1351:
5879 // If the brace-or-equal-initializer of a non-static data member
5880 // invokes a defaulted default constructor of its class or of an
5881 // enclosing class in a potentially evaluated subexpression, the
5882 // program is ill-formed.
5883 //
5884 // This resolution is unworkable: the exception specification of the
5885 // default constructor can be needed in an unevaluated context, in
5886 // particular, in the operand of a noexcept-expression, and we can be
5887 // unable to compute an exception specification for an enclosed class.
5888 //
5889 // Any attempt to resolve the exception specification of a defaulted default
5890 // constructor before the initializer is lexically complete will ultimately
5891 // come here at which point we can diagnose it.
5892 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
5893 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
5894 << OutermostClass << Field;
5895 Diag(Field->getEndLoc(),
5896 diag::note_default_member_initializer_not_yet_parsed);
5897 // Recover by marking the field invalid, unless we're in a SFINAE context.
5898 if (!isSFINAEContext())
5899 Field->setInvalidDecl();
5900 return ExprError();
5901}
5902
5905 Expr *Fn) {
5906 if (Proto && Proto->isVariadic()) {
5907 if (isa_and_nonnull<CXXConstructorDecl>(FDecl))
5908 return VariadicConstructor;
5909 else if (Fn && Fn->getType()->isBlockPointerType())
5910 return VariadicBlock;
5911 else if (FDecl) {
5912 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5913 if (Method->isInstance())
5914 return VariadicMethod;
5915 } else if (Fn && Fn->getType() == Context.BoundMemberTy)
5916 return VariadicMethod;
5917 return VariadicFunction;
5918 }
5919 return VariadicDoesNotApply;
5920}
5921
5922namespace {
5923class FunctionCallCCC final : public FunctionCallFilterCCC {
5924public:
5925 FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
5926 unsigned NumArgs, MemberExpr *ME)
5927 : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
5928 FunctionName(FuncName) {}
5929
5930 bool ValidateCandidate(const TypoCorrection &candidate) override {
5931 if (!candidate.getCorrectionSpecifier() ||
5932 candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
5933 return false;
5934 }
5935
5937 }
5938
5939 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5940 return std::make_unique<FunctionCallCCC>(*this);
5941 }
5942
5943private:
5944 const IdentifierInfo *const FunctionName;
5945};
5946}
5947
5949 FunctionDecl *FDecl,
5950 ArrayRef<Expr *> Args) {
5951 MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
5952 DeclarationName FuncName = FDecl->getDeclName();
5953 SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
5954
5955 FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
5956 if (TypoCorrection Corrected = S.CorrectTypo(
5958 S.getScopeForContext(S.CurContext), nullptr, CCC,
5960 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5961 if (Corrected.isOverloaded()) {
5964 for (NamedDecl *CD : Corrected) {
5965 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5967 OCS);
5968 }
5969 switch (OCS.BestViableFunction(S, NameLoc, Best)) {
5970 case OR_Success:
5971 ND = Best->FoundDecl;
5972 Corrected.setCorrectionDecl(ND);
5973 break;
5974 default:
5975 break;
5976 }
5977 }
5978 ND = ND->getUnderlyingDecl();
5979 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
5980 return Corrected;
5981 }
5982 }
5983 return TypoCorrection();
5984}
5985
5986/// ConvertArgumentsForCall - Converts the arguments specified in
5987/// Args/NumArgs to the parameter types of the function FDecl with
5988/// function prototype Proto. Call is the call expression itself, and
5989/// Fn is the function expression. For a C++ member function, this
5990/// routine does not attempt to convert the object argument. Returns
5991/// true if the call is ill-formed.
5992bool
5994 FunctionDecl *FDecl,
5995 const FunctionProtoType *Proto,
5996 ArrayRef<Expr *> Args,
5997 SourceLocation RParenLoc,
5998 bool IsExecConfig) {
5999 // Bail out early if calling a builtin with custom typechecking.
6000 if (FDecl)
6001 if (unsigned ID = FDecl->getBuiltinID())
6003 return false;
6004
6005 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6006 // assignment, to the types of the corresponding parameter, ...
6007 bool HasExplicitObjectParameter =
6008 FDecl && FDecl->hasCXXExplicitFunctionObjectParameter();
6009 unsigned ExplicitObjectParameterOffset = HasExplicitObjectParameter ? 1 : 0;
6010 unsigned NumParams = Proto->getNumParams();
6011 bool Invalid = false;
6012 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
6013 unsigned FnKind = Fn->getType()->isBlockPointerType()
6014 ? 1 /* block */
6015 : (IsExecConfig ? 3 /* kernel function (exec config) */
6016 : 0 /* function */);
6017
6018 // If too few arguments are available (and we don't have default
6019 // arguments for the remaining parameters), don't make the call.
6020 if (Args.size() < NumParams) {
6021 if (Args.size() < MinArgs) {
6022 TypoCorrection TC;
6023 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6024 unsigned diag_id =
6025 MinArgs == NumParams && !Proto->isVariadic()
6026 ? diag::err_typecheck_call_too_few_args_suggest
6027 : diag::err_typecheck_call_too_few_args_at_least_suggest;
6029 TC, PDiag(diag_id)
6030 << FnKind << MinArgs - ExplicitObjectParameterOffset
6031 << static_cast<unsigned>(Args.size()) -
6032 ExplicitObjectParameterOffset
6033 << HasExplicitObjectParameter << TC.getCorrectionRange());
6034 } else if (MinArgs - ExplicitObjectParameterOffset == 1 && FDecl &&
6035 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6036 ->getDeclName())
6037 Diag(RParenLoc,
6038 MinArgs == NumParams && !Proto->isVariadic()
6039 ? diag::err_typecheck_call_too_few_args_one
6040 : diag::err_typecheck_call_too_few_args_at_least_one)
6041 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6042 << HasExplicitObjectParameter << Fn->getSourceRange();
6043 else
6044 Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
6045 ? diag::err_typecheck_call_too_few_args
6046 : diag::err_typecheck_call_too_few_args_at_least)
6047 << FnKind << MinArgs - ExplicitObjectParameterOffset
6048 << static_cast<unsigned>(Args.size()) -
6049 ExplicitObjectParameterOffset
6050 << HasExplicitObjectParameter << Fn->getSourceRange();
6051
6052 // Emit the location of the prototype.
6053 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6054 Diag(FDecl->getLocation(), diag::note_callee_decl)
6055 << FDecl << FDecl->getParametersSourceRange();
6056
6057 return true;
6058 }
6059 // We reserve space for the default arguments when we create
6060 // the call expression, before calling ConvertArgumentsForCall.
6061 assert((Call->getNumArgs() == NumParams) &&
6062 "We should have reserved space for the default arguments before!");
6063 }
6064
6065 // If too many are passed and not variadic, error on the extras and drop
6066 // them.
6067 if (Args.size() > NumParams) {
6068 if (!Proto->isVariadic()) {
6069 TypoCorrection TC;
6070 if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
6071 unsigned diag_id =
6072 MinArgs == NumParams && !Proto->isVariadic()
6073 ? diag::err_typecheck_call_too_many_args_suggest
6074 : diag::err_typecheck_call_too_many_args_at_most_suggest;
6076 TC, PDiag(diag_id)
6077 << FnKind << NumParams - ExplicitObjectParameterOffset
6078 << static_cast<unsigned>(Args.size()) -
6079 ExplicitObjectParameterOffset
6080 << HasExplicitObjectParameter << TC.getCorrectionRange());
6081 } else if (NumParams - ExplicitObjectParameterOffset == 1 && FDecl &&
6082 FDecl->getParamDecl(ExplicitObjectParameterOffset)
6083 ->getDeclName())
6084 Diag(Args[NumParams]->getBeginLoc(),
6085 MinArgs == NumParams
6086 ? diag::err_typecheck_call_too_many_args_one
6087 : diag::err_typecheck_call_too_many_args_at_most_one)
6088 << FnKind << FDecl->getParamDecl(ExplicitObjectParameterOffset)
6089 << static_cast<unsigned>(Args.size()) -
6090 ExplicitObjectParameterOffset
6091 << HasExplicitObjectParameter << Fn->getSourceRange()
6092 << SourceRange(Args[NumParams]->getBeginLoc(),
6093 Args.back()->getEndLoc());
6094 else
6095 Diag(Args[NumParams]->getBeginLoc(),
6096 MinArgs == NumParams
6097 ? diag::err_typecheck_call_too_many_args
6098 : diag::err_typecheck_call_too_many_args_at_most)
6099 << FnKind << NumParams - ExplicitObjectParameterOffset
6100 << static_cast<unsigned>(Args.size()) -
6101 ExplicitObjectParameterOffset
6102 << HasExplicitObjectParameter << Fn->getSourceRange()
6103 << SourceRange(Args[NumParams]->getBeginLoc(),
6104 Args.back()->getEndLoc());
6105
6106 // Emit the location of the prototype.
6107 if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
6108 Diag(FDecl->getLocation(), diag::note_callee_decl)
6109 << FDecl << FDecl->getParametersSourceRange();
6110
6111 // This deletes the extra arguments.
6112 Call->shrinkNumArgs(NumParams);
6113 return true;
6114 }
6115 }
6116 SmallVector<Expr *, 8> AllArgs;
6117 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6118
6119 Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
6120 AllArgs, CallType);
6121 if (Invalid)
6122 return true;
6123 unsigned TotalNumArgs = AllArgs.size();
6124 for (unsigned i = 0; i < TotalNumArgs; ++i)
6125 Call->setArg(i, AllArgs[i]);
6126
6127 Call->computeDependence();
6128 return false;
6129}
6130
6132 const FunctionProtoType *Proto,
6133 unsigned FirstParam, ArrayRef<Expr *> Args,
6134 SmallVectorImpl<Expr *> &AllArgs,
6135 VariadicCallType CallType, bool AllowExplicit,
6136 bool IsListInitialization) {
6137 unsigned NumParams = Proto->getNumParams();
6138 bool Invalid = false;
6139 size_t ArgIx = 0;
6140 // Continue to check argument types (even if we have too few/many args).
6141 for (unsigned i = FirstParam; i < NumParams; i++) {
6142 QualType ProtoArgType = Proto->getParamType(i);
6143
6144 Expr *Arg;
6145 ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
6146 if (ArgIx < Args.size()) {
6147 Arg = Args[ArgIx++];
6148
6149 if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
6150 diag::err_call_incomplete_argument, Arg))
6151 return true;
6152
6153 // Strip the unbridged-cast placeholder expression off, if applicable.
6154 bool CFAudited = false;
6155 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
6156 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6157 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6158 Arg = stripARCUnbridgedCast(Arg);
6159 else if (getLangOpts().ObjCAutoRefCount &&
6160 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
6161 (!Param || !Param->hasAttr<CFConsumedAttr>()))
6162 CFAudited = true;
6163
6164 if (Proto->getExtParameterInfo(i).isNoEscape() &&
6165 ProtoArgType->isBlockPointerType())
6166 if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
6167 BE->getBlockDecl()->setDoesNotEscape();
6168
6169 InitializedEntity Entity =
6171 ProtoArgType)
6173 Context, ProtoArgType, Proto->isParamConsumed(i));
6174
6175 // Remember that parameter belongs to a CF audited API.
6176 if (CFAudited)
6177 Entity.setParameterCFAudited();
6178
6180 Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
6181 if (ArgE.isInvalid())
6182 return true;
6183
6184 Arg = ArgE.getAs<Expr>();
6185 } else {
6186 assert(Param && "can't use default arguments without a known callee");
6187
6188 ExprResult ArgExpr = BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
6189 if (ArgExpr.isInvalid())
6190 return true;
6191
6192 Arg = ArgExpr.getAs<Expr>();
6193 }
6194
6195 // Check for array bounds violations for each argument to the call. This
6196 // check only triggers warnings when the argument isn't a more complex Expr
6197 // with its own checking, such as a BinaryOperator.
6198 CheckArrayAccess(Arg);
6199
6200 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6201 CheckStaticArrayArgument(CallLoc, Param, Arg);
6202
6203 AllArgs.push_back(Arg);
6204 }
6205
6206 // If this is a variadic call, handle args passed through "...".
6207 if (CallType != VariadicDoesNotApply) {
6208 // Assume that extern "C" functions with variadic arguments that
6209 // return __unknown_anytype aren't *really* variadic.
6210 if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
6211 FDecl->isExternC()) {
6212 for (Expr *A : Args.slice(ArgIx)) {
6213 QualType paramType; // ignored
6214 ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
6215 Invalid |= arg.isInvalid();
6216 AllArgs.push_back(arg.get());
6217 }
6218
6219 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6220 } else {
6221 for (Expr *A : Args.slice(ArgIx)) {
6222 ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
6223 Invalid |= Arg.isInvalid();
6224 AllArgs.push_back(Arg.get());
6225 }
6226 }
6227
6228 // Check for array bounds violations.
6229 for (Expr *A : Args.slice(ArgIx))
6230 CheckArrayAccess(A);
6231 }
6232 return Invalid;
6233}
6234
6236 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
6237 if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
6238 TL = DTL.getOriginalLoc();
6239 if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
6240 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
6241 << ATL.getLocalSourceRange();
6242}
6243
6244/// CheckStaticArrayArgument - If the given argument corresponds to a static
6245/// array parameter, check that it is non-null, and that if it is formed by
6246/// array-to-pointer decay, the underlying array is sufficiently large.
6247///
6248/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6249/// array type derivation, then for each call to the function, the value of the
6250/// corresponding actual argument shall provide access to the first element of
6251/// an array with at least as many elements as specified by the size expression.
6252void
6254 ParmVarDecl *Param,
6255 const Expr *ArgExpr) {
6256 // Static array parameters are not supported in C++.
6257 if (!Param || getLangOpts().CPlusPlus)
6258 return;
6259
6260 QualType OrigTy = Param->getOriginalType();
6261
6262 const ArrayType *AT = Context.getAsArrayType(OrigTy);
6263 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6264 return;
6265
6266 if (ArgExpr->isNullPointerConstant(Context,
6268 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6269 DiagnoseCalleeStaticArrayParam(*this, Param);
6270 return;
6271 }
6272
6273 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
6274 if (!CAT)
6275 return;
6276
6277 const ConstantArrayType *ArgCAT =
6279 if (!ArgCAT)
6280 return;
6281
6282 if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
6283 ArgCAT->getElementType())) {
6284 if (ArgCAT->getSize().ult(CAT->getSize())) {
6285 Diag(CallLoc, diag::warn_static_array_too_small)
6286 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6287 << (unsigned)CAT->getZExtSize() << 0;
6288 DiagnoseCalleeStaticArrayParam(*this, Param);
6289 }
6290 return;
6291 }
6292
6293 std::optional<CharUnits> ArgSize =
6295 std::optional<CharUnits> ParmSize =
6297 if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
6298 Diag(CallLoc, diag::warn_static_array_too_small)
6299 << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
6300 << (unsigned)ParmSize->getQuantity() << 1;
6301 DiagnoseCalleeStaticArrayParam(*this, Param);
6302 }
6303}
6304
6305/// Given a function expression of unknown-any type, try to rebuild it
6306/// to have a function type.
6308
6309/// Is the given type a placeholder that we need to lower out
6310/// immediately during argument processing?
6312 // Placeholders are never sugared.
6313 const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
6314 if (!placeholder) return false;
6315
6316 switch (placeholder->getKind()) {
6317 // Ignore all the non-placeholder types.
6318#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6319 case BuiltinType::Id:
6320#include "clang/Basic/OpenCLImageTypes.def"
6321#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6322 case BuiltinType::Id:
6323#include "clang/Basic/OpenCLExtensionTypes.def"
6324 // In practice we'll never use this, since all SVE types are sugared
6325 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6326#define SVE_TYPE(Name, Id, SingletonId) \
6327 case BuiltinType::Id:
6328#include "clang/Basic/AArch64SVEACLETypes.def"
6329#define PPC_VECTOR_TYPE(Name, Id, Size) \
6330 case BuiltinType::Id:
6331#include "clang/Basic/PPCTypes.def"
6332#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6333#include "clang/Basic/RISCVVTypes.def"
6334#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6335#include "clang/Basic/WebAssemblyReferenceTypes.def"
6336#define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6337#define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6338#include "clang/AST/BuiltinTypes.def"
6339 return false;
6340
6341 // We cannot lower out overload sets; they might validly be resolved
6342 // by the call machinery.
6343 case BuiltinType::Overload:
6344 return false;
6345
6346 // Unbridged casts in ARC can be handled in some call positions and
6347 // should be left in place.
6348 case BuiltinType::ARCUnbridgedCast:
6349 return false;
6350
6351 // Pseudo-objects should be converted as soon as possible.
6352 case BuiltinType::PseudoObject:
6353 return true;
6354
6355 // The debugger mode could theoretically but currently does not try
6356 // to resolve unknown-typed arguments based on known parameter types.
6357 case BuiltinType::UnknownAny:
6358 return true;
6359
6360 // These are always invalid as call arguments and should be reported.
6361 case BuiltinType::BoundMember:
6362 case BuiltinType::BuiltinFn:
6363 case BuiltinType::IncompleteMatrixIdx:
6364 case BuiltinType::OMPArraySection:
6365 case BuiltinType::OMPArrayShaping:
6366 case BuiltinType::OMPIterator:
6367 return true;
6368
6369 }
6370 llvm_unreachable("bad builtin type kind");
6371}
6372
6374 // Apply this processing to all the arguments at once instead of
6375 // dying at the first failure.
6376 bool hasInvalid = false;
6377 for (size_t i = 0, e = args.size(); i != e; i++) {
6378 if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
6379 ExprResult result = CheckPlaceholderExpr(args[i]);
6380 if (result.isInvalid()) hasInvalid = true;
6381 else args[i] = result.get();
6382 }
6383 }
6384 return hasInvalid;
6385}
6386
6387/// If a builtin function has a pointer argument with no explicit address
6388/// space, then it should be able to accept a pointer to any address
6389/// space as input. In order to do this, we need to replace the
6390/// standard builtin declaration with one that uses the same address space
6391/// as the call.
6392///
6393/// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6394/// it does not contain any pointer arguments without
6395/// an address space qualifer. Otherwise the rewritten
6396/// FunctionDecl is returned.
6397/// TODO: Handle pointer return types.
6399 FunctionDecl *FDecl,
6400 MultiExprArg ArgExprs) {
6401
6402 QualType DeclType = FDecl->getType();
6403 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
6404
6405 if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) || !FT ||
6406 ArgExprs.size() < FT->getNumParams())
6407 return nullptr;
6408
6409 bool NeedsNewDecl = false;
6410 unsigned i = 0;
6411 SmallVector<QualType, 8> OverloadParams;
6412
6413 for (QualType ParamType : FT->param_types()) {
6414
6415 // Convert array arguments to pointer to simplify type lookup.
6416 ExprResult ArgRes =
6418 if (ArgRes.isInvalid())
6419 return nullptr;
6420 Expr *Arg = ArgRes.get();
6421 QualType ArgType = Arg->getType();
6422 if (!ParamType->isPointerType() || ParamType.hasAddressSpace() ||
6423 !ArgType->isPointerType() ||
6424 !ArgType->getPointeeType().hasAddressSpace() ||
6426 OverloadParams.push_back(ParamType);
6427 continue;
6428 }
6429
6430 QualType PointeeType = ParamType->getPointeeType();
6431 if (PointeeType.hasAddressSpace())
6432 continue;
6433
6434 NeedsNewDecl = true;
6435 LangAS AS = ArgType->getPointeeType().getAddressSpace();
6436
6437 PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
6438 OverloadParams.push_back(Context.getPointerType(PointeeType));
6439 }
6440
6441 if (!NeedsNewDecl)
6442 return nullptr;
6443
6445 EPI.Variadic = FT->isVariadic();
6446 QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
6447 OverloadParams, EPI);
6448 DeclContext *Parent = FDecl->getParent();
6449 FunctionDecl *OverloadDecl = FunctionDecl::Create(
6450 Context, Parent, FDecl->getLocation(), FDecl->getLocation(),
6451 FDecl->getIdentifier(), OverloadTy,
6452 /*TInfo=*/nullptr, SC_Extern, Sema->getCurFPFeatures().isFPConstrained(),
6453 false,
6454 /*hasPrototype=*/true);
6456 FT = cast<FunctionProtoType>(OverloadTy);
6457 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
6458 QualType ParamType = FT->getParamType(i);
6459 ParmVarDecl *Parm =
6460 ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
6461 SourceLocation(), nullptr, ParamType,
6462 /*TInfo=*/nullptr, SC_None, nullptr);
6463 Parm->setScopeInfo(0, i);
6464 Params.push_back(Parm);
6465 }
6466 OverloadDecl->setParams(Params);
6467 Sema->mergeDeclAttributes(OverloadDecl, FDecl);
6468 return OverloadDecl;
6469}
6470
6471static void checkDirectCallValidity(Sema &S, const Expr *Fn,
6472 FunctionDecl *Callee,
6473 MultiExprArg ArgExprs) {
6474 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6475 // similar attributes) really don't like it when functions are called with an
6476 // invalid number of args.
6477 if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
6478 /*PartialOverloading=*/false) &&
6479 !Callee->isVariadic())
6480 return;
6481 if (Callee->getMinRequiredArguments() > ArgExprs.size())
6482 return;
6483
6484 if (const EnableIfAttr *Attr =
6485 S.CheckEnableIf(Callee, Fn->getBeginLoc(), ArgExprs, true)) {
6486 S.Diag(Fn->getBeginLoc(),
6487 isa<CXXMethodDecl>(Callee)
6488 ? diag::err_ovl_no_viable_member_function_in_call
6489 : diag::err_ovl_no_viable_function_in_call)
6490 << Callee << Callee->getSourceRange();
6491 S.Diag(Callee->getLocation(),
6492 diag::note_ovl_candidate_disabled_by_function_cond_attr)
6493 << Attr->getCond()->getSourceRange() << Attr->getMessage();
6494 return;
6495 }
6496}
6497
6499 const UnresolvedMemberExpr *const UME, Sema &S) {
6500
6501 const auto GetFunctionLevelDCIfCXXClass =
6502 [](Sema &S) -> const CXXRecordDecl * {
6503 const DeclContext *const DC = S.getFunctionLevelDeclContext();
6504 if (!DC || !DC->getParent())
6505 return nullptr;
6506
6507 // If the call to some member function was made from within a member
6508 // function body 'M' return return 'M's parent.
6509 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
6510 return MD->getParent()->getCanonicalDecl();
6511 // else the call was made from within a default member initializer of a
6512 // class, so return the class.
6513 if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
6514 return RD->getCanonicalDecl();
6515 return nullptr;
6516 };
6517 // If our DeclContext is neither a member function nor a class (in the
6518 // case of a lambda in a default member initializer), we can't have an
6519 // enclosing 'this'.
6520
6521 const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
6522 if (!CurParentClass)
6523 return false;
6524
6525 // The naming class for implicit member functions call is the class in which
6526 // name lookup starts.
6527 const CXXRecordDecl *const NamingClass =
6529 assert(NamingClass && "Must have naming class even for implicit access");
6530
6531 // If the unresolved member functions were found in a 'naming class' that is
6532 // related (either the same or derived from) to the class that contains the
6533 // member function that itself contained the implicit member access.
6534
6535 return CurParentClass == NamingClass ||
6536 CurParentClass->isDerivedFrom(NamingClass);
6537}
6538
6539static void
6541 Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
6542
6543 if (!UME)
6544 return;
6545
6546 LambdaScopeInfo *const CurLSI = S.getCurLambda();
6547 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6548 // already been captured, or if this is an implicit member function call (if
6549 // it isn't, an attempt to capture 'this' should already have been made).
6550 if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
6551 !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
6552 return;
6553
6554 // Check if the naming class in which the unresolved members were found is
6555 // related (same as or is a base of) to the enclosing class.
6556
6558 return;
6559
6560
6561 DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
6562 // If the enclosing function is not dependent, then this lambda is
6563 // capture ready, so if we can capture this, do so.
6564 if (!EnclosingFunctionCtx->isDependentContext()) {
6565 // If the current lambda and all enclosing lambdas can capture 'this' -
6566 // then go ahead and capture 'this' (since our unresolved overload set
6567 // contains at least one non-static member function).
6568 if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
6569 S.CheckCXXThisCapture(CallLoc);
6570 } else if (S.CurContext->isDependentContext()) {
6571 // ... since this is an implicit member reference, that might potentially
6572 // involve a 'this' capture, mark 'this' for potential capture in
6573 // enclosing lambdas.
6574 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
6575 CurLSI->addPotentialThisCapture(CallLoc);
6576 }
6577}
6578
6579// Once a call is fully resolved, warn for unqualified calls to specific
6580// C++ standard functions, like move and forward.
6582 const CallExpr *Call) {
6583 // We are only checking unary move and forward so exit early here.
6584 if (Call->getNumArgs() != 1)
6585 return;
6586
6587 const Expr *E = Call->getCallee()->IgnoreParenImpCasts();
6588 if (!E || isa<UnresolvedLookupExpr>(E))
6589 return;
6590 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(E);
6591 if (!DRE || !DRE->getLocation().isValid())
6592 return;
6593
6594 if (DRE->getQualifier())
6595 return;
6596
6597 const FunctionDecl *FD = Call->getDirectCallee();
6598 if (!FD)
6599 return;
6600
6601 // Only warn for some functions deemed more frequent or problematic.
6602 unsigned BuiltinID = FD->getBuiltinID();
6603 if (BuiltinID != Builtin::BImove && BuiltinID != Builtin::BIforward)
6604 return;
6605
6606 S.Diag(DRE->getLocation(), diag::warn_unqualified_call_to_std_cast_function)
6608 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6609}
6610
6612 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6613 Expr *ExecConfig) {
6615 BuildCallExpr(Scope, Fn, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6616 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6617 if (Call.isInvalid())
6618 return Call;
6619
6620 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6621 // language modes.
6622 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(Fn);
6623 ULE && ULE->hasExplicitTemplateArgs() &&
6624 ULE->decls_begin() == ULE->decls_end()) {
6626 ? diag::warn_cxx17_compat_adl_only_template_id
6627 : diag::ext_adl_only_template_id)
6628 << ULE->getName();
6629 }
6630
6631 if (LangOpts.OpenMP)
6632 Call = OpenMP().ActOnOpenMPCall(Call, Scope, LParenLoc, ArgExprs, RParenLoc,
6633 ExecConfig);
6634 if (LangOpts.CPlusPlus) {
6635 if (const auto *CE = dyn_cast<CallExpr>(Call.get()))
6637 }
6638 return Call;
6639}
6640
6641/// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6642/// This provides the location of the left/right parens and a list of comma
6643/// locations.
6645 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6646 Expr *ExecConfig, bool IsExecConfig,
6647 bool AllowRecovery) {
6648 // Since this might be a postfix expression, get rid of ParenListExprs.
6650 if (Result.isInvalid()) return ExprError();
6651 Fn = Result.get();
6652
6653 if (CheckArgsForPlaceholders(ArgExprs))
6654 return ExprError();
6655
6656 if (getLangOpts().CPlusPlus) {
6657 // If this is a pseudo-destructor expression, build the call immediately.
6658 if (isa<CXXPseudoDestructorExpr>(Fn)) {
6659 if (!ArgExprs.empty()) {
6660 // Pseudo-destructor calls should not have any arguments.
6661 Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
6663 SourceRange(ArgExprs.front()->getBeginLoc(),
6664 ArgExprs.back()->getEndLoc()));
6665 }
6666
6667 return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
6668 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6669 }
6670 if (Fn->getType() == Context.PseudoObjectTy) {
6671 ExprResult result = CheckPlaceholderExpr(Fn);
6672 if (result.isInvalid()) return ExprError();
6673 Fn = result.get();
6674 }
6675
6676 // Determine whether this is a dependent call inside a C++ template,
6677 // in which case we won't do any semantic analysis now.
6678 if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
6679 if (ExecConfig) {
6681 cast<CallExpr>(ExecConfig), ArgExprs,
6683 RParenLoc, CurFPFeatureOverrides());
6684 } else {
6685
6687 *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
6688 Fn->getBeginLoc());
6689
6690 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6691 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6692 }
6693 }
6694
6695 // Determine whether this is a call to an object (C++ [over.call.object]).
6696 if (Fn->getType()->isRecordType())
6697 return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
6698 RParenLoc);
6699
6700 if (Fn->getType() == Context.UnknownAnyTy) {
6701 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6702 if (result.isInvalid()) return ExprError();
6703 Fn = result.get();
6704 }
6705
6706 if (Fn->getType() == Context.BoundMemberTy) {
6707 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6708 RParenLoc, ExecConfig, IsExecConfig,
6709 AllowRecovery);
6710 }
6711 }
6712
6713 // Check for overloaded calls. This can happen even in C due to extensions.
6714 if (Fn->getType() == Context.OverloadTy) {
6716
6717 // We aren't supposed to apply this logic if there's an '&' involved.
6718 if (!find.HasFormOfMemberPointer) {
6720 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6721 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6722 OverloadExpr *ovl = find.Expression;
6723 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
6725 Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
6726 /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
6727 return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
6728 RParenLoc, ExecConfig, IsExecConfig,
6729 AllowRecovery);
6730 }
6731 }
6732
6733 // If we're directly calling a function, get the appropriate declaration.
6734 if (Fn->getType() == Context.UnknownAnyTy) {
6735 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
6736 if (result.isInvalid()) return ExprError();
6737 Fn = result.get();
6738 }
6739
6740 Expr *NakedFn = Fn->IgnoreParens();
6741
6742 bool CallingNDeclIndirectly = false;
6743 NamedDecl *NDecl = nullptr;
6744 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
6745 if (UnOp->getOpcode() == UO_AddrOf) {
6746 CallingNDeclIndirectly = true;
6747 NakedFn = UnOp->getSubExpr()->IgnoreParens();
6748 }
6749 }
6750
6751 if (auto *DRE = dyn_cast<DeclRefExpr>(NakedFn)) {
6752 NDecl = DRE->getDecl();
6753
6754 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
6755 if (FDecl && FDecl->getBuiltinID()) {
6756 // Rewrite the function decl for this builtin by replacing parameters
6757 // with no explicit address space with the address space of the arguments
6758 // in ArgExprs.
6759 if ((FDecl =
6760 rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
6761 NDecl = FDecl;
6763 Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
6764 SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl,
6765 nullptr, DRE->isNonOdrUse());
6766 }
6767 }
6768 } else if (auto *ME = dyn_cast<MemberExpr>(NakedFn))
6769 NDecl = ME->getMemberDecl();
6770
6771 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
6772 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6773 FD, /*Complain=*/true, Fn->getBeginLoc()))
6774 return ExprError();
6775
6776 checkDirectCallValidity(*this, Fn, FD, ArgExprs);
6777
6778 // If this expression is a call to a builtin function in HIP device
6779 // compilation, allow a pointer-type argument to default address space to be
6780 // passed as a pointer-type parameter to a non-default address space.
6781 // If Arg is declared in the default address space and Param is declared
6782 // in a non-default address space, perform an implicit address space cast to
6783 // the parameter type.
6784 if (getLangOpts().HIP && getLangOpts().CUDAIsDevice && FD &&
6785 FD->getBuiltinID()) {
6786 for (unsigned Idx = 0; Idx < FD->param_size(); ++Idx) {
6787 ParmVarDecl *Param = FD->getParamDecl(Idx);
6788 if (!ArgExprs[Idx] || !Param || !Param->getType()->isPointerType() ||
6789 !ArgExprs[Idx]->getType()->isPointerType())
6790 continue;
6791
6792 auto ParamAS = Param->getType()->getPointeeType().getAddressSpace();
6793 auto ArgTy = ArgExprs[Idx]->getType();
6794 auto ArgPtTy = ArgTy->getPointeeType();
6795 auto ArgAS = ArgPtTy.getAddressSpace();
6796
6797 // Add address space cast if target address spaces are different
6798 bool NeedImplicitASC =
6799 ParamAS != LangAS::Default && // Pointer params in generic AS don't need special handling.
6800 ( ArgAS == LangAS::Default || // We do allow implicit conversion from generic AS
6801 // or from specific AS which has target AS matching that of Param.
6803 if (!NeedImplicitASC)
6804 continue;
6805
6806 // First, ensure that the Arg is an RValue.
6807 if (ArgExprs[Idx]->isGLValue()) {
6808 ArgExprs[Idx] = ImplicitCastExpr::Create(
6809 Context, ArgExprs[Idx]->getType(), CK_NoOp, ArgExprs[Idx],
6810 nullptr, VK_PRValue, FPOptionsOverride());
6811 }
6812
6813 // Construct a new arg type with address space of Param
6814 Qualifiers ArgPtQuals = ArgPtTy.getQualifiers();
6815 ArgPtQuals.setAddressSpace(ParamAS);
6816 auto NewArgPtTy =
6817 Context.getQualifiedType(ArgPtTy.getUnqualifiedType(), ArgPtQuals);
6818 auto NewArgTy =
6820 ArgTy.getQualifiers());
6821
6822 // Finally perform an implicit address space cast
6823 ArgExprs[Idx] = ImpCastExprToType(ArgExprs[Idx], NewArgTy,
6824 CK_AddressSpaceConversion)
6825 .get();
6826 }
6827 }
6828 }
6829
6832 assert(!getLangOpts().CPlusPlus);
6833 assert((Fn->containsErrors() ||
6834 llvm::any_of(ArgExprs,
6835 [](clang::Expr *E) { return E->containsErrors(); })) &&
6836 "should only occur in error-recovery path.");
6837 return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
6838 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
6839 }
6840 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
6841 ExecConfig, IsExecConfig);
6842}
6843
6844/// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6845// with the specified CallArgs
6847 MultiExprArg CallArgs) {
6848 StringRef Name = Context.BuiltinInfo.getName(Id);
6849 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6851 LookupName(R, TUScope, /*AllowBuiltinCreation=*/true);
6852
6853 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
6854 assert(BuiltInDecl && "failed to find builtin declaration");
6855
6856 ExprResult DeclRef =
6857 BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
6858 assert(DeclRef.isUsable() && "Builtin reference cannot fail");
6859
6861 BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
6862
6863 assert(!Call.isInvalid() && "Call to builtin cannot fail!");
6864 return Call.get();
6865}
6866
6867/// Parse a __builtin_astype expression.
6868///
6869/// __builtin_astype( value, dst type )
6870///
6872 SourceLocation BuiltinLoc,
6873 SourceLocation RParenLoc) {
6874 QualType DstTy = GetTypeFromParser(ParsedDestTy);
6875 return BuildAsTypeExpr(E, DstTy, BuiltinLoc, RParenLoc);
6876}
6877
6878/// Create a new AsTypeExpr node (bitcast) from the arguments.
6880 SourceLocation BuiltinLoc,
6881 SourceLocation RParenLoc) {
6884 QualType SrcTy = E->getType();
6885 if (!SrcTy->isDependentType() &&
6886 Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
6887 return ExprError(
6888 Diag(BuiltinLoc, diag::err_invalid_astype_of_different_size)
6889 << DestTy << SrcTy << E->getSourceRange());
6890 return new (Context) AsTypeExpr(E, DestTy, VK, OK, BuiltinLoc, RParenLoc);
6891}
6892
6893/// ActOnConvertVectorExpr - create a new convert-vector expression from the
6894/// provided arguments.
6895///
6896/// __builtin_convertvector( value, dst type )
6897///
6899 SourceLocation BuiltinLoc,
6900 SourceLocation RParenLoc) {
6901 TypeSourceInfo *TInfo;
6902 GetTypeFromParser(ParsedDestTy, &TInfo);
6903 return ConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
6904}
6905
6906/// BuildResolvedCallExpr - Build a call to a resolved expression,
6907/// i.e. an expression not of \p OverloadTy. The expression should
6908/// unary-convert to an expression of function-pointer or
6909/// block-pointer type.
6910///
6911/// \param NDecl the declaration being called, if available
6913 SourceLocation LParenLoc,
6914 ArrayRef<Expr *> Args,
6915 SourceLocation RParenLoc, Expr *Config,
6916 bool IsExecConfig, ADLCallKind UsesADL) {
6917 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
6918 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
6919
6920 // Functions with 'interrupt' attribute cannot be called directly.
6921 if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
6922 Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
6923 return ExprError();
6924 }
6925
6926 // Interrupt handlers don't save off the VFP regs automatically on ARM,
6927 // so there's some risk when calling out to non-interrupt handler functions
6928 // that the callee might not preserve them. This is easy to diagnose here,
6929 // but can be very challenging to debug.
6930 // Likewise, X86 interrupt handlers may only call routines with attribute
6931 // no_caller_saved_registers since there is no efficient way to
6932 // save and restore the non-GPR state.
6933 if (auto *Caller = getCurFunctionDecl()) {
6934 if (Caller->hasAttr<ARMInterruptAttr>()) {
6935 bool VFP = Context.getTargetInfo().hasFeature("vfp");
6936 if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>())) {
6937 Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
6938 if (FDecl)
6939 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6940 }
6941 }
6942 if (Caller->hasAttr<AnyX86InterruptAttr>() ||
6943 Caller->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) {
6944 const TargetInfo &TI = Context.getTargetInfo();
6945 bool HasNonGPRRegisters =
6946 TI.hasFeature("sse") || TI.hasFeature("x87") || TI.hasFeature("mmx");
6947 if (HasNonGPRRegisters &&
6948 (!FDecl || !FDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())) {
6949 Diag(Fn->getExprLoc(), diag::warn_anyx86_excessive_regsave)
6950 << (Caller->hasAttr<AnyX86InterruptAttr>() ? 0 : 1);
6951 if (FDecl)
6952 Diag(FDecl->getLocation(), diag::note_callee_decl) << FDecl;
6953 }
6954 }
6955 }
6956
6957 // Promote the function operand.
6958 // We special-case function promotion here because we only allow promoting
6959 // builtin functions to function pointers in the callee of a call.
6961 QualType ResultTy;
6962 if (BuiltinID &&
6963 Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
6964 // Extract the return type from the (builtin) function pointer type.
6965 // FIXME Several builtins still have setType in
6966 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
6967 // Builtins.td to ensure they are correct before removing setType calls.
6968 QualType FnPtrTy = Context.getPointerType(FDecl->getType());
6969 Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
6970 ResultTy = FDecl->getCallResultType();
6971 } else {
6973 ResultTy = Context.BoolTy;
6974 }
6975 if (Result.isInvalid())
6976 return ExprError();
6977 Fn = Result.get();
6978
6979 // Check for a valid function type, but only if it is not a builtin which
6980 // requires custom type checking. These will be handled by
6981 // CheckBuiltinFunctionCall below just after creation of the call expression.
6982 const FunctionType *FuncT = nullptr;
6983 if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
6984 retry:
6985 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
6986 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
6987 // have type pointer to function".
6988 FuncT = PT->getPointeeType()->getAs<FunctionType>();
6989 if (!FuncT)
6990 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
6991 << Fn->getType() << Fn->getSourceRange());
6992 } else if (const BlockPointerType *BPT =
6993 Fn->getType()->getAs<BlockPointerType>()) {
6994 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
6995 } else {
6996 // Handle calls to expressions of unknown-any type.
6997 if (Fn->getType() == Context.UnknownAnyTy) {
6998 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
6999 if (rewrite.isInvalid())
7000 return ExprError();
7001 Fn = rewrite.get();
7002 goto retry;
7003 }
7004
7005 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
7006 << Fn->getType() << Fn->getSourceRange());
7007 }
7008 }
7009
7010 // Get the number of parameters in the function prototype, if any.
7011 // We will allocate space for max(Args.size(), NumParams) arguments
7012 // in the call expression.
7013 const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
7014 unsigned NumParams = Proto ? Proto->getNumParams() : 0;
7015
7016 CallExpr *TheCall;
7017 if (Config) {
7018 assert(UsesADL == ADLCallKind::NotADL &&
7019 "CUDAKernelCallExpr should not use ADL");
7020 TheCall = CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config),
7021 Args, ResultTy, VK_PRValue, RParenLoc,
7022 CurFPFeatureOverrides(), NumParams);
7023 } else {
7024 TheCall =
7025 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7026 CurFPFeatureOverrides(), NumParams, UsesADL);
7027 }
7028
7030 // Forget about the nulled arguments since typo correction
7031 // do not handle them well.
7032 TheCall->shrinkNumArgs(Args.size());
7033 // C cannot always handle TypoExpr nodes in builtin calls and direct
7034 // function calls as their argument checking don't necessarily handle
7035 // dependent types properly, so make sure any TypoExprs have been
7036 // dealt with.
7038 if (!Result.isUsable()) return ExprError();
7039 CallExpr *TheOldCall = TheCall;
7040 TheCall = dyn_cast<CallExpr>(Result.get());
7041 bool CorrectedTypos = TheCall != TheOldCall;
7042 if (!TheCall) return Result;
7043 Args = llvm::ArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
7044
7045 // A new call expression node was created if some typos were corrected.
7046 // However it may not have been constructed with enough storage. In this
7047 // case, rebuild the node with enough storage. The waste of space is
7048 // immaterial since this only happens when some typos were corrected.
7049 if (CorrectedTypos && Args.size() < NumParams) {
7050 if (Config)
7052 Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_PRValue,
7053 RParenLoc, CurFPFeatureOverrides(), NumParams);
7054 else
7055 TheCall =
7056 CallExpr::Create(Context, Fn, Args, ResultTy, VK_PRValue, RParenLoc,
7057 CurFPFeatureOverrides(), NumParams, UsesADL);
7058 }
7059 // We can now handle the nulled arguments for the default arguments.
7060 TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
7061 }
7062
7063 // Bail out early if calling a builtin with custom type checking.
7064 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
7065 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7066
7067 if (getLangOpts().CUDA) {
7068 if (Config) {
7069 // CUDA: Kernel calls must be to global functions
7070 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
7071 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
7072 << FDecl << Fn->getSourceRange());
7073
7074 // CUDA: Kernel function must have 'void' return type
7075 if (!FuncT->getReturnType()->isVoidType() &&
7076 !FuncT->getReturnType()->getAs<AutoType>() &&
7078 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
7079 << Fn->getType() << Fn->getSourceRange());
7080 } else {
7081 // CUDA: Calls to global functions must be configured
7082 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
7083 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
7084 << FDecl << Fn->getSourceRange());
7085 }
7086 }
7087
7088 // Check for a valid return type
7089 if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
7090 FDecl))
7091 return ExprError();
7092
7093 // We know the result type of the call, set it.
7094 TheCall->setType(FuncT->getCallResultType(Context));
7096
7097 // WebAssembly tables can't be used as arguments.
7098 if (Context.getTargetInfo().getTriple().isWasm()) {
7099 for (const Expr *Arg : Args) {
7100 if (Arg && Arg->getType()->isWebAssemblyTableType()) {
7101 return ExprError(Diag(Arg->getExprLoc(),
7102 diag::err_wasm_table_as_function_parameter));
7103 }
7104 }
7105 }
7106
7107 if (Proto) {
7108 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
7109 IsExecConfig))
7110 return ExprError();
7111 } else {
7112 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
7113
7114 if (FDecl) {
7115 // Check if we have too few/too many template arguments, based
7116 // on our knowledge of the function definition.
7117 const FunctionDecl *Def = nullptr;
7118 if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
7119 Proto = Def->getType()->getAs<FunctionProtoType>();
7120 if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
7121 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
7122 << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
7123 }
7124
7125 // If the function we're calling isn't a function prototype, but we have
7126 // a function prototype from a prior declaratiom, use that prototype.
7127 if (!FDecl->hasPrototype())
7128 Proto = FDecl->getType()->getAs<FunctionProtoType>();
7129 }
7130
7131 // If we still haven't found a prototype to use but there are arguments to
7132 // the call, diagnose this as calling a function without a prototype.
7133 // However, if we found a function declaration, check to see if
7134 // -Wdeprecated-non-prototype was disabled where the function was declared.
7135 // If so, we will silence the diagnostic here on the assumption that this
7136 // interface is intentional and the user knows what they're doing. We will
7137 // also silence the diagnostic if there is a function declaration but it
7138 // was implicitly defined (the user already gets diagnostics about the
7139 // creation of the implicit function declaration, so the additional warning
7140 // is not helpful).
7141 if (!Proto && !Args.empty() &&
7142 (!FDecl || (!FDecl->isImplicit() &&
7143 !Diags.isIgnored(diag::warn_strict_uses_without_prototype,
7144 FDecl->getLocation()))))
7145 Diag(LParenLoc, diag::warn_strict_uses_without_prototype)
7146 << (FDecl != nullptr) << FDecl;
7147
7148 // Promote the arguments (C99 6.5.2.2p6).
7149 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7150 Expr *Arg = Args[i];
7151
7152 if (Proto && i < Proto->getNumParams()) {
7154 Context, Proto->getParamType(i), Proto->isParamConsumed(i));
7155 ExprResult ArgE =
7157 if (ArgE.isInvalid())
7158 return true;
7159
7160 Arg = ArgE.getAs<Expr>();
7161
7162 } else {
7164
7165 if (ArgE.isInvalid())
7166 return true;
7167
7168 Arg = ArgE.getAs<Expr>();
7169 }
7170
7171 if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
7172 diag::err_call_incomplete_argument, Arg))
7173 return ExprError();
7174
7175 TheCall->setArg(i, Arg);
7176 }
7177 TheCall->computeDependence();
7178 }
7179
7180 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
7181 if (!isa<RequiresExprBodyDecl>(CurContext) &&
7182 Method->isImplicitObjectMemberFunction())
7183 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
7184 << Fn->getSourceRange() << 0);
7185
7186 // Check for sentinels
7187 if (NDecl)
7188 DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
7189
7190 // Warn for unions passing across security boundary (CMSE).
7191 if (FuncT != nullptr && FuncT->getCmseNSCallAttr()) {
7192 for (unsigned i = 0, e = Args.size(); i != e; i++) {
7193 if (const auto *RT =
7194 dyn_cast<RecordType>(Args[i]->getType().getCanonicalType())) {
7195 if (RT->getDecl()->isOrContainsUnion())
7196 Diag(Args[i]->getBeginLoc(), diag::warn_cmse_nonsecure_union)
7197 << 0 << i;
7198 }
7199 }
7200 }
7201
7202 // Do special checking on direct calls to functions.
7203 if (FDecl) {
7204 if (CheckFunctionCall(FDecl, TheCall, Proto))
7205 return ExprError();
7206
7207 checkFortifiedBuiltinMemoryFunction(FDecl, TheCall);
7208
7209 if (BuiltinID)
7210 return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
7211 } else if (NDecl) {
7212 if (CheckPointerCall(NDecl, TheCall, Proto))
7213 return ExprError();
7214 } else {
7215 if (CheckOtherCall(TheCall, Proto))
7216 return ExprError();
7217 }
7218
7219 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FDecl);
7220}
7221
7224 SourceLocation RParenLoc, Expr *InitExpr) {
7225 assert(Ty && "ActOnCompoundLiteral(): missing type");
7226 assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
7227
7228 TypeSourceInfo *TInfo;
7229 QualType literalType = GetTypeFromParser(Ty, &TInfo);
7230 if (!TInfo)
7231 TInfo = Context.getTrivialTypeSourceInfo(literalType);
7232
7233 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
7234}
7235
7238 SourceLocation RParenLoc, Expr *LiteralExpr) {
7239 QualType literalType = TInfo->getType();
7240
7241 if (literalType->isArrayType()) {
7243 LParenLoc, Context.getBaseElementType(literalType),
7244 diag::err_array_incomplete_or_sizeless_type,
7245 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7246 return ExprError();
7247 if (literalType->isVariableArrayType()) {
7248 // C23 6.7.10p4: An entity of variable length array type shall not be
7249 // initialized except by an empty initializer.
7250 //
7251 // The C extension warnings are issued from ParseBraceInitializer() and
7252 // do not need to be issued here. However, we continue to issue an error
7253 // in the case there are initializers or we are compiling C++. We allow
7254 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7255 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7256 // FIXME: should we allow this construct in C++ when it makes sense to do
7257 // so?
7258 std::optional<unsigned> NumInits;
7259 if (const auto *ILE = dyn_cast<InitListExpr>(LiteralExpr))
7260 NumInits = ILE->getNumInits();
7261 if ((LangOpts.CPlusPlus || NumInits.value_or(0)) &&
7262 !tryToFixVariablyModifiedVarType(TInfo, literalType, LParenLoc,
7263 diag::err_variable_object_no_init))
7264 return ExprError();
7265 }
7266 } else if (!literalType->isDependentType() &&
7267 RequireCompleteType(LParenLoc, literalType,
7268 diag::err_typecheck_decl_incomplete_type,
7269 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
7270 return ExprError();
7271
7272 InitializedEntity Entity
7276 SourceRange(LParenLoc, RParenLoc),
7277 /*InitList=*/true);
7278 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7279 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
7280 &literalType);
7281 if (Result.isInvalid())
7282 return ExprError();
7283 LiteralExpr = Result.get();
7284
7285 bool isFileScope = !CurContext->isFunctionOrMethod();
7286
7287 // In C, compound literals are l-values for some reason.
7288 // For GCC compatibility, in C++, file-scope array compound literals with
7289 // constant initializers are also l-values, and compound literals are
7290 // otherwise prvalues.
7291 //
7292 // (GCC also treats C++ list-initialized file-scope array prvalues with
7293 // constant initializers as l-values, but that's non-conforming, so we don't
7294 // follow it there.)
7295 //
7296 // FIXME: It would be better to handle the lvalue cases as materializing and
7297 // lifetime-extending a temporary object, but our materialized temporaries
7298 // representation only supports lifetime extension from a variable, not "out
7299 // of thin air".
7300 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7301 // is bound to the result of applying array-to-pointer decay to the compound
7302 // literal.
7303 // FIXME: GCC supports compound literals of reference type, which should
7304 // obviously have a value kind derived from the kind of reference involved.
7305 ExprValueKind VK =
7306 (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
7307 ? VK_PRValue
7308 : VK_LValue;
7309
7310 if (isFileScope)
7311 if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
7312 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7313 Expr *Init = ILE->getInit(i);
7314 ILE->setInit(i, ConstantExpr::Create(Context, Init));
7315 }
7316
7317 auto *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
7318 VK, LiteralExpr, isFileScope);
7319 if (isFileScope) {
7320 if (!LiteralExpr->isTypeDependent() &&
7321 !LiteralExpr->isValueDependent() &&
7322 !literalType->isDependentType()) // C99 6.5.2.5p3
7323 if (CheckForConstantInitializer(LiteralExpr))
7324 return ExprError();
7325 } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
7326 literalType.getAddressSpace() != LangAS::Default) {
7327 // Embedded-C extensions to C99 6.5.2.5:
7328 // "If the compound literal occurs inside the body of a function, the
7329 // type name shall not be qualified by an address-space qualifier."
7330 Diag(LParenLoc, diag::err_compound_literal_with_address_space)
7331 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
7332 return ExprError();
7333 }
7334
7335 if (!isFileScope && !getLangOpts().CPlusPlus) {
7336 // Compound literals that have automatic storage duration are destroyed at
7337 // the end of the scope in C; in C++, they're just temporaries.
7338
7339 // Emit diagnostics if it is or contains a C union type that is non-trivial
7340 // to destruct.
7344
7345 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7346 if (literalType.isDestructedType()) {
7348 ExprCleanupObjects.push_back(E);
7350 }
7351 }
7352
7355 checkNonTrivialCUnionInInitializer(E->getInitializer(),
7356 E->getInitializer()->getExprLoc());
7357
7358 return MaybeBindToTemporary(E);
7359}
7360
7363 SourceLocation RBraceLoc) {
7364 // Only produce each kind of designated initialization diagnostic once.
7365 SourceLocation FirstDesignator;
7366 bool DiagnosedArrayDesignator = false;
7367 bool DiagnosedNestedDesignator = false;
7368 bool DiagnosedMixedDesignator = false;
7369
7370 // Check that any designated initializers are syntactically valid in the
7371 // current language mode.
7372 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7373 if (auto *DIE = dyn_cast<DesignatedInitExpr>(InitArgList[I])) {
7374 if (FirstDesignator.isInvalid())
7375 FirstDesignator = DIE->getBeginLoc();
7376
7377 if (!getLangOpts().CPlusPlus)
7378 break;
7379
7380 if (!DiagnosedNestedDesignator && DIE->size() > 1) {
7381 DiagnosedNestedDesignator = true;
7382 Diag(DIE->getBeginLoc(), diag::ext_designated_init_nested)
7383 << DIE->getDesignatorsSourceRange();
7384 }
7385
7386 for (auto &Desig : DIE->designators()) {
7387 if (!Desig.isFieldDesignator() && !DiagnosedArrayDesignator) {
7388 DiagnosedArrayDesignator = true;
7389 Diag(Desig.getBeginLoc(), diag::ext_designated_init_array)
7390 << Desig.getSourceRange();
7391 }
7392 }
7393
7394 if (!DiagnosedMixedDesignator &&
7395 !isa<DesignatedInitExpr>(InitArgList[0])) {
7396 DiagnosedMixedDesignator = true;
7397 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7398 << DIE->getSourceRange();
7399 Diag(InitArgList[0]->getBeginLoc(), diag::note_designated_init_mixed)
7400 << InitArgList[0]->getSourceRange();
7401 }
7402 } else if (getLangOpts().CPlusPlus && !DiagnosedMixedDesignator &&
7403 isa<DesignatedInitExpr>(InitArgList[0])) {
7404 DiagnosedMixedDesignator = true;
7405 auto *DIE = cast<DesignatedInitExpr>(InitArgList[0]);
7406 Diag(DIE->getBeginLoc(), diag::ext_designated_init_mixed)
7407 << DIE->getSourceRange();
7408 Diag(InitArgList[I]->getBeginLoc(), diag::note_designated_init_mixed)
7409 << InitArgList[I]->getSourceRange();
7410 }
7411 }
7412
7413 if (FirstDesignator.isValid()) {
7414 // Only diagnose designated initiaization as a C++20 extension if we didn't
7415 // already diagnose use of (non-C++20) C99 designator syntax.
7416 if (getLangOpts().CPlusPlus && !DiagnosedArrayDesignator &&
7417 !DiagnosedNestedDesignator && !DiagnosedMixedDesignator) {
7418 Diag(FirstDesignator, getLangOpts().CPlusPlus20
7419 ? diag::warn_cxx17_compat_designated_init
7420 : diag::ext_cxx_designated_init);
7421 } else if (!getLangOpts().CPlusPlus && !getLangOpts().C99) {
7422 Diag(FirstDesignator, diag::ext_designated_init);
7423 }
7424 }
7425
7426 return BuildInitList(LBraceLoc, InitArgList, RBraceLoc);
7427}
7428
7431 SourceLocation RBraceLoc) {
7432 // Semantic analysis for initializers is done by ActOnDeclarator() and
7433 // CheckInitializer() - it requires knowledge of the object being initialized.
7434
7435 // Immediately handle non-overload placeholders. Overloads can be
7436 // resolved contextually, but everything else here can't.
7437 for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
7438 if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
7439 ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
7440
7441 // Ignore failures; dropping the entire initializer list because
7442 // of one failure would be terrible for indexing/etc.
7443 if (result.isInvalid()) continue;
7444
7445 InitArgList[I] = result.get();
7446 }
7447 }
7448
7449 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
7450 RBraceLoc);
7451 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
7452 return E;
7453}
7454
7455/// Do an explicit extend of the given block pointer if we're in ARC.
7457 assert(E.get()->getType()->isBlockPointerType());
7458 assert(E.get()->isPRValue());
7459
7460 // Only do this in an r-value context.
7461 if (!getLangOpts().ObjCAutoRefCount) return;
7462
7464 Context, E.get()->getType(), CK_ARCExtendBlockObject, E.get(),
7465 /*base path*/ nullptr, VK_PRValue, FPOptionsOverride());
7467}
7468
7469/// Prepare a conversion of the given expression to an ObjC object
7470/// pointer type.
7472 QualType type = E.get()->getType();
7473 if (type->isObjCObjectPointerType()) {
7474 return CK_BitCast;
7475 } else if (type->isBlockPointerType()) {
7477 return CK_BlockPointerToObjCPointerCast;
7478 } else {
7479 assert(type->isPointerType());
7480 return CK_CPointerToObjCPointerCast;
7481 }
7482}
7483
7484/// Prepares for a scalar cast, performing all the necessary stages
7485/// except the final cast and returning the kind required.
7487 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7488 // Also, callers should have filtered out the invalid cases with
7489 // pointers. Everything else should be possible.
7490
7491 QualType SrcTy = Src.get()->getType();
7492 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
7493 return CK_NoOp;
7494
7495 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7497 llvm_unreachable("member pointer type in C");
7498
7499 case Type::STK_CPointer:
7502 switch (DestTy->getScalarTypeKind()) {
7503 case Type::STK_CPointer: {
7504 LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
7505 LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
7506 if (SrcAS != DestAS)
7507 return CK_AddressSpaceConversion;
7508 if (Context.hasCvrSimilarType(SrcTy, DestTy))
7509 return CK_NoOp;
7510 return CK_BitCast;
7511 }
7513 return (SrcKind == Type::STK_BlockPointer
7514 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7516 if (SrcKind == Type::STK_ObjCObjectPointer)
7517 return CK_BitCast;
7518 if (SrcKind == Type::STK_CPointer)
7519 return CK_CPointerToObjCPointerCast;
7521 return CK_BlockPointerToObjCPointerCast;
7522 case Type::STK_Bool:
7523 return CK_PointerToBoolean;
7524 case Type::STK_Integral:
7525 return CK_PointerToIntegral;
7526 case Type::STK_Floating:
7531 llvm_unreachable("illegal cast from pointer");
7532 }
7533 llvm_unreachable("Should have returned before this");
7534
7536 switch (DestTy->getScalarTypeKind()) {
7538 return CK_FixedPointCast;
7539 case Type::STK_Bool:
7540 return CK_FixedPointToBoolean;
7541 case Type::STK_Integral:
7542 return CK_FixedPointToIntegral;
7543 case Type::STK_Floating:
7544 return CK_FixedPointToFloating;
7547 Diag(Src.get()->getExprLoc(),
7548 diag::err_unimplemented_conversion_with_fixed_point_type)
7549 << DestTy;
7550 return CK_IntegralCast;
7551 case Type::STK_CPointer:
7555 llvm_unreachable("illegal cast to pointer type");
7556 }
7557 llvm_unreachable("Should have returned before this");
7558
7559 case Type::STK_Bool: // casting from bool is like casting from an integer
7560 case Type::STK_Integral:
7561 switch (DestTy->getScalarTypeKind()) {
7562 case Type::STK_CPointer:
7567 return CK_NullToPointer;
7568 return CK_IntegralToPointer;
7569 case Type::STK_Bool:
7570 return CK_IntegralToBoolean;
7571 case Type::STK_Integral:
7572 return CK_IntegralCast;
7573 case Type::STK_Floating:
7574 return CK_IntegralToFloating;
7576 Src = ImpCastExprToType(Src.get(),
7577 DestTy->castAs<ComplexType>()->getElementType(),
7578 CK_IntegralCast);
7579 return CK_IntegralRealToComplex;
7581 Src = ImpCastExprToType(Src.get(),
7582 DestTy->castAs<ComplexType>()->getElementType(),
7583 CK_IntegralToFloating);
7584 return CK_FloatingRealToComplex;
7586 llvm_unreachable("member pointer type in C");
7588 return CK_IntegralToFixedPoint;
7589 }
7590 llvm_unreachable("Should have returned before this");
7591
7592 case Type::STK_Floating:
7593 switch (DestTy->getScalarTypeKind()) {
7594 case Type::STK_Floating:
7595 return CK_FloatingCast;
7596 case Type::STK_Bool:
7597 return CK_FloatingToBoolean;
7598 case Type::STK_Integral:
7599 return CK_FloatingToIntegral;
7601 Src = ImpCastExprToType(Src.get(),
7602 DestTy->castAs<ComplexType>()->getElementType(),
7603 CK_FloatingCast);
7604 return CK_FloatingRealToComplex;
7606 Src = ImpCastExprToType(Src.get(),
7607 DestTy->castAs<ComplexType>()->getElementType(),
7608 CK_FloatingToIntegral);
7609 return CK_IntegralRealToComplex;
7610 case Type::STK_CPointer:
7613 llvm_unreachable("valid float->pointer cast?");
7615 llvm_unreachable("member pointer type in C");
7617 return CK_FloatingToFixedPoint;
7618 }
7619 llvm_unreachable("Should have returned before this");
7620
7622 switch (DestTy->getScalarTypeKind()) {
7624 return CK_FloatingComplexCast;
7626 return CK_FloatingComplexToIntegralComplex;
7627 case Type::STK_Floating: {
7628 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7629 if (Context.hasSameType(ET, DestTy))
7630 return CK_FloatingComplexToReal;
7631 Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
7632 return CK_FloatingCast;
7633 }
7634 case Type::STK_Bool:
7635 return CK_FloatingComplexToBoolean;
7636 case Type::STK_Integral:
7637 Src = ImpCastExprToType(Src.get(),
7638 SrcTy->castAs<ComplexType>()->getElementType(),
7639 CK_FloatingComplexToReal);
7640 return CK_FloatingToIntegral;
7641 case Type::STK_CPointer:
7644 llvm_unreachable("valid complex float->pointer cast?");
7646 llvm_unreachable("member pointer type in C");
7648 Diag(Src.get()->getExprLoc(),
7649 diag::err_unimplemented_conversion_with_fixed_point_type)
7650 << SrcTy;
7651 return CK_IntegralCast;
7652 }
7653 llvm_unreachable("Should have returned before this");
7654
7656 switch (DestTy->getScalarTypeKind()) {
7658 return CK_IntegralComplexToFloatingComplex;
7660 return CK_IntegralComplexCast;
7661 case Type::STK_Integral: {
7662 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7663 if (Context.hasSameType(ET, DestTy))
7664 return CK_IntegralComplexToReal;
7665 Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
7666 return CK_IntegralCast;
7667 }
7668 case Type::STK_Bool:
7669 return CK_IntegralComplexToBoolean;
7670 case Type::STK_Floating:
7671 Src = ImpCastExprToType(Src.get(),
7672 SrcTy->castAs<ComplexType>()->getElementType(),
7673 CK_IntegralComplexToReal);
7674 return CK_IntegralToFloating;
7675 case Type::STK_CPointer:
7678 llvm_unreachable("valid complex int->pointer cast?");
7680 llvm_unreachable("member pointer type in C");
7682 Diag(Src.get()->getExprLoc(),
7683 diag::err_unimplemented_conversion_with_fixed_point_type)
7684 << SrcTy;
7685 return CK_IntegralCast;
7686 }
7687 llvm_unreachable("Should have returned before this");
7688 }
7689
7690 llvm_unreachable("Unhandled scalar cast");
7691}
7692
7693static bool breakDownVectorType(QualType type, uint64_t &len,
7694 QualType &eltType) {
7695 // Vectors are simple.
7696 if (const VectorType *vecType = type->getAs<VectorType>()) {
7697 len = vecType->getNumElements();
7698 eltType = vecType->getElementType();
7699 assert(eltType->isScalarType());
7700 return true;
7701 }
7702
7703 // We allow lax conversion to and from non-vector types, but only if
7704 // they're real types (i.e. non-complex, non-pointer scalar types).
7705 if (!type->isRealType()) return false;
7706
7707 len = 1;
7708 eltType = type;
7709 return true;
7710}
7711
7712/// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7713/// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7714/// allowed?
7715///
7716/// This will also return false if the two given types do not make sense from
7717/// the perspective of SVE bitcasts.
7719 assert(srcTy->isVectorType() || destTy->isVectorType());
7720
7721 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7722 if (!FirstType->isSVESizelessBuiltinType())
7723 return false;
7724
7725 const auto *VecTy = SecondType->getAs<VectorType>();
7726 return VecTy && VecTy->getVectorKind() == VectorKind::SveFixedLengthData;
7727 };
7728
7729 return ValidScalableConversion(srcTy, destTy) ||
7730 ValidScalableConversion(destTy, srcTy);
7731}
7732
7733/// Are the two types RVV-bitcast-compatible types? I.e. is bitcasting from the
7734/// first RVV type (e.g. an RVV scalable type) to the second type (e.g. an RVV
7735/// VLS type) allowed?
7736///
7737/// This will also return false if the two given types do not make sense from
7738/// the perspective of RVV bitcasts.
7740 assert(srcTy->isVectorType() || destTy->isVectorType());
7741
7742 auto ValidScalableConversion = [](QualType FirstType, QualType SecondType) {
7743 if (!FirstType->isRVVSizelessBuiltinType())
7744 return false;
7745
7746 const auto *VecTy = SecondType->getAs<VectorType>();
7747 return VecTy && VecTy->getVectorKind() == VectorKind::RVVFixedLengthData;
7748 };
7749
7750 return ValidScalableConversion(srcTy, destTy) ||
7751 ValidScalableConversion(destTy, srcTy);
7752}
7753
7754/// Are the two types matrix types and do they have the same dimensions i.e.
7755/// do they have the same number of rows and the same number of columns?
7757 if (!destTy->isMatrixType() || !srcTy->isMatrixType())
7758 return false;
7759
7760 const ConstantMatrixType *matSrcType = srcTy->getAs<ConstantMatrixType>();
7761 const ConstantMatrixType *matDestType = destTy->getAs<ConstantMatrixType>();
7762
7763 return matSrcType->getNumRows() == matDestType->getNumRows() &&
7764 matSrcType->getNumColumns() == matDestType->getNumColumns();
7765}
7766
7768 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7769
7770 uint64_t SrcLen, DestLen;
7771 QualType SrcEltTy, DestEltTy;
7772 if (!breakDownVectorType(SrcTy, SrcLen, SrcEltTy))
7773 return false;
7774 if (!breakDownVectorType(DestTy, DestLen, DestEltTy))
7775 return false;
7776
7777 // ASTContext::getTypeSize will return the size rounded up to a
7778 // power of 2, so instead of using that, we need to use the raw
7779 // element size multiplied by the element count.
7780 uint64_t SrcEltSize = Context.getTypeSize(SrcEltTy);
7781 uint64_t DestEltSize = Context.getTypeSize(DestEltTy);
7782
7783 return (SrcLen * SrcEltSize == DestLen * DestEltSize);
7784}
7785
7786// This returns true if at least one of the types is an altivec vector.
7788 assert((DestTy->isVectorType() || SrcTy->isVectorType()) &&
7789 "expected at least one type to be a vector here");
7790
7791 bool IsSrcTyAltivec =
7792 SrcTy->isVectorType() && ((SrcTy->castAs<VectorType>()->getVectorKind() ==
7794 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7796 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7798
7799 bool IsDestTyAltivec = DestTy->isVectorType() &&
7800 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7802 (DestTy->castAs<VectorType>()->getVectorKind() ==
7804 (DestTy->castAs<VectorType>()->getVectorKind() ==
7806
7807 return (IsSrcTyAltivec || IsDestTyAltivec);
7808}
7809
7810/// Are the two types lax-compatible vector types? That is, given
7811/// that one of them is a vector, do they have equal storage sizes,
7812/// where the storage size is the number of elements times the element
7813/// size?
7814///
7815/// This will also return false if either of the types is neither a
7816/// vector nor a real type.
7818 assert(destTy->isVectorType() || srcTy->isVectorType());
7819
7820 // Disallow lax conversions between scalars and ExtVectors (these
7821 // conversions are allowed for other vector types because common headers
7822 // depend on them). Most scalar OP ExtVector cases are handled by the
7823 // splat path anyway, which does what we want (convert, not bitcast).
7824 // What this rules out for ExtVectors is crazy things like char4*float.
7825 if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
7826 if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
7827
7828 return areVectorTypesSameSize(srcTy, destTy);
7829}
7830
7831/// Is this a legal conversion between two types, one of which is
7832/// known to be a vector type?
7834 assert(destTy->isVectorType() || srcTy->isVectorType());
7835
7836 switch (Context.getLangOpts().getLaxVectorConversions()) {
7838 return false;
7839
7841 if (!srcTy->isIntegralOrEnumerationType()) {
7842 auto *Vec = srcTy->getAs<VectorType>();
7843 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7844 return false;
7845 }
7846 if (!destTy->isIntegralOrEnumerationType()) {
7847 auto *Vec = destTy->getAs<VectorType>();
7848 if (!Vec || !Vec->getElementType()->isIntegralOrEnumerationType())
7849 return false;
7850 }
7851 // OK, integer (vector) -> integer (vector) bitcast.
7852 break;
7853
7855 break;
7856 }
7857
7858 return areLaxCompatibleVectorTypes(srcTy, destTy);
7859}
7860
7862 CastKind &Kind) {
7863 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7864 if (!areMatrixTypesOfTheSameDimension(SrcTy, DestTy)) {
7865 return Diag(R.getBegin(), diag::err_invalid_conversion_between_matrixes)
7866 << DestTy << SrcTy << R;
7867 }
7868 } else if (SrcTy->isMatrixType()) {
7869 return Diag(R.getBegin(),
7870 diag::err_invalid_conversion_between_matrix_and_type)
7871 << SrcTy << DestTy << R;
7872 } else if (DestTy->isMatrixType()) {
7873 return Diag(R.getBegin(),
7874 diag::err_invalid_conversion_between_matrix_and_type)
7875 << DestTy << SrcTy << R;
7876 }
7877
7878 Kind = CK_MatrixCast;
7879 return false;
7880}
7881
7883 CastKind &Kind) {
7884 assert(VectorTy->isVectorType() && "Not a vector type!");
7885
7886 if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
7887 if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
7888 return Diag(R.getBegin(),
7889 Ty->isVectorType() ?
7890 diag::err_invalid_conversion_between_vectors :
7891 diag::err_invalid_conversion_between_vector_and_integer)
7892 << VectorTy << Ty << R;
7893 } else
7894 return Diag(R.getBegin(),
7895 diag::err_invalid_conversion_between_vector_and_scalar)
7896 << VectorTy << Ty << R;
7897
7898 Kind = CK_BitCast;
7899 return false;
7900}
7901
7903 QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
7904
7905 if (DestElemTy == SplattedExpr->getType())
7906 return SplattedExpr;
7907
7908 assert(DestElemTy->isFloatingType() ||
7909 DestElemTy->isIntegralOrEnumerationType());
7910
7911 CastKind CK;
7912 if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
7913 // OpenCL requires that we convert `true` boolean expressions to -1, but
7914 // only when splatting vectors.
7915 if (DestElemTy->isFloatingType()) {
7916 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
7917 // in two steps: boolean to signed integral, then to floating.
7918 ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
7919 CK_BooleanToSignedIntegral);
7920 SplattedExpr = CastExprRes.get();
7921 CK = CK_IntegralToFloating;
7922 } else {
7923 CK = CK_BooleanToSignedIntegral;
7924 }
7925 } else {
7926 ExprResult CastExprRes = SplattedExpr;
7927 CK = PrepareScalarCast(CastExprRes, DestElemTy);
7928 if (CastExprRes.isInvalid())
7929 return ExprError();
7930 SplattedExpr = CastExprRes.get();
7931 }
7932 return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
7933}
7934
7936 Expr *CastExpr, CastKind &Kind) {
7937 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
7938
7939 QualType SrcTy = CastExpr->getType();
7940
7941 // If SrcTy is a VectorType, the total size must match to explicitly cast to
7942 // an ExtVectorType.
7943 // In OpenCL, casts between vectors of different types are not allowed.
7944 // (See OpenCL 6.2).
7945 if (SrcTy->isVectorType()) {
7946 if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
7947 (getLangOpts().OpenCL &&
7948 !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
7949 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
7950 << DestTy << SrcTy << R;
7951 return ExprError();
7952 }
7953 Kind = CK_BitCast;
7954 return CastExpr;
7955 }
7956
7957 // All non-pointer scalars can be cast to ExtVector type. The appropriate
7958 // conversion will take place first from scalar to elt type, and then
7959 // splat from elt type to vector.
7960 if (SrcTy->isPointerType())
7961 return Diag(R.getBegin(),
7962 diag::err_invalid_conversion_between_vector_and_scalar)
7963 << DestTy << SrcTy << R;
7964
7965 Kind = CK_VectorSplat;
7966 return prepareVectorSplat(DestTy, CastExpr);
7967}
7968
7971 Declarator &D, ParsedType &Ty,
7972 SourceLocation RParenLoc, Expr *CastExpr) {
7973 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7974 "ActOnCastExpr(): missing type or expr");
7975
7977 if (D.isInvalidType())
7978 return ExprError();
7979
7980 if (getLangOpts().CPlusPlus) {
7981 // Check that there are no default arguments (C++ only).
7983 } else {
7984 // Make sure any TypoExprs have been dealt with.
7986 if (!Res.isUsable())
7987 return ExprError();
7988 CastExpr = Res.get();
7989 }
7990
7992
7993 QualType castType = castTInfo->getType();
7994 Ty = CreateParsedType(castType, castTInfo);
7995
7996 bool isVectorLiteral = false;
7997
7998 // Check for an altivec or OpenCL literal,
7999 // i.e. all the elements are integer constants.
8000 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
8001 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
8002 if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
8003 && castType->isVectorType() && (PE || PLE)) {
8004 if (PLE && PLE->getNumExprs() == 0) {
8005 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
8006 return ExprError();
8007 }
8008 if (PE || PLE->getNumExprs() == 1) {
8009 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
8010 if (!E->isTypeDependent() && !E->getType()->isVectorType())
8011 isVectorLiteral = true;
8012 }
8013 else
8014 isVectorLiteral = true;
8015 }
8016
8017 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8018 // then handle it as such.
8019 if (isVectorLiteral)
8020 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
8021
8022 // If the Expr being casted is a ParenListExpr, handle it specially.
8023 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8024 // sequence of BinOp comma operators.
8025 if (isa<ParenListExpr>(CastExpr)) {
8027 if (Result.isInvalid()) return ExprError();
8028 CastExpr = Result.get();
8029 }
8030
8031 if (getLangOpts().CPlusPlus && !castType->isVoidType())
8032 Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
8033
8035
8037
8039
8040 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
8041}
8042
8044 SourceLocation RParenLoc, Expr *E,
8045 TypeSourceInfo *TInfo) {
8046 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
8047 "Expected paren or paren list expression");
8048
8049 Expr **exprs;
8050 unsigned numExprs;
8051 Expr *subExpr;
8052 SourceLocation LiteralLParenLoc, LiteralRParenLoc;
8053 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
8054 LiteralLParenLoc = PE->getLParenLoc();
8055 LiteralRParenLoc = PE->getRParenLoc();
8056 exprs = PE->getExprs();
8057 numExprs = PE->getNumExprs();
8058 } else { // isa<ParenExpr> by assertion at function entrance
8059 LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
8060 LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
8061 subExpr = cast<ParenExpr>(E)->getSubExpr();
8062 exprs = &subExpr;
8063 numExprs = 1;
8064 }
8065
8066 QualType Ty = TInfo->getType();
8067 assert(Ty->isVectorType() && "Expected vector type");
8068
8069 SmallVector<Expr *, 8> initExprs;
8070 const VectorType *VTy = Ty->castAs<VectorType>();
8071 unsigned numElems = VTy->getNumElements();
8072
8073 // '(...)' form of vector initialization in AltiVec: the number of
8074 // initializers must be one or must match the size of the vector.
8075 // If a single value is specified in the initializer then it will be
8076 // replicated to all the components of the vector
8078 VTy->getElementType()))
8079 return ExprError();
8081 // The number of initializers must be one or must match the size of the
8082 // vector. If a single value is specified in the initializer then it will
8083 // be replicated to all the components of the vector
8084 if (numExprs == 1) {
8085 QualType ElemTy = VTy->getElementType();
8086 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8087 if (Literal.isInvalid())
8088 return ExprError();
8089 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8090 PrepareScalarCast(Literal, ElemTy));
8091 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8092 }
8093 else if (numExprs < numElems) {
8094 Diag(E->getExprLoc(),
8095 diag::err_incorrect_number_of_vector_initializers);
8096 return ExprError();
8097 }
8098 else
8099 initExprs.append(exprs, exprs + numExprs);
8100 }
8101 else {
8102 // For OpenCL, when the number of initializers is a single value,
8103 // it will be replicated to all components of the vector.
8105 numExprs == 1) {
8106 QualType ElemTy = VTy->getElementType();
8107 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
8108 if (Literal.isInvalid())
8109 return ExprError();
8110 Literal = ImpCastExprToType(Literal.get(), ElemTy,
8111 PrepareScalarCast(Literal, ElemTy));
8112 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
8113 }
8114
8115 initExprs.append(exprs, exprs + numExprs);
8116 }
8117 // FIXME: This means that pretty-printing the final AST will produce curly
8118 // braces instead of the original commas.
8119 InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
8120 initExprs, LiteralRParenLoc);
8121 initE->setType(Ty);
8122 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
8123}
8124
8125/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8126/// the ParenListExpr into a sequence of comma binary operators.
8129 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
8130 if (!E)
8131 return OrigExpr;
8132
8133 ExprResult Result(E->getExpr(0));
8134
8135 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8136 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
8137 E->getExpr(i));
8138
8139 if (Result.isInvalid()) return ExprError();
8140
8141 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
8142}
8143
8146 MultiExprArg Val) {
8147 return ParenListExpr::Create(Context, L, Val, R);
8148}
8149
8150/// Emit a specialized diagnostic when one expression is a null pointer
8151/// constant and the other is not a pointer. Returns true if a diagnostic is
8152/// emitted.
8153bool Sema::DiagnoseConditionalForNull(const Expr *LHSExpr, const Expr *RHSExpr,
8154 SourceLocation QuestionLoc) {
8155 const Expr *NullExpr = LHSExpr;
8156 const Expr *NonPointerExpr = RHSExpr;
8160
8161 if (NullKind == Expr::NPCK_NotNull) {
8162 NullExpr = RHSExpr;
8163 NonPointerExpr = LHSExpr;
8164 NullKind =
8167 }
8168
8169 if (NullKind == Expr::NPCK_NotNull)
8170 return false;
8171
8172 if (NullKind == Expr::NPCK_ZeroExpression)
8173 return false;
8174
8175 if (NullKind == Expr::NPCK_ZeroLiteral) {
8176 // In this case, check to make sure that we got here from a "NULL"
8177 // string in the source code.
8178 NullExpr = NullExpr->IgnoreParenImpCasts();
8179 SourceLocation loc = NullExpr->getExprLoc();
8180 if (!findMacroSpelling(loc, "NULL"))
8181 return false;
8182 }
8183
8184 int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
8185 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
8186 << NonPointerExpr->getType() << DiagType
8187 << NonPointerExpr->getSourceRange();
8188 return true;
8189}
8190
8191/// Return false if the condition expression is valid, true otherwise.
8192static bool checkCondition(Sema &S, const Expr *Cond,
8193 SourceLocation QuestionLoc) {
8194 QualType CondTy = Cond->getType();
8195
8196 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8197 if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
8198 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8199 << CondTy << Cond->getSourceRange();
8200 return true;
8201 }
8202
8203 // C99 6.5.15p2
8204 if (CondTy->isScalarType()) return false;
8205
8206 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
8207 << CondTy << Cond->getSourceRange();
8208 return true;
8209}
8210
8211/// Return false if the NullExpr can be promoted to PointerTy,
8212/// true otherwise.
8214 QualType PointerTy) {
8215 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8216 !NullExpr.get()->isNullPointerConstant(S.Context,
8218 return true;
8219
8220 NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
8221 return false;
8222}
8223
8224/// Checks compatibility between two pointers and return the resulting
8225/// type.
8227 ExprResult &RHS,
8228 SourceLocation Loc) {
8229 QualType LHSTy = LHS.get()->getType();
8230 QualType RHSTy = RHS.get()->getType();
8231
8232 if (S.Context.hasSameType(LHSTy, RHSTy)) {
8233 // Two identical pointers types are always compatible.
8234 return S.Context.getCommonSugaredType(LHSTy, RHSTy);
8235 }
8236
8237 QualType lhptee, rhptee;
8238
8239 // Get the pointee types.
8240 bool IsBlockPointer = false;
8241 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
8242 lhptee = LHSBTy->getPointeeType();
8243 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
8244 IsBlockPointer = true;
8245 } else {
8246 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8247 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8248 }
8249
8250 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8251 // differently qualified versions of compatible types, the result type is
8252 // a pointer to an appropriately qualified version of the composite
8253 // type.
8254
8255 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8256 // clause doesn't make sense for our extensions. E.g. address space 2 should
8257 // be incompatible with address space 3: they may live on different devices or
8258 // anything.
8259 Qualifiers lhQual = lhptee.getQualifiers();
8260 Qualifiers rhQual = rhptee.getQualifiers();
8261
8262 LangAS ResultAddrSpace = LangAS::Default;
8263 LangAS LAddrSpace = lhQual.getAddressSpace();
8264 LangAS RAddrSpace = rhQual.getAddressSpace();
8265
8266 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8267 // spaces is disallowed.
8268 if (lhQual.isAddressSpaceSupersetOf(rhQual))
8269 ResultAddrSpace = LAddrSpace;
8270 else if (rhQual.isAddressSpaceSupersetOf(lhQual))
8271 ResultAddrSpace = RAddrSpace;
8272 else {
8273 S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8274 << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
8275 << RHS.get()->getSourceRange();
8276 return QualType();
8277 }
8278
8279 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
8280 auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
8281 lhQual.removeCVRQualifiers();
8282 rhQual.removeCVRQualifiers();
8283
8284 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8285 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8286 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8287 // qual types are compatible iff
8288 // * corresponded types are compatible
8289 // * CVR qualifiers are equal
8290 // * address spaces are equal
8291 // Thus for conditional operator we merge CVR and address space unqualified
8292 // pointees and if there is a composite type we return a pointer to it with
8293 // merged qualifiers.
8294 LHSCastKind =
8295 LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8296 RHSCastKind =
8297 RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
8298 lhQual.removeAddressSpace();
8299 rhQual.removeAddressSpace();
8300
8301 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
8302 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
8303
8304 QualType CompositeTy = S.Context.mergeTypes(
8305 lhptee, rhptee, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8306 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8307
8308 if (CompositeTy.isNull()) {
8309 // In this situation, we assume void* type. No especially good
8310 // reason, but this is what gcc does, and we do have to pick
8311 // to get a consistent AST.
8312 QualType incompatTy;
8313 incompatTy = S.Context.getPointerType(
8314 S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
8315 LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
8316 RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
8317
8318 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8319 // for casts between types with incompatible address space qualifiers.
8320 // For the following code the compiler produces casts between global and
8321 // local address spaces of the corresponded innermost pointees:
8322 // local int *global *a;
8323 // global int *global *b;
8324 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8325 S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
8326 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8327 << RHS.get()->getSourceRange();
8328
8329 return incompatTy;
8330 }
8331
8332 // The pointer types are compatible.
8333 // In case of OpenCL ResultTy should have the address space qualifier
8334 // which is a superset of address spaces of both the 2nd and the 3rd
8335 // operands of the conditional operator.
8336 QualType ResultTy = [&, ResultAddrSpace]() {
8337 if (S.getLangOpts().OpenCL) {
8338 Qualifiers CompositeQuals = CompositeTy.getQualifiers();
8339 CompositeQuals.setAddressSpace(ResultAddrSpace);
8340 return S.Context
8341 .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
8342 .withCVRQualifiers(MergedCVRQual);
8343 }
8344 return CompositeTy.withCVRQualifiers(MergedCVRQual);
8345 }();
8346 if (IsBlockPointer)
8347 ResultTy = S.Context.getBlockPointerType(ResultTy);
8348 else
8349 ResultTy = S.Context.getPointerType(ResultTy);
8350
8351 LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
8352 RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
8353 return ResultTy;
8354}
8355
8356/// Return the resulting type when the operands are both block pointers.
8358 ExprResult &LHS,
8359 ExprResult &RHS,
8360 SourceLocation Loc) {
8361 QualType LHSTy = LHS.get()->getType();
8362 QualType RHSTy = RHS.get()->getType();
8363
8364 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
8365 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
8367 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8368 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8369 return destType;
8370 }
8371 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
8372 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8373 << RHS.get()->getSourceRange();
8374 return QualType();
8375 }
8376
8377 // We have 2 block pointer types.
8378 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8379}
8380
8381/// Return the resulting type when the operands are both pointers.
8382static QualType
8384 ExprResult &RHS,
8385 SourceLocation Loc) {
8386 // get the pointer types
8387 QualType LHSTy = LHS.get()->getType();
8388 QualType RHSTy = RHS.get()->getType();
8389
8390 // get the "pointed to" types
8391 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8392 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8393
8394 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8395 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
8396 // Figure out necessary qualifiers (C99 6.5.15p6)
8397 QualType destPointee
8398 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8399 QualType destType = S.Context.getPointerType(destPointee);
8400 // Add qualifiers if necessary.
8401 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8402 // Promote to void*.
8403 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8404 return destType;
8405 }
8406 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8407 QualType destPointee
8408 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8409 QualType destType = S.Context.getPointerType(destPointee);
8410 // Add qualifiers if necessary.
8411 RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8412 // Promote to void*.
8413 LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8414 return destType;
8415 }
8416
8417 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
8418}
8419
8420/// Return false if the first expression is not an integer and the second
8421/// expression is not a pointer, true otherwise.
8423 Expr* PointerExpr, SourceLocation Loc,
8424 bool IsIntFirstExpr) {
8425 if (!PointerExpr->getType()->isPointerType() ||
8426 !Int.get()->getType()->isIntegerType())
8427 return false;
8428
8429 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
8430 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
8431
8432 S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
8433 << Expr1->getType() << Expr2->getType()
8434 << Expr1->getSourceRange() << Expr2->getSourceRange();
8435 Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
8436 CK_IntegralToPointer);
8437 return true;
8438}
8439
8440/// Simple conversion between integer and floating point types.
8441///
8442/// Used when handling the OpenCL conditional operator where the
8443/// condition is a vector while the other operands are scalar.
8444///
8445/// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8446/// types are either integer or floating type. Between the two
8447/// operands, the type with the higher rank is defined as the "result
8448/// type". The other operand needs to be promoted to the same type. No
8449/// other type promotion is allowed. We cannot use
8450/// UsualArithmeticConversions() for this purpose, since it always
8451/// promotes promotable types.
8453 ExprResult &RHS,
8454 SourceLocation QuestionLoc) {
8456 if (LHS.isInvalid())
8457 return QualType();
8459 if (RHS.isInvalid())
8460 return QualType();
8461
8462 // For conversion purposes, we ignore any qualifiers.
8463 // For example, "const float" and "float" are equivalent.
8464 QualType LHSType =
8466 QualType RHSType =
8468
8469 if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
8470 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8471 << LHSType << LHS.get()->getSourceRange();
8472 return QualType();
8473 }
8474
8475 if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
8476 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
8477 << RHSType << RHS.get()->getSourceRange();
8478 return QualType();
8479 }
8480
8481 // If both types are identical, no conversion is needed.
8482 if (LHSType == RHSType)
8483 return LHSType;
8484
8485 // Now handle "real" floating types (i.e. float, double, long double).
8486 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
8487 return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
8488 /*IsCompAssign = */ false);
8489
8490 // Finally, we have two differing integer types.
8491 return handleIntegerConversion<doIntegralCast, doIntegralCast>
8492 (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
8493}
8494
8495/// Convert scalar operands to a vector that matches the
8496/// condition in length.
8497///
8498/// Used when handling the OpenCL conditional operator where the
8499/// condition is a vector while the other operands are scalar.
8500///
8501/// We first compute the "result type" for the scalar operands
8502/// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8503/// into a vector of that type where the length matches the condition
8504/// vector type. s6.11.6 requires that the element types of the result
8505/// and the condition must have the same number of bits.
8506static QualType
8508 QualType CondTy, SourceLocation QuestionLoc) {
8509 QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
8510 if (ResTy.isNull()) return QualType();
8511
8512 const VectorType *CV = CondTy->getAs<VectorType>();
8513 assert(CV);
8514
8515 // Determine the vector result type
8516 unsigned NumElements = CV->getNumElements();
8517 QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
8518
8519 // Ensure that all types have the same number of bits
8521 != S.Context.getTypeSize(ResTy)) {
8522 // Since VectorTy is created internally, it does not pretty print
8523 // with an OpenCL name. Instead, we just print a description.
8524 std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
8525 SmallString<64> Str;
8526 llvm::raw_svector_ostream OS(Str);
8527 OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
8528 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8529 << CondTy << OS.str();
8530 return QualType();
8531 }
8532
8533 // Convert operands to the vector result type
8534 LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
8535 RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
8536
8537 return VectorTy;
8538}
8539
8540/// Return false if this is a valid OpenCL condition vector
8542 SourceLocation QuestionLoc) {
8543 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8544 // integral type.
8545 const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
8546 assert(CondTy);
8547 QualType EleTy = CondTy->getElementType();
8548 if (EleTy->isIntegerType()) return false;
8549
8550 S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
8551 << Cond->getType() << Cond->getSourceRange();
8552 return true;
8553}
8554
8555/// Return false if the vector condition type and the vector
8556/// result type are compatible.
8557///
8558/// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8559/// number of elements, and their element types have the same number
8560/// of bits.
8561static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
8562 SourceLocation QuestionLoc) {
8563 const VectorType *CV = CondTy->getAs<VectorType>();
8564 const VectorType *RV = VecResTy->getAs<VectorType>();
8565 assert(CV && RV);
8566
8567 if (CV->getNumElements() != RV->getNumElements()) {
8568 S.Diag(QuestionLoc, diag::err_conditional_vector_size)
8569 << CondTy << VecResTy;
8570 return true;
8571 }
8572
8573 QualType CVE = CV->getElementType();
8574 QualType RVE = RV->getElementType();
8575
8576 if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
8577 S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
8578 << CondTy << VecResTy;
8579 return true;
8580 }
8581
8582 return false;
8583}
8584
8585/// Return the resulting type for the conditional operator in
8586/// OpenCL (aka "ternary selection operator", OpenCL v1.1
8587/// s6.3.i) when the condition is a vector type.
8588static QualType
8590 ExprResult &LHS, ExprResult &RHS,
8591 SourceLocation QuestionLoc) {
8593 if (Cond.isInvalid())
8594 return QualType();
8595 QualType CondTy = Cond.get()->getType();
8596
8597 if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
8598 return QualType();
8599
8600 // If either operand is a vector then find the vector type of the
8601 // result as specified in OpenCL v1.1 s6.3.i.
8602 if (LHS.get()->getType()->isVectorType() ||
8603 RHS.get()->getType()->isVectorType()) {
8604 bool IsBoolVecLang =
8605 !S.getLangOpts().OpenCL && !S.getLangOpts().OpenCLCPlusPlus;
8606 QualType VecResTy =
8607 S.CheckVectorOperands(LHS, RHS, QuestionLoc,
8608 /*isCompAssign*/ false,
8609 /*AllowBothBool*/ true,
8610 /*AllowBoolConversions*/ false,
8611 /*AllowBooleanOperation*/ IsBoolVecLang,
8612 /*ReportInvalid*/ true);
8613 if (VecResTy.isNull())
8614 return QualType();
8615 // The result type must match the condition type as specified in
8616 // OpenCL v1.1 s6.11.6.
8617 if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
8618 return QualType();
8619 return VecResTy;
8620 }
8621
8622 // Both operands are scalar.
8623 return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
8624}
8625
8626/// Return true if the Expr is block type
8627static bool checkBlockType(Sema &S, const Expr *E) {
8628 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
8629 QualType Ty = CE->getCallee()->getType();
8630 if (Ty->isBlockPointerType()) {
8631 S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
8632 return true;
8633 }
8634 }
8635 return false;
8636}
8637
8638/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8639/// In that case, LHS = cond.
8640/// C99 6.5.15
8642 ExprResult &RHS, ExprValueKind &VK,
8643 ExprObjectKind &OK,
8644 SourceLocation QuestionLoc) {
8645
8646 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
8647 if (!LHSResult.isUsable()) return QualType();
8648 LHS = LHSResult;
8649
8650 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
8651 if (!RHSResult.isUsable()) return QualType();
8652 RHS = RHSResult;
8653
8654 // C++ is sufficiently different to merit its own checker.
8655 if (getLangOpts().CPlusPlus)
8656 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
8657
8658 VK = VK_PRValue;
8659 OK = OK_Ordinary;
8660
8662 (Cond.get()->isTypeDependent() || LHS.get()->isTypeDependent() ||
8663 RHS.get()->isTypeDependent())) {
8664 assert(!getLangOpts().CPlusPlus);
8665 assert((Cond.get()->containsErrors() || LHS.get()->containsErrors() ||
8666 RHS.get()->containsErrors()) &&
8667 "should only occur in error-recovery path.");
8668 return Context.DependentTy;
8669 }
8670
8671 // The OpenCL operator with a vector condition is sufficiently
8672 // different to merit its own checker.
8673 if ((getLangOpts().OpenCL && Cond.get()->getType()->isVectorType()) ||
8674 Cond.get()->getType()->isExtVectorType())
8675 return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
8676
8677 // First, check the condition.
8678 Cond = UsualUnaryConversions(Cond.get());
8679 if (Cond.isInvalid())
8680 return QualType();
8681 if (checkCondition(*this, Cond.get(), QuestionLoc))
8682 return QualType();
8683
8684 // Handle vectors.
8685 if (LHS.get()->getType()->isVectorType() ||
8686 RHS.get()->getType()->isVectorType())
8687 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
8688 /*AllowBothBool*/ true,
8689 /*AllowBoolConversions*/ false,
8690 /*AllowBooleanOperation*/ false,
8691 /*ReportInvalid*/ true);
8692
8693 QualType ResTy =
8694 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
8695 if (LHS.isInvalid() || RHS.isInvalid())
8696 return QualType();
8697
8698 // WebAssembly tables are not allowed as conditional LHS or RHS.
8699 QualType LHSTy = LHS.get()->getType();
8700 QualType RHSTy = RHS.get()->getType();
8701 if (LHSTy->isWebAssemblyTableType() || RHSTy->isWebAssemblyTableType()) {
8702 Diag(QuestionLoc, diag::err_wasm_table_conditional_expression)
8703 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8704 return QualType();
8705 }
8706
8707 // Diagnose attempts to convert between __ibm128, __float128 and long double
8708 // where such conversions currently can't be handled.
8709 if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
8710 Diag(QuestionLoc,
8711 diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
8712 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8713 return QualType();
8714 }
8715
8716 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8717 // selection operator (?:).
8718 if (getLangOpts().OpenCL &&
8719 ((int)checkBlockType(*this, LHS.get()) | (int)checkBlockType(*this, RHS.get()))) {
8720 return QualType();
8721 }
8722
8723 // If both operands have arithmetic type, do the usual arithmetic conversions
8724 // to find a common type: C99 6.5.15p3,5.
8725 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
8726 // Disallow invalid arithmetic conversions, such as those between bit-
8727 // precise integers types of different sizes, or between a bit-precise
8728 // integer and another type.
8729 if (ResTy.isNull() && (LHSTy->isBitIntType() || RHSTy->isBitIntType())) {
8730 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8731 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8732 << RHS.get()->getSourceRange();
8733 return QualType();
8734 }
8735
8736 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
8737 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
8738
8739 return ResTy;
8740 }
8741
8742 // If both operands are the same structure or union type, the result is that
8743 // type.
8744 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
8745 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
8746 if (LHSRT->getDecl() == RHSRT->getDecl())
8747 // "If both the operands have structure or union type, the result has
8748 // that type." This implies that CV qualifiers are dropped.
8750 RHSTy.getUnqualifiedType());
8751 // FIXME: Type of conditional expression must be complete in C mode.
8752 }
8753
8754 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8755 // The following || allows only one side to be void (a GCC-ism).
8756 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
8757 QualType ResTy;
8758 if (LHSTy->isVoidType() && RHSTy->isVoidType()) {
8759 ResTy = Context.getCommonSugaredType(LHSTy, RHSTy);
8760 } else if (RHSTy->isVoidType()) {
8761 ResTy = RHSTy;
8762 Diag(RHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8763 << RHS.get()->getSourceRange();
8764 } else {
8765 ResTy = LHSTy;
8766 Diag(LHS.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void)
8767 << LHS.get()->getSourceRange();
8768 }
8769 LHS = ImpCastExprToType(LHS.get(), ResTy, CK_ToVoid);
8770 RHS = ImpCastExprToType(RHS.get(), ResTy, CK_ToVoid);
8771 return ResTy;
8772 }
8773
8774 // C23 6.5.15p7:
8775 // ... if both the second and third operands have nullptr_t type, the
8776 // result also has that type.
8777 if (LHSTy->isNullPtrType() && Context.hasSameType(LHSTy, RHSTy))
8778 return ResTy;
8779
8780 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8781 // the type of the other operand."
8782 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
8783 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
8784
8785 // All objective-c pointer type analysis is done here.
8786 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
8787 QuestionLoc);
8788 if (LHS.isInvalid() || RHS.isInvalid())
8789 return QualType();
8790 if (!compositeType.isNull())
8791 return compositeType;
8792
8793
8794 // Handle block pointer types.
8795 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
8796 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
8797 QuestionLoc);
8798
8799 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8800 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8801 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
8802 QuestionLoc);
8803
8804 // GCC compatibility: soften pointer/integer mismatch. Note that
8805 // null pointers have been filtered out by this point.
8806 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
8807 /*IsIntFirstExpr=*/true))
8808 return RHSTy;
8809 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
8810 /*IsIntFirstExpr=*/false))
8811 return LHSTy;
8812
8813 // Emit a better diagnostic if one of the expressions is a null pointer
8814 // constant and the other is not a pointer type. In this case, the user most
8815 // likely forgot to take the address of the other expression.
8816 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
8817 return QualType();
8818
8819 // Finally, if the LHS and RHS types are canonically the same type, we can
8820 // use the common sugared type.
8821 if (Context.hasSameType(LHSTy, RHSTy))
8822 return Context.getCommonSugaredType(LHSTy, RHSTy);
8823
8824 // Otherwise, the operands are not compatible.
8825 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
8826 << LHSTy << RHSTy << LHS.get()->getSourceRange()
8827 << RHS.get()->getSourceRange();
8828 return QualType();
8829}
8830
8831/// FindCompositeObjCPointerType - Helper method to find composite type of
8832/// two objective-c pointer types of the two input expressions.
8834 SourceLocation QuestionLoc) {
8835 QualType LHSTy = LHS.get()->getType();
8836 QualType RHSTy = RHS.get()->getType();
8837
8838 // Handle things like Class and struct objc_class*. Here we case the result
8839 // to the pseudo-builtin, because that will be implicitly cast back to the
8840 // redefinition type if an attempt is made to access its fields.
8841 if (LHSTy->isObjCClassType() &&
8843 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8844 return LHSTy;
8845 }
8846 if (RHSTy->isObjCClassType() &&
8848 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8849 return RHSTy;
8850 }
8851 // And the same for struct objc_object* / id
8852 if (LHSTy->isObjCIdType() &&
8854 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
8855 return LHSTy;
8856 }
8857 if (RHSTy->isObjCIdType() &&
8859 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
8860 return RHSTy;
8861 }
8862 // And the same for struct objc_selector* / SEL
8863 if (Context.isObjCSelType(LHSTy) &&
8865 RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
8866 return LHSTy;
8867 }
8868 if (Context.isObjCSelType(RHSTy) &&
8870 LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
8871 return RHSTy;
8872 }
8873 // Check constraints for Objective-C object pointers types.
8874 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
8875
8876 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
8877 // Two identical object pointer types are always compatible.
8878 return LHSTy;
8879 }
8880 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
8881 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
8882 QualType compositeType = LHSTy;
8883
8884 // If both operands are interfaces and either operand can be
8885 // assigned to the other, use that type as the composite
8886 // type. This allows
8887 // xxx ? (A*) a : (B*) b
8888 // where B is a subclass of A.
8889 //
8890 // Additionally, as for assignment, if either type is 'id'
8891 // allow silent coercion. Finally, if the types are
8892 // incompatible then make sure to use 'id' as the composite
8893 // type so the result is acceptable for sending messages to.
8894
8895 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
8896 // It could return the composite type.
8897 if (!(compositeType =
8898 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
8899 // Nothing more to do.
8900 } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
8901 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
8902 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
8903 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8904 } else if ((LHSOPT->isObjCQualifiedIdType() ||
8905 RHSOPT->isObjCQualifiedIdType()) &&
8907 true)) {
8908 // Need to handle "id<xx>" explicitly.
8909 // GCC allows qualified id and any Objective-C type to devolve to
8910 // id. Currently localizing to here until clear this should be
8911 // part of ObjCQualifiedIdTypesAreCompatible.
8912 compositeType = Context.getObjCIdType();
8913 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
8914 compositeType = Context.getObjCIdType();
8915 } else {
8916 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
8917 << LHSTy << RHSTy
8918 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8919 QualType incompatTy = Context.getObjCIdType();
8920 LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
8921 RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
8922 return incompatTy;
8923 }
8924 // The object pointer types are compatible.
8925 LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
8926 RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
8927 return compositeType;
8928 }
8929 // Check Objective-C object pointer types and 'void *'
8930 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
8931 if (getLangOpts().ObjCAutoRefCount) {
8932 // ARC forbids the implicit conversion of object pointers to 'void *',
8933 // so these types are not compatible.
8934 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8935 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8936 LHS = RHS = true;
8937 return QualType();
8938 }
8939 QualType lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
8940 QualType rhptee = RHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8941 QualType destPointee
8942 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
8943 QualType destType = Context.getPointerType(destPointee);
8944 // Add qualifiers if necessary.
8945 LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
8946 // Promote to void*.
8947 RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
8948 return destType;
8949 }
8950 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
8951 if (getLangOpts().ObjCAutoRefCount) {
8952 // ARC forbids the implicit conversion of object pointers to 'void *',
8953 // so these types are not compatible.
8954 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
8955 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8956 LHS = RHS = true;
8957 return QualType();
8958 }
8959 QualType lhptee = LHSTy->castAs<ObjCObjectPointerType>()->getPointeeType();
8960 QualType rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
8961 QualType destPointee
8962 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
8963 QualType destType = Context.getPointerType(destPointee);
8964 // Add qualifiers if necessary.
8965 RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
8966 // Promote to void*.
8967 LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
8968 return destType;
8969 }
8970 return QualType();
8971}
8972
8973/// SuggestParentheses - Emit a note with a fixit hint that wraps
8974/// ParenRange in parentheses.
8976 const PartialDiagnostic &Note,
8977 SourceRange ParenRange) {
8978 SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
8979 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8980 EndLoc.isValid()) {
8981 Self.Diag(Loc, Note)
8982 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
8983 << FixItHint::CreateInsertion(EndLoc, ")");
8984 } else {
8985 // We can't display the parentheses, so just show the bare note.
8986 Self.Diag(Loc, Note) << ParenRange;
8987 }
8988}
8989
8991 return BinaryOperator::isAdditiveOp(Opc) ||
8993 BinaryOperator::isShiftOp(Opc) || Opc == BO_And || Opc == BO_Or;
8994 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
8995 // not any of the logical operators. Bitwise-xor is commonly used as a
8996 // logical-xor because there is no logical-xor operator. The logical
8997 // operators, including uses of xor, have a high false positive rate for
8998 // precedence warnings.
8999}
9000
9001/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9002/// expression, either using a built-in or overloaded operator,
9003/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9004/// expression.
9005static bool IsArithmeticBinaryExpr(const Expr *E, BinaryOperatorKind *Opcode,
9006 const Expr **RHSExprs) {
9007 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9008 E = E->IgnoreImpCasts();
9010 E = E->IgnoreImpCasts();
9011 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
9012 E = MTE->getSubExpr();
9013 E = E->IgnoreImpCasts();
9014 }
9015
9016 // Built-in binary operator.
9017 if (const auto *OP = dyn_cast<BinaryOperator>(E);
9018 OP && IsArithmeticOp(OP->getOpcode())) {
9019 *Opcode = OP->getOpcode();
9020 *RHSExprs = OP->getRHS();
9021 return true;
9022 }
9023
9024 // Overloaded operator.
9025 if (const auto *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
9026 if (Call->getNumArgs() != 2)
9027 return false;
9028
9029 // Make sure this is really a binary operator that is safe to pass into
9030 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9031 OverloadedOperatorKind OO = Call->getOperator();
9032 if (OO < OO_Plus || OO > OO_Arrow ||
9033 OO == OO_PlusPlus || OO == OO_MinusMinus)
9034 return false;
9035
9037 if (IsArithmeticOp(OpKind)) {
9038 *Opcode = OpKind;
9039 *RHSExprs = Call->getArg(1);
9040 return true;
9041 }
9042 }
9043
9044 return false;
9045}
9046
9047/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9048/// or is a logical expression such as (x==y) which has int type, but is
9049/// commonly interpreted as boolean.
9050static bool ExprLooksBoolean(const Expr *E) {
9051 E = E->IgnoreParenImpCasts();
9052
9053 if (E->getType()->isBooleanType())
9054 return true;
9055 if (const auto *OP = dyn_cast<BinaryOperator>(E))
9056 return OP->isComparisonOp() || OP->isLogicalOp();
9057 if (const auto *OP = dyn_cast<UnaryOperator>(E))
9058 return OP->getOpcode() == UO_LNot;
9059 if (E->getType()->isPointerType())
9060 return true;
9061 // FIXME: What about overloaded operator calls returning "unspecified boolean
9062 // type"s (commonly pointer-to-members)?
9063
9064 return false;
9065}
9066
9067/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9068/// and binary operator are mixed in a way that suggests the programmer assumed
9069/// the conditional operator has higher precedence, for example:
9070/// "int x = a + someBinaryCondition ? 1 : 2".
9072 Expr *Condition, const Expr *LHSExpr,
9073 const Expr *RHSExpr) {
9074 BinaryOperatorKind CondOpcode;
9075 const Expr *CondRHS;
9076
9077 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
9078 return;
9079 if (!ExprLooksBoolean(CondRHS))
9080 return;
9081
9082 // The condition is an arithmetic binary expression, with a right-
9083 // hand side that looks boolean, so warn.
9084
9085 unsigned DiagID = BinaryOperator::isBitwiseOp(CondOpcode)
9086 ? diag::warn_precedence_bitwise_conditional
9087 : diag::warn_precedence_conditional;
9088
9089 Self.Diag(OpLoc, DiagID)
9090 << Condition->getSourceRange()
9091 << BinaryOperator::getOpcodeStr(CondOpcode);
9092
9094 Self, OpLoc,
9095 Self.PDiag(diag::note_precedence_silence)
9096 << BinaryOperator::getOpcodeStr(CondOpcode),
9097 SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
9098
9099 SuggestParentheses(Self, OpLoc,
9100 Self.PDiag(diag::note_precedence_conditional_first),
9101 SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
9102}
9103
9104/// Compute the nullability of a conditional expression.
9106 QualType LHSTy, QualType RHSTy,
9107 ASTContext &Ctx) {
9108 if (!ResTy->isAnyPointerType())
9109 return ResTy;
9110
9111 auto GetNullability = [](QualType Ty) {
9112 std::optional<NullabilityKind> Kind = Ty->getNullability();
9113 if (Kind) {
9114 // For our purposes, treat _Nullable_result as _Nullable.
9117 return *Kind;
9118 }
9120 };
9121
9122 auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
9123 NullabilityKind MergedKind;
9124
9125 // Compute nullability of a binary conditional expression.
9126 if (IsBin) {
9127 if (LHSKind == NullabilityKind::NonNull)
9128 MergedKind = NullabilityKind::NonNull;
9129 else
9130 MergedKind = RHSKind;
9131 // Compute nullability of a normal conditional expression.
9132 } else {
9133 if (LHSKind == NullabilityKind::Nullable ||
9134 RHSKind == NullabilityKind::Nullable)
9135 MergedKind = NullabilityKind::Nullable;
9136 else if (LHSKind == NullabilityKind::NonNull)
9137 MergedKind = RHSKind;
9138 else if (RHSKind == NullabilityKind::NonNull)
9139 MergedKind = LHSKind;
9140 else
9141 MergedKind = NullabilityKind::Unspecified;
9142 }
9143
9144 // Return if ResTy already has the correct nullability.
9145 if (GetNullability(ResTy) == MergedKind)
9146 return ResTy;
9147
9148 // Strip all nullability from ResTy.
9149 while (ResTy->getNullability())
9150 ResTy = ResTy.getSingleStepDesugaredType(Ctx);
9151
9152 // Create a new AttributedType with the new nullability kind.
9153 auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
9154 return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
9155}
9156
9157/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
9158/// in the case of a the GNU conditional expr extension.
9160 SourceLocation ColonLoc,
9161 Expr *CondExpr, Expr *LHSExpr,
9162 Expr *RHSExpr) {
9164 // C cannot handle TypoExpr nodes in the condition because it
9165 // doesn't handle dependent types properly, so make sure any TypoExprs have
9166 // been dealt with before checking the operands.
9167 ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
9168 ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
9169 ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
9170
9171 if (!CondResult.isUsable())
9172 return ExprError();
9173
9174 if (LHSExpr) {
9175 if (!LHSResult.isUsable())
9176 return ExprError();
9177 }
9178
9179 if (!RHSResult.isUsable())
9180 return ExprError();
9181
9182 CondExpr = CondResult.get();
9183 LHSExpr = LHSResult.get();
9184 RHSExpr = RHSResult.get();
9185 }
9186
9187 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9188 // was the condition.
9189 OpaqueValueExpr *opaqueValue = nullptr;
9190 Expr *commonExpr = nullptr;
9191 if (!LHSExpr) {
9192 commonExpr = CondExpr;
9193 // Lower out placeholder types first. This is important so that we don't
9194 // try to capture a placeholder. This happens in few cases in C++; such
9195 // as Objective-C++'s dictionary subscripting syntax.
9196 if (commonExpr->hasPlaceholderType()) {
9197 ExprResult result = CheckPlaceholderExpr(commonExpr);
9198 if (!result.isUsable()) return ExprError();
9199 commonExpr = result.get();
9200 }
9201 // We usually want to apply unary conversions *before* saving, except
9202 // in the special case of a C++ l-value conditional.
9203 if (!(getLangOpts().CPlusPlus
9204 && !commonExpr->isTypeDependent()
9205 && commonExpr->getValueKind() == RHSExpr->getValueKind()
9206 && commonExpr->isGLValue()
9207 && commonExpr->isOrdinaryOrBitFieldObject()
9208 && RHSExpr->isOrdinaryOrBitFieldObject()
9209 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
9210 ExprResult commonRes = UsualUnaryConversions(commonExpr);
9211 if (commonRes.isInvalid())
9212 return ExprError();
9213 commonExpr = commonRes.get();
9214 }
9215
9216 // If the common expression is a class or array prvalue, materialize it
9217 // so that we can safely refer to it multiple times.
9218 if (commonExpr->isPRValue() && (commonExpr->getType()->isRecordType() ||
9219 commonExpr->getType()->isArrayType())) {
9220 ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
9221 if (MatExpr.isInvalid())
9222 return ExprError();
9223 commonExpr = MatExpr.get();
9224 }
9225
9226 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
9227 commonExpr->getType(),
9228 commonExpr->getValueKind(),
9229 commonExpr->getObjectKind(),
9230 commonExpr);
9231 LHSExpr = CondExpr = opaqueValue;
9232 }
9233
9234 QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
9237 ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
9238 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
9239 VK, OK, QuestionLoc);
9240 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
9241 RHS.isInvalid())
9242 return ExprError();
9243
9244 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
9245 RHS.get());
9246
9247 CheckBoolLikeConversion(Cond.get(), QuestionLoc);
9248
9249 result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
9250 Context);
9251
9252 if (!commonExpr)
9253 return new (Context)
9254 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9255 RHS.get(), result, VK, OK);
9256
9258 commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
9259 ColonLoc, result, VK, OK);
9260}
9261
9262// Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
9264 unsigned FromAttributes = 0, ToAttributes = 0;
9265 if (const auto *FromFn =
9266 dyn_cast<FunctionProtoType>(Context.getCanonicalType(FromType)))
9267 FromAttributes =
9268 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9269 if (const auto *ToFn =
9270 dyn_cast<FunctionProtoType>(Context.getCanonicalType(ToType)))
9271 ToAttributes =
9272 ToFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9273
9274 return FromAttributes != ToAttributes;
9275}
9276
9277// Check if we have a conversion between incompatible cmse function pointer
9278// types, that is, a conversion between a function pointer with the
9279// cmse_nonsecure_call attribute and one without.
9281 QualType ToType) {
9282 if (const auto *ToFn =
9283 dyn_cast<FunctionType>(S.Context.getCanonicalType(ToType))) {
9284 if (const auto *FromFn =
9285 dyn_cast<FunctionType>(S.Context.getCanonicalType(FromType))) {
9286 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
9287 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
9288
9289 return ToEInfo.getCmseNSCall() != FromEInfo.getCmseNSCall();
9290 }
9291 }
9292 return false;
9293}
9294
9295// checkPointerTypesForAssignment - This is a very tricky routine (despite
9296// being closely modeled after the C99 spec:-). The odd characteristic of this
9297// routine is it effectively iqnores the qualifiers on the top level pointee.
9298// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9299// FIXME: add a couple examples in this comment.
9302 SourceLocation Loc) {
9303 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9304 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9305
9306 // get the "pointed to" type (ignoring qualifiers at the top level)
9307 const Type *lhptee, *rhptee;
9308 Qualifiers lhq, rhq;
9309 std::tie(lhptee, lhq) =
9310 cast<PointerType>(LHSType)->getPointeeType().split().asPair();
9311 std::tie(rhptee, rhq) =
9312 cast<PointerType>(RHSType)->getPointeeType().split().asPair();
9313
9315
9316 // C99 6.5.16.1p1: This following citation is common to constraints
9317 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9318 // qualifiers of the type *pointed to* by the right;
9319
9320 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9321 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
9323 // Ignore lifetime for further calculation.
9324 lhq.removeObjCLifetime();
9325 rhq.removeObjCLifetime();
9326 }
9327
9328 if (!lhq.compatiblyIncludes(rhq)) {
9329 // Treat address-space mismatches as fatal.
9330 if (!lhq.isAddressSpaceSupersetOf(rhq))
9332
9333 // It's okay to add or remove GC or lifetime qualifiers when converting to
9334 // and from void*.
9335 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
9338 && (lhptee->isVoidType() || rhptee->isVoidType()))
9339 ; // keep old
9340
9341 // Treat lifetime mismatches as fatal.
9342 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9344
9345 // For GCC/MS compatibility, other qualifier mismatches are treated
9346 // as still compatible in C.
9348 }
9349
9350 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9351 // incomplete type and the other is a pointer to a qualified or unqualified
9352 // version of void...
9353 if (lhptee->isVoidType()) {
9354 if (rhptee->isIncompleteOrObjectType())
9355 return ConvTy;
9356
9357 // As an extension, we allow cast to/from void* to function pointer.
9358 assert(rhptee->isFunctionType());
9360 }
9361
9362 if (rhptee->isVoidType()) {
9363 if (lhptee->isIncompleteOrObjectType())
9364 return ConvTy;
9365
9366 // As an extension, we allow cast to/from void* to function pointer.
9367 assert(lhptee->isFunctionType());
9369 }
9370
9371 if (!S.Diags.isIgnored(
9372 diag::warn_typecheck_convert_incompatible_function_pointer_strict,
9373 Loc) &&
9374 RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType() &&
9375 !S.IsFunctionConversion(RHSType, LHSType, RHSType))
9377
9378 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9379 // unqualified versions of compatible types, ...
9380 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
9381 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
9382 // Check if the pointee types are compatible ignoring the sign.
9383 // We explicitly check for char so that we catch "char" vs
9384 // "unsigned char" on systems where "char" is unsigned.
9385 if (lhptee->isCharType())
9386 ltrans = S.Context.UnsignedCharTy;
9387 else if (lhptee->hasSignedIntegerRepresentation())
9388 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
9389
9390 if (rhptee->isCharType())
9391 rtrans = S.Context.UnsignedCharTy;
9392 else if (rhptee->hasSignedIntegerRepresentation())
9393 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
9394
9395 if (ltrans == rtrans) {
9396 // Types are compatible ignoring the sign. Qualifier incompatibility
9397 // takes priority over sign incompatibility because the sign
9398 // warning can be disabled.
9399 if (ConvTy != Sema::Compatible)
9400 return ConvTy;
9401
9403 }
9404
9405 // If we are a multi-level pointer, it's possible that our issue is simply
9406 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9407 // the eventual target type is the same and the pointers have the same
9408 // level of indirection, this must be the issue.
9409 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
9410 do {
9411 std::tie(lhptee, lhq) =
9412 cast<PointerType>(lhptee)->getPointeeType().split().asPair();
9413 std::tie(rhptee, rhq) =
9414 cast<PointerType>(rhptee)->getPointeeType().split().asPair();
9415
9416 // Inconsistent address spaces at this point is invalid, even if the
9417 // address spaces would be compatible.
9418 // FIXME: This doesn't catch address space mismatches for pointers of
9419 // different nesting levels, like:
9420 // __local int *** a;
9421 // int ** b = a;
9422 // It's not clear how to actually determine when such pointers are
9423 // invalidly incompatible.
9424 if (lhq.getAddressSpace() != rhq.getAddressSpace())
9426
9427 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
9428
9429 if (lhptee == rhptee)
9431 }
9432
9433 // General pointer incompatibility takes priority over qualifiers.
9434 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9437 }
9438 if (!S.getLangOpts().CPlusPlus &&
9439 S.IsFunctionConversion(ltrans, rtrans, ltrans))
9441 if (IsInvalidCmseNSCallConversion(S, ltrans, rtrans))
9443 if (S.IsInvalidSMECallConversion(rtrans, ltrans))
9445 return ConvTy;
9446}
9447
9448/// checkBlockPointerTypesForAssignment - This routine determines whether two
9449/// block pointer types are compatible or whether a block and normal pointer
9450/// are compatible. It is more restrict than comparing two function pointer
9451// types.
9454 QualType RHSType) {
9455 assert(LHSType.isCanonical() && "LHS not canonicalized!");
9456 assert(RHSType.isCanonical() && "RHS not canonicalized!");
9457
9458 QualType lhptee, rhptee;
9459
9460 // get the "pointed to" type (ignoring qualifiers at the top level)
9461 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
9462 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
9463
9464 // In C++, the types have to match exactly.
9465 if (S.getLangOpts().CPlusPlus)
9467
9469
9470 // For blocks we enforce that qualifiers are identical.
9471 Qualifiers LQuals = lhptee.getLocalQualifiers();
9472 Qualifiers RQuals = rhptee.getLocalQualifiers();
9473 if (S.getLangOpts().OpenCL) {
9474 LQuals.removeAddressSpace();
9475 RQuals.removeAddressSpace();
9476 }
9477 if (LQuals != RQuals)
9479
9480 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9481 // assignment.
9482 // The current behavior is similar to C++ lambdas. A block might be
9483 // assigned to a variable iff its return type and parameters are compatible
9484 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9485 // an assignment. Presumably it should behave in way that a function pointer
9486 // assignment does in C, so for each parameter and return type:
9487 // * CVR and address space of LHS should be a superset of CVR and address
9488 // space of RHS.
9489 // * unqualified types should be compatible.
9490 if (S.getLangOpts().OpenCL) {
9492 S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
9493 S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
9495 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9497
9498 return ConvTy;
9499}
9500
9501/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9502/// for assignment compatibility.
9505 QualType RHSType) {
9506 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
9507 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
9508
9509 if (LHSType->isObjCBuiltinType()) {
9510 // Class is not compatible with ObjC object pointers.
9511 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
9512 !RHSType->isObjCQualifiedClassType())
9514 return Sema::Compatible;
9515 }
9516 if (RHSType->isObjCBuiltinType()) {
9517 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9518 !LHSType->isObjCQualifiedClassType())
9520 return Sema::Compatible;
9521 }
9522 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9523 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9524
9525 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
9526 // make an exception for id<P>
9527 !LHSType->isObjCQualifiedIdType())
9529
9530 if (S.Context.typesAreCompatible(LHSType, RHSType))
9531 return Sema::Compatible;
9532 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9535}
9536
9539 QualType LHSType, QualType RHSType) {
9540 // Fake up an opaque expression. We don't actually care about what
9541 // cast operations are required, so if CheckAssignmentConstraints
9542 // adds casts to this they'll be wasted, but fortunately that doesn't
9543 // usually happen on valid code.
9544 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_PRValue);
9545 ExprResult RHSPtr = &RHSExpr;
9546 CastKind K;
9547
9548 return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
9549}
9550
9551/// This helper function returns true if QT is a vector type that has element
9552/// type ElementType.
9553static bool isVector(QualType QT, QualType ElementType) {
9554 if (const VectorType *VT = QT->getAs<VectorType>())
9555 return VT->getElementType().getCanonicalType() == ElementType;
9556 return false;
9557}
9558
9559/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9560/// has code to accommodate several GCC extensions when type checking
9561/// pointers. Here are some objectionable examples that GCC considers warnings:
9562///
9563/// int a, *pint;
9564/// short *pshort;
9565/// struct foo *pfoo;
9566///
9567/// pint = pshort; // warning: assignment from incompatible pointer type
9568/// a = pint; // warning: assignment makes integer from pointer without a cast
9569/// pint = a; // warning: assignment makes pointer from integer without a cast
9570/// pint = pfoo; // warning: assignment from incompatible pointer type
9571///
9572/// As a result, the code for dealing with pointers is more complex than the
9573/// C99 spec dictates.
9574///
9575/// Sets 'Kind' for any result kind except Incompatible.
9578 CastKind &Kind, bool ConvertRHS) {
9579 QualType RHSType = RHS.get()->getType();
9580 QualType OrigLHSType = LHSType;
9581
9582 // Get canonical types. We're not formatting these types, just comparing
9583 // them.
9584 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
9585 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
9586
9587 // Common case: no conversion required.
9588 if (LHSType == RHSType) {
9589 Kind = CK_NoOp;
9590 return Compatible;
9591 }
9592
9593 // If the LHS has an __auto_type, there are no additional type constraints
9594 // to be worried about.
9595 if (const auto *AT = dyn_cast<AutoType>(LHSType)) {
9596 if (AT->isGNUAutoType()) {
9597 Kind = CK_NoOp;
9598 return Compatible;
9599 }
9600 }
9601
9602 // If we have an atomic type, try a non-atomic assignment, then just add an
9603 // atomic qualification step.
9604 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
9606 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
9607 if (result != Compatible)
9608 return result;
9609 if (Kind != CK_NoOp && ConvertRHS)
9610 RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
9611 Kind = CK_NonAtomicToAtomic;
9612 return Compatible;
9613 }
9614
9615 // If the left-hand side is a reference type, then we are in a
9616 // (rare!) case where we've allowed the use of references in C,
9617 // e.g., as a parameter type in a built-in function. In this case,
9618 // just make sure that the type referenced is compatible with the
9619 // right-hand side type. The caller is responsible for adjusting
9620 // LHSType so that the resulting expression does not have reference
9621 // type.
9622 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
9623 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
9624 Kind = CK_LValueBitCast;
9625 return Compatible;
9626 }
9627 return Incompatible;
9628 }
9629
9630 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9631 // to the same ExtVector type.
9632 if (LHSType->isExtVectorType()) {
9633 if (RHSType->isExtVectorType())
9634 return Incompatible;
9635 if (RHSType->isArithmeticType()) {
9636 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9637 if (ConvertRHS)
9638 RHS = prepareVectorSplat(LHSType, RHS.get());
9639 Kind = CK_VectorSplat;
9640 return Compatible;
9641 }
9642 }
9643
9644 // Conversions to or from vector type.
9645 if (LHSType->isVectorType() || RHSType->isVectorType()) {
9646 if (LHSType->isVectorType() && RHSType->isVectorType()) {
9647 // Allow assignments of an AltiVec vector type to an equivalent GCC
9648 // vector type and vice versa
9649 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
9650 Kind = CK_BitCast;
9651 return Compatible;
9652 }
9653
9654 // If we are allowing lax vector conversions, and LHS and RHS are both
9655 // vectors, the total size only needs to be the same. This is a bitcast;
9656 // no bits are changed but the result type is different.
9657 if (isLaxVectorConversion(RHSType, LHSType)) {
9658 // The default for lax vector conversions with Altivec vectors will
9659 // change, so if we are converting between vector types where
9660 // at least one is an Altivec vector, emit a warning.
9661 if (Context.getTargetInfo().getTriple().isPPC() &&
9662 anyAltivecTypes(RHSType, LHSType) &&
9663 !Context.areCompatibleVectorTypes(RHSType, LHSType))
9664 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9665 << RHSType << LHSType;
9666 Kind = CK_BitCast;
9667 return IncompatibleVectors;
9668 }
9669 }
9670
9671 // When the RHS comes from another lax conversion (e.g. binops between
9672 // scalars and vectors) the result is canonicalized as a vector. When the
9673 // LHS is also a vector, the lax is allowed by the condition above. Handle
9674 // the case where LHS is a scalar.
9675 if (LHSType->isScalarType()) {
9676 const VectorType *VecType = RHSType->getAs<VectorType>();
9677 if (VecType && VecType->getNumElements() == 1 &&
9678 isLaxVectorConversion(RHSType, LHSType)) {
9679 if (Context.getTargetInfo().getTriple().isPPC() &&
9681 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9683 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9684 << RHSType << LHSType;
9685 ExprResult *VecExpr = &RHS;
9686 *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
9687 Kind = CK_BitCast;
9688 return Compatible;
9689 }
9690 }
9691
9692 // Allow assignments between fixed-length and sizeless SVE vectors.
9693 if ((LHSType->isSVESizelessBuiltinType() && RHSType->isVectorType()) ||
9694 (LHSType->isVectorType() && RHSType->isSVESizelessBuiltinType()))
9695 if (Context.areCompatibleSveTypes(LHSType, RHSType) ||
9696 Context.areLaxCompatibleSveTypes(LHSType, RHSType)) {
9697 Kind = CK_BitCast;
9698 return Compatible;
9699 }
9700
9701 // Allow assignments between fixed-length and sizeless RVV vectors.
9702 if ((LHSType->isRVVSizelessBuiltinType() && RHSType->isVectorType()) ||
9703 (LHSType->isVectorType() && RHSType->isRVVSizelessBuiltinType())) {
9704 if (Context.areCompatibleRVVTypes(LHSType, RHSType) ||
9705 Context.areLaxCompatibleRVVTypes(LHSType, RHSType)) {
9706 Kind = CK_BitCast;
9707 return Compatible;
9708 }
9709 }
9710
9711 return Incompatible;
9712 }
9713
9714 // Diagnose attempts to convert between __ibm128, __float128 and long double
9715 // where such conversions currently can't be handled.
9716 if (unsupportedTypeConversion(*this, LHSType, RHSType))
9717 return Incompatible;
9718
9719 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9720 // discards the imaginary part.
9721 if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
9722 !LHSType->getAs<ComplexType>())
9723 return Incompatible;
9724
9725 // Arithmetic conversions.
9726 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
9727 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
9728 if (ConvertRHS)
9729 Kind = PrepareScalarCast(RHS, LHSType);
9730 return Compatible;
9731 }
9732
9733 // Conversions to normal pointers.
9734 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
9735 // U* -> T*
9736 if (isa<PointerType>(RHSType)) {
9737 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9738 LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
9739 if (AddrSpaceL != AddrSpaceR)
9740 Kind = CK_AddressSpaceConversion;
9741 else if (Context.hasCvrSimilarType(RHSType, LHSType))
9742 Kind = CK_NoOp;
9743 else
9744 Kind = CK_BitCast;
9745 return checkPointerTypesForAssignment(*this, LHSType, RHSType,
9746 RHS.get()->getBeginLoc());
9747 }
9748
9749 // int -> T*
9750 if (RHSType->isIntegerType()) {
9751 Kind = CK_IntegralToPointer; // FIXME: null?
9752 return IntToPointer;
9753 }
9754
9755 // C pointers are not compatible with ObjC object pointers,
9756 // with two exceptions:
9757 if (isa<ObjCObjectPointerType>(RHSType)) {
9758 // - conversions to void*
9759 if (LHSPointer->getPointeeType()->isVoidType()) {
9760 Kind = CK_BitCast;
9761 return Compatible;
9762 }
9763
9764 // - conversions from 'Class' to the redefinition type
9765 if (RHSType->isObjCClassType() &&
9766 Context.hasSameType(LHSType,
9768 Kind = CK_BitCast;
9769 return Compatible;
9770 }
9771
9772 Kind = CK_BitCast;
9773 return IncompatiblePointer;
9774 }
9775
9776 // U^ -> void*
9777 if (RHSType->getAs<BlockPointerType>()) {
9778 if (LHSPointer->getPointeeType()->isVoidType()) {
9779 LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
9780 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9781 ->getPointeeType()
9782 .getAddressSpace();
9783 Kind =
9784 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9785 return Compatible;
9786 }
9787 }
9788
9789 return Incompatible;
9790 }
9791
9792 // Conversions to block pointers.
9793 if (isa<BlockPointerType>(LHSType)) {
9794 // U^ -> T^
9795 if (RHSType->isBlockPointerType()) {
9796 LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
9797 ->getPointeeType()
9798 .getAddressSpace();
9799 LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
9800 ->getPointeeType()
9801 .getAddressSpace();
9802 Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
9803 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
9804 }
9805
9806 // int or null -> T^
9807 if (RHSType->isIntegerType()) {
9808 Kind = CK_IntegralToPointer; // FIXME: null
9809 return IntToBlockPointer;
9810 }
9811
9812 // id -> T^
9813 if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
9814 Kind = CK_AnyPointerToBlockPointerCast;
9815 return Compatible;
9816 }
9817
9818 // void* -> T^
9819 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
9820 if (RHSPT->getPointeeType()->isVoidType()) {
9821 Kind = CK_AnyPointerToBlockPointerCast;
9822 return Compatible;
9823 }
9824
9825 return Incompatible;
9826 }
9827
9828 // Conversions to Objective-C pointers.
9829 if (isa<ObjCObjectPointerType>(LHSType)) {
9830 // A* -> B*
9831 if (RHSType->isObjCObjectPointerType()) {
9832 Kind = CK_BitCast;
9834 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
9835 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9836 result == Compatible &&
9837 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
9838 result = IncompatibleObjCWeakRef;
9839 return result;
9840 }
9841
9842 // int or null -> A*
9843 if (RHSType->isIntegerType()) {
9844 Kind = CK_IntegralToPointer; // FIXME: null
9845 return IntToPointer;
9846 }
9847
9848 // In general, C pointers are not compatible with ObjC object pointers,
9849 // with two exceptions:
9850 if (isa<PointerType>(RHSType)) {
9851 Kind = CK_CPointerToObjCPointerCast;
9852
9853 // - conversions from 'void*'
9854 if (RHSType->isVoidPointerType()) {
9855 return Compatible;
9856 }
9857
9858 // - conversions to 'Class' from its redefinition type
9859 if (LHSType->isObjCClassType() &&
9860 Context.hasSameType(RHSType,
9862 return Compatible;
9863 }
9864
9865 return IncompatiblePointer;
9866 }
9867
9868 // Only under strict condition T^ is compatible with an Objective-C pointer.
9869 if (RHSType->isBlockPointerType() &&
9871 if (ConvertRHS)
9873 Kind = CK_BlockPointerToObjCPointerCast;
9874 return Compatible;
9875 }
9876
9877 return Incompatible;
9878 }
9879
9880 // Conversion to nullptr_t (C23 only)
9881 if (getLangOpts().C23 && LHSType->isNullPtrType() &&
9884 // null -> nullptr_t
9885 Kind = CK_NullToPointer;
9886 return Compatible;
9887 }
9888
9889 // Conversions from pointers that are not covered by the above.
9890 if (isa<PointerType>(RHSType)) {
9891 // T* -> _Bool
9892 if (LHSType == Context.BoolTy) {
9893 Kind = CK_PointerToBoolean;
9894 return Compatible;
9895 }
9896
9897 // T* -> int
9898 if (LHSType->isIntegerType()) {
9899 Kind = CK_PointerToIntegral;
9900 return PointerToInt;
9901 }
9902
9903 return Incompatible;
9904 }
9905
9906 // Conversions from Objective-C pointers that are not covered by the above.
9907 if (isa<ObjCObjectPointerType>(RHSType)) {
9908 // T* -> _Bool
9909 if (LHSType == Context.BoolTy) {
9910 Kind = CK_PointerToBoolean;
9911 return Compatible;
9912 }
9913
9914 // T* -> int
9915 if (LHSType->isIntegerType()) {
9916 Kind = CK_PointerToIntegral;
9917 return PointerToInt;
9918 }
9919
9920 return Incompatible;
9921 }
9922
9923 // struct A -> struct B
9924 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
9925 if (Context.typesAreCompatible(LHSType, RHSType)) {
9926 Kind = CK_NoOp;
9927 return Compatible;
9928 }
9929 }
9930
9931 if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
9932 Kind = CK_IntToOCLSampler;
9933 return Compatible;
9934 }
9935
9936 return Incompatible;
9937}
9938
9939/// Constructs a transparent union from an expression that is
9940/// used to initialize the transparent union.
9942 ExprResult &EResult, QualType UnionType,
9943 FieldDecl *Field) {
9944 // Build an initializer list that designates the appropriate member
9945 // of the transparent union.
9946 Expr *E = EResult.get();
9948 E, SourceLocation());
9949 Initializer->setType(UnionType);
9950 Initializer->setInitializedFieldInUnion(Field);
9951
9952 // Build a compound literal constructing a value of the transparent
9953 // union type from this initializer list.
9954 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
9955 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9956 VK_PRValue, Initializer, false);
9957}
9958
9961 ExprResult &RHS) {
9962 QualType RHSType = RHS.get()->getType();
9963
9964 // If the ArgType is a Union type, we want to handle a potential
9965 // transparent_union GCC extension.
9966 const RecordType *UT = ArgType->getAsUnionType();
9967 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
9968 return Incompatible;
9969
9970 // The field to initialize within the transparent union.
9971 RecordDecl *UD = UT->getDecl();
9972 FieldDecl *InitField = nullptr;
9973 // It's compatible if the expression matches any of the fields.
9974 for (auto *it : UD->fields()) {
9975 if (it->getType()->isPointerType()) {
9976 // If the transparent union contains a pointer type, we allow:
9977 // 1) void pointer
9978 // 2) null pointer constant
9979 if (RHSType->isPointerType())
9980 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
9981 RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
9982 InitField = it;
9983 break;
9984 }
9985
9988 RHS = ImpCastExprToType(RHS.get(), it->getType(),
9989 CK_NullToPointer);
9990 InitField = it;
9991 break;
9992 }
9993 }
9994
9995 CastKind Kind;
9996 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
9997 == Compatible) {
9998 RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
9999 InitField = it;
10000 break;
10001 }
10002 }
10003
10004 if (!InitField)
10005 return Incompatible;
10006
10007 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
10008 return Compatible;
10009}
10010
10013 bool Diagnose,
10014 bool DiagnoseCFAudited,
10015 bool ConvertRHS) {
10016 // We need to be able to tell the caller whether we diagnosed a problem, if
10017 // they ask us to issue diagnostics.
10018 assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
10019
10020 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10021 // we can't avoid *all* modifications at the moment, so we need some somewhere
10022 // to put the updated value.
10023 ExprResult LocalRHS = CallerRHS;
10024 ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
10025
10026 if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
10027 if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
10028 if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
10029 !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
10030 Diag(RHS.get()->getExprLoc(),
10031 diag::warn_noderef_to_dereferenceable_pointer)
10032 << RHS.get()->getSourceRange();
10033 }
10034 }
10035 }
10036
10037 if (getLangOpts().CPlusPlus) {
10038 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
10039 // C++ 5.17p3: If the left operand is not of class type, the
10040 // expression is implicitly converted (C++ 4) to the
10041 // cv-unqualified type of the left operand.
10042 QualType RHSType = RHS.get()->getType();
10043 if (Diagnose) {
10044 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10045 AA_Assigning);
10046 } else {
10049 /*SuppressUserConversions=*/false,
10050 AllowedExplicit::None,
10051 /*InOverloadResolution=*/false,
10052 /*CStyle=*/false,
10053 /*AllowObjCWritebackConversion=*/false);
10054 if (ICS.isFailure())
10055 return Incompatible;
10056 RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
10057 ICS, AA_Assigning);
10058 }
10059 if (RHS.isInvalid())
10060 return Incompatible;
10062 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10063 !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
10064 result = IncompatibleObjCWeakRef;
10065 return result;
10066 }
10067
10068 // FIXME: Currently, we fall through and treat C++ classes like C
10069 // structures.
10070 // FIXME: We also fall through for atomics; not sure what should
10071 // happen there, though.
10072 } else if (RHS.get()->getType() == Context.OverloadTy) {
10073 // As a set of extensions to C, we support overloading on functions. These
10074 // functions need to be resolved here.
10075 DeclAccessPair DAP;
10077 RHS.get(), LHSType, /*Complain=*/false, DAP))
10078 RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
10079 else
10080 return Incompatible;
10081 }
10082
10083 // This check seems unnatural, however it is necessary to ensure the proper
10084 // conversion of functions/arrays. If the conversion were done for all
10085 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10086 // expressions that suppress this implicit conversion (&, sizeof). This needs
10087 // to happen before we check for null pointer conversions because C does not
10088 // undergo the same implicit conversions as C++ does above (by the calls to
10089 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10090 // lvalue to rvalue cast before checking for null pointer constraints. This
10091 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10092 //
10093 // Suppress this for references: C++ 8.5.3p5.
10094 if (!LHSType->isReferenceType()) {
10095 // FIXME: We potentially allocate here even if ConvertRHS is false.
10097 if (RHS.isInvalid())
10098 return Incompatible;
10099 }
10100
10101 // The constraints are expressed in terms of the atomic, qualified, or
10102 // unqualified type of the LHS.
10103 QualType LHSTypeAfterConversion = LHSType.getAtomicUnqualifiedType();
10104
10105 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10106 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10107 if ((LHSTypeAfterConversion->isPointerType() ||
10108 LHSTypeAfterConversion->isObjCObjectPointerType() ||
10109 LHSTypeAfterConversion->isBlockPointerType()) &&
10110 ((getLangOpts().C23 && RHS.get()->getType()->isNullPtrType()) ||
10113 if (Diagnose || ConvertRHS) {
10114 CastKind Kind;
10115 CXXCastPath Path;
10116 CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
10117 /*IgnoreBaseAccess=*/false, Diagnose);
10118 if (ConvertRHS)
10119 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_PRValue, &Path);
10120 }
10121 return Compatible;
10122 }
10123 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10124 // unqualified bool, and the right operand is a pointer or its type is
10125 // nullptr_t.
10126 if (getLangOpts().C23 && LHSType->isBooleanType() &&
10127 RHS.get()->getType()->isNullPtrType()) {
10128 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10129 // only handles nullptr -> _Bool due to needing an extra conversion
10130 // step.
10131 // We model this by converting from nullptr -> void * and then let the
10132 // conversion from void * -> _Bool happen naturally.
10133 if (Diagnose || ConvertRHS) {
10134 CastKind Kind;
10135 CXXCastPath Path;
10136 CheckPointerConversion(RHS.get(), Context.VoidPtrTy, Kind, Path,
10137 /*IgnoreBaseAccess=*/false, Diagnose);
10138 if (ConvertRHS)
10139 RHS = ImpCastExprToType(RHS.get(), Context.VoidPtrTy, Kind, VK_PRValue,
10140 &Path);
10141 }
10142 }
10143
10144 // OpenCL queue_t type assignment.
10145 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10147 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10148 return Compatible;
10149 }
10150
10151 CastKind Kind;
10153 CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
10154
10155 // C99 6.5.16.1p2: The value of the right operand is converted to the
10156 // type of the assignment expression.
10157 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10158 // so that we can use references in built-in functions even in C.
10159 // The getNonReferenceType() call makes sure that the resulting expression
10160 // does not have reference type.
10161 if (result != Incompatible && RHS.get()->getType() != LHSType) {
10163 Expr *E = RHS.get();
10164
10165 // Check for various Objective-C errors. If we are not reporting
10166 // diagnostics and just checking for errors, e.g., during overload
10167 // resolution, return Incompatible to indicate the failure.
10168 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10171 DiagnoseCFAudited) != ACR_okay) {
10172 if (!Diagnose)
10173 return Incompatible;
10174 }
10175 if (getLangOpts().ObjC &&
10177 E->getType(), E, Diagnose) ||
10178 CheckConversionToObjCLiteral(LHSType, E, Diagnose))) {
10179 if (!Diagnose)
10180 return Incompatible;
10181 // Replace the expression with a corrected version and continue so we
10182 // can find further errors.
10183 RHS = E;
10184 return Compatible;
10185 }
10186
10187 if (ConvertRHS)
10188 RHS = ImpCastExprToType(E, Ty, Kind);
10189 }
10190
10191 return result;
10192}
10193
10194namespace {
10195/// The original operand to an operator, prior to the application of the usual
10196/// arithmetic conversions and converting the arguments of a builtin operator
10197/// candidate.
10198struct OriginalOperand {
10199 explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
10200 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
10201 Op = MTE->getSubExpr();
10202 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
10203 Op = BTE->getSubExpr();
10204 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
10205 Orig = ICE->getSubExprAsWritten();
10206 Conversion = ICE->getConversionFunction();
10207 }
10208 }
10209
10210 QualType getType() const { return Orig->getType(); }
10211
10212 Expr *Orig;
10213 NamedDecl *Conversion;
10214};
10215}
10216
10218 ExprResult &RHS) {
10219 OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
10220
10221 Diag(Loc, diag::err_typecheck_invalid_operands)
10222 << OrigLHS.getType() << OrigRHS.getType()
10223 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10224
10225 // If a user-defined conversion was applied to either of the operands prior
10226 // to applying the built-in operator rules, tell the user about it.
10227 if (OrigLHS.Conversion) {
10228 Diag(OrigLHS.Conversion->getLocation(),
10229 diag::note_typecheck_invalid_operands_converted)
10230 << 0 << LHS.get()->getType();
10231 }
10232 if (OrigRHS.Conversion) {
10233 Diag(OrigRHS.Conversion->getLocation(),
10234 diag::note_typecheck_invalid_operands_converted)
10235 << 1 << RHS.get()->getType();
10236 }
10237
10238 return QualType();
10239}
10240
10241// Diagnose cases where a scalar was implicitly converted to a vector and
10242// diagnose the underlying types. Otherwise, diagnose the error
10243// as invalid vector logical operands for non-C++ cases.
10245 ExprResult &RHS) {
10246 QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
10247 QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
10248
10249 bool LHSNatVec = LHSType->isVectorType();
10250 bool RHSNatVec = RHSType->isVectorType();
10251
10252 if (!(LHSNatVec && RHSNatVec)) {
10253 Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
10254 Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
10255 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10256 << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
10257 << Vector->getSourceRange();
10258 return QualType();
10259 }
10260
10261 Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
10262 << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
10263 << RHS.get()->getSourceRange();
10264
10265 return QualType();
10266}
10267
10268/// Try to convert a value of non-vector type to a vector type by converting
10269/// the type to the element type of the vector and then performing a splat.
10270/// If the language is OpenCL, we only use conversions that promote scalar
10271/// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10272/// for float->int.
10273///
10274/// OpenCL V2.0 6.2.6.p2:
10275/// An error shall occur if any scalar operand type has greater rank
10276/// than the type of the vector element.
10277///
10278/// \param scalar - if non-null, actually perform the conversions
10279/// \return true if the operation fails (but without diagnosing the failure)
10281 QualType scalarTy,
10282 QualType vectorEltTy,
10283 QualType vectorTy,
10284 unsigned &DiagID) {
10285 // The conversion to apply to the scalar before splatting it,
10286 // if necessary.
10287 CastKind scalarCast = CK_NoOp;
10288
10289 if (vectorEltTy->isIntegralType(S.Context)) {
10290 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10291 (scalarTy->isIntegerType() &&
10292 S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
10293 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10294 return true;
10295 }
10296 if (!scalarTy->isIntegralType(S.Context))
10297 return true;
10298 scalarCast = CK_IntegralCast;
10299 } else if (vectorEltTy->isRealFloatingType()) {
10300 if (scalarTy->isRealFloatingType()) {
10301 if (S.getLangOpts().OpenCL &&
10302 S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
10303 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10304 return true;
10305 }
10306 scalarCast = CK_FloatingCast;
10307 }
10308 else if (scalarTy->isIntegralType(S.Context))
10309 scalarCast = CK_IntegralToFloating;
10310 else
10311 return true;
10312 } else {
10313 return true;
10314 }
10315
10316 // Adjust scalar if desired.
10317 if (scalar) {
10318 if (scalarCast != CK_NoOp)
10319 *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
10320 *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
10321 }
10322 return false;
10323}
10324
10325/// Convert vector E to a vector with the same number of elements but different
10326/// element type.
10327static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
10328 const auto *VecTy = E->getType()->getAs<VectorType>();
10329 assert(VecTy && "Expression E must be a vector");
10330 QualType NewVecTy =
10331 VecTy->isExtVectorType()
10332 ? S.Context.getExtVectorType(ElementType, VecTy->getNumElements())
10333 : S.Context.getVectorType(ElementType, VecTy->getNumElements(),
10334 VecTy->getVectorKind());
10335
10336 // Look through the implicit cast. Return the subexpression if its type is
10337 // NewVecTy.
10338 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10339 if (ICE->getSubExpr()->getType() == NewVecTy)
10340 return ICE->getSubExpr();
10341
10342 auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
10343 return S.ImpCastExprToType(E, NewVecTy, Cast);
10344}
10345
10346/// Test if a (constant) integer Int can be casted to another integer type
10347/// IntTy without losing precision.
10349 QualType OtherIntTy) {
10350 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10351
10352 // Reject cases where the value of the Int is unknown as that would
10353 // possibly cause truncation, but accept cases where the scalar can be
10354 // demoted without loss of precision.
10355 Expr::EvalResult EVResult;
10356 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10357 int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
10358 bool IntSigned = IntTy->hasSignedIntegerRepresentation();
10359 bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
10360
10361 if (CstInt) {
10362 // If the scalar is constant and is of a higher order and has more active
10363 // bits that the vector element type, reject it.
10364 llvm::APSInt Result = EVResult.Val.getInt();
10365 unsigned NumBits = IntSigned
10366 ? (Result.isNegative() ? Result.getSignificantBits()
10367 : Result.getActiveBits())
10368 : Result.getActiveBits();
10369 if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
10370 return true;
10371
10372 // If the signedness of the scalar type and the vector element type
10373 // differs and the number of bits is greater than that of the vector
10374 // element reject it.
10375 return (IntSigned != OtherIntSigned &&
10376 NumBits > S.Context.getIntWidth(OtherIntTy));
10377 }
10378
10379 // Reject cases where the value of the scalar is not constant and it's
10380 // order is greater than that of the vector element type.
10381 return (Order < 0);
10382}
10383
10384/// Test if a (constant) integer Int can be casted to floating point type
10385/// FloatTy without losing precision.
10387 QualType FloatTy) {
10388 QualType IntTy = Int->get()->getType().getUnqualifiedType();
10389
10390 // Determine if the integer constant can be expressed as a floating point
10391 // number of the appropriate type.
10392 Expr::EvalResult EVResult;
10393 bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
10394
10395 uint64_t Bits = 0;
10396 if (CstInt) {
10397 // Reject constants that would be truncated if they were converted to
10398 // the floating point type. Test by simple to/from conversion.
10399 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10400 // could be avoided if there was a convertFromAPInt method
10401 // which could signal back if implicit truncation occurred.
10402 llvm::APSInt Result = EVResult.Val.getInt();
10403 llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
10404 Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
10405 llvm::APFloat::rmTowardZero);
10406 llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
10408 bool Ignored = false;
10409 Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
10410 &Ignored);
10411 if (Result != ConvertBack)
10412 return true;
10413 } else {
10414 // Reject types that cannot be fully encoded into the mantissa of
10415 // the float.
10416 Bits = S.Context.getTypeSize(IntTy);
10417 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10418 S.Context.getFloatTypeSemantics(FloatTy));
10419 if (Bits > FloatPrec)
10420 return true;
10421 }
10422
10423 return false;
10424}
10425
10426/// Attempt to convert and splat Scalar into a vector whose types matches
10427/// Vector following GCC conversion rules. The rule is that implicit
10428/// conversion can occur when Scalar can be casted to match Vector's element
10429/// type without causing truncation of Scalar.
10431 ExprResult *Vector) {
10432 QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
10433 QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
10434 QualType VectorEltTy;
10435
10436 if (const auto *VT = VectorTy->getAs<VectorType>()) {
10437 assert(!isa<ExtVectorType>(VT) &&
10438 "ExtVectorTypes should not be handled here!");
10439 VectorEltTy = VT->getElementType();
10440 } else if (VectorTy->isSveVLSBuiltinType()) {
10441 VectorEltTy =
10442 VectorTy->castAs<BuiltinType>()->getSveEltType(S.getASTContext());
10443 } else {
10444 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10445 }
10446
10447 // Reject cases where the vector element type or the scalar element type are
10448 // not integral or floating point types.
10449 if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
10450 return true;
10451
10452 // The conversion to apply to the scalar before splatting it,
10453 // if necessary.
10454 CastKind ScalarCast = CK_NoOp;
10455
10456 // Accept cases where the vector elements are integers and the scalar is
10457 // an integer.
10458 // FIXME: Notionally if the scalar was a floating point value with a precise
10459 // integral representation, we could cast it to an appropriate integer
10460 // type and then perform the rest of the checks here. GCC will perform
10461 // this conversion in some cases as determined by the input language.
10462 // We should accept it on a language independent basis.
10463 if (VectorEltTy->isIntegralType(S.Context) &&
10464 ScalarTy->isIntegralType(S.Context) &&
10465 S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
10466
10467 if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
10468 return true;
10469
10470 ScalarCast = CK_IntegralCast;
10471 } else if (VectorEltTy->isIntegralType(S.Context) &&
10472 ScalarTy->isRealFloatingType()) {
10473 if (S.Context.getTypeSize(VectorEltTy) == S.Context.getTypeSize(ScalarTy))
10474 ScalarCast = CK_FloatingToIntegral;
10475 else
10476 return true;
10477 } else if (VectorEltTy->isRealFloatingType()) {
10478 if (ScalarTy->isRealFloatingType()) {
10479
10480 // Reject cases where the scalar type is not a constant and has a higher
10481 // Order than the vector element type.
10482 llvm::APFloat Result(0.0);
10483
10484 // Determine whether this is a constant scalar. In the event that the
10485 // value is dependent (and thus cannot be evaluated by the constant
10486 // evaluator), skip the evaluation. This will then diagnose once the
10487 // expression is instantiated.
10488 bool CstScalar = Scalar->get()->isValueDependent() ||
10489 Scalar->get()->EvaluateAsFloat(Result, S.Context);
10490 int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
10491 if (!CstScalar && Order < 0)
10492 return true;
10493
10494 // If the scalar cannot be safely casted to the vector element type,
10495 // reject it.
10496 if (CstScalar) {
10497 bool Truncated = false;
10498 Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
10499 llvm::APFloat::rmNearestTiesToEven, &Truncated);
10500 if (Truncated)
10501 return true;
10502 }
10503
10504 ScalarCast = CK_FloatingCast;
10505 } else if (ScalarTy->isIntegralType(S.Context)) {
10506 if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
10507 return true;
10508
10509 ScalarCast = CK_IntegralToFloating;
10510 } else
10511 return true;
10512 } else if (ScalarTy->isEnumeralType())
10513 return true;
10514
10515 // Adjust scalar if desired.
10516 if (ScalarCast != CK_NoOp)
10517 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
10518 *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
10519 return false;
10520}
10521
10523 SourceLocation Loc, bool IsCompAssign,
10524 bool AllowBothBool,
10525 bool AllowBoolConversions,
10526 bool AllowBoolOperation,
10527 bool ReportInvalid) {
10528 if (!IsCompAssign) {
10530 if (LHS.isInvalid())
10531 return QualType();
10532 }
10534 if (RHS.isInvalid())
10535 return QualType();
10536
10537 // For conversion purposes, we ignore any qualifiers.
10538 // For example, "const float" and "float" are equivalent.
10539 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10540 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10541
10542 const VectorType *LHSVecType = LHSType->getAs<VectorType>();
10543 const VectorType *RHSVecType = RHSType->getAs<VectorType>();
10544 assert(LHSVecType || RHSVecType);
10545
10546 // AltiVec-style "vector bool op vector bool" combinations are allowed
10547 // for some operators but not others.
10548 if (!AllowBothBool && LHSVecType &&
10549 LHSVecType->getVectorKind() == VectorKind::AltiVecBool && RHSVecType &&
10550 RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
10551 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10552
10553 // This operation may not be performed on boolean vectors.
10554 if (!AllowBoolOperation &&
10555 (LHSType->isExtVectorBoolType() || RHSType->isExtVectorBoolType()))
10556 return ReportInvalid ? InvalidOperands(Loc, LHS, RHS) : QualType();
10557
10558 // If the vector types are identical, return.
10559 if (Context.hasSameType(LHSType, RHSType))
10560 return Context.getCommonSugaredType(LHSType, RHSType);
10561
10562 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10563 if (LHSVecType && RHSVecType &&
10564 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
10565 if (isa<ExtVectorType>(LHSVecType)) {
10566 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10567 return LHSType;
10568 }
10569
10570 if (!IsCompAssign)
10571 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10572 return RHSType;
10573 }
10574
10575 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10576 // can be mixed, with the result being the non-bool type. The non-bool
10577 // operand must have integer element type.
10578 if (AllowBoolConversions && LHSVecType && RHSVecType &&
10579 LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
10580 (Context.getTypeSize(LHSVecType->getElementType()) ==
10581 Context.getTypeSize(RHSVecType->getElementType()))) {
10582 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10583 LHSVecType->getElementType()->isIntegerType() &&
10584 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10585 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10586 return LHSType;
10587 }
10588 if (!IsCompAssign &&
10589 LHSVecType->getVectorKind() == VectorKind::AltiVecBool &&
10590 RHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10591 RHSVecType->getElementType()->isIntegerType()) {
10592 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10593 return RHSType;
10594 }
10595 }
10596
10597 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
10598 // invalid since the ambiguity can affect the ABI.
10599 auto IsSveRVVConversion = [](QualType FirstType, QualType SecondType,
10600 unsigned &SVEorRVV) {
10601 const VectorType *VecType = SecondType->getAs<VectorType>();
10602 SVEorRVV = 0;
10603 if (FirstType->isSizelessBuiltinType() && VecType) {
10606 return true;
10609 SVEorRVV = 1;
10610 return true;
10611 }
10612 }
10613
10614 return false;
10615 };
10616
10617 unsigned SVEorRVV;
10618 if (IsSveRVVConversion(LHSType, RHSType, SVEorRVV) ||
10619 IsSveRVVConversion(RHSType, LHSType, SVEorRVV)) {
10620 Diag(Loc, diag::err_typecheck_sve_rvv_ambiguous)
10621 << SVEorRVV << LHSType << RHSType;
10622 return QualType();
10623 }
10624
10625 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
10626 // invalid since the ambiguity can affect the ABI.
10627 auto IsSveRVVGnuConversion = [](QualType FirstType, QualType SecondType,
10628 unsigned &SVEorRVV) {
10629 const VectorType *FirstVecType = FirstType->getAs<VectorType>();
10630 const VectorType *SecondVecType = SecondType->getAs<VectorType>();
10631
10632 SVEorRVV = 0;
10633 if (FirstVecType && SecondVecType) {
10634 if (FirstVecType->getVectorKind() == VectorKind::Generic) {
10635 if (SecondVecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10636 SecondVecType->getVectorKind() ==
10638 return true;
10639 if (SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10640 SecondVecType->getVectorKind() == VectorKind::RVVFixedLengthMask) {
10641 SVEorRVV = 1;
10642 return true;
10643 }
10644 }
10645 return false;
10646 }
10647
10648 if (SecondVecType &&
10649 SecondVecType->getVectorKind() == VectorKind::Generic) {
10650 if (FirstType->isSVESizelessBuiltinType())
10651 return true;
10652 if (FirstType->isRVVSizelessBuiltinType()) {
10653 SVEorRVV = 1;
10654 return true;
10655 }
10656 }
10657
10658 return false;
10659 };
10660
10661 if (IsSveRVVGnuConversion(LHSType, RHSType, SVEorRVV) ||
10662 IsSveRVVGnuConversion(RHSType, LHSType, SVEorRVV)) {
10663 Diag(Loc, diag::err_typecheck_sve_rvv_gnu_ambiguous)
10664 << SVEorRVV << LHSType << RHSType;
10665 return QualType();
10666 }
10667
10668 // If there's a vector type and a scalar, try to convert the scalar to
10669 // the vector element type and splat.
10670 unsigned DiagID = diag::err_typecheck_vector_not_convertable;
10671 if (!RHSVecType) {
10672 if (isa<ExtVectorType>(LHSVecType)) {
10673 if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
10674 LHSVecType->getElementType(), LHSType,
10675 DiagID))
10676 return LHSType;
10677 } else {
10678 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10679 return LHSType;
10680 }
10681 }
10682 if (!LHSVecType) {
10683 if (isa<ExtVectorType>(RHSVecType)) {
10684 if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
10685 LHSType, RHSVecType->getElementType(),
10686 RHSType, DiagID))
10687 return RHSType;
10688 } else {
10689 if (LHS.get()->isLValue() ||
10690 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10691 return RHSType;
10692 }
10693 }
10694
10695 // FIXME: The code below also handles conversion between vectors and
10696 // non-scalars, we should break this down into fine grained specific checks
10697 // and emit proper diagnostics.
10698 QualType VecType = LHSVecType ? LHSType : RHSType;
10699 const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
10700 QualType OtherType = LHSVecType ? RHSType : LHSType;
10701 ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
10702 if (isLaxVectorConversion(OtherType, VecType)) {
10703 if (Context.getTargetInfo().getTriple().isPPC() &&
10704 anyAltivecTypes(RHSType, LHSType) &&
10705 !Context.areCompatibleVectorTypes(RHSType, LHSType))
10706 Diag(Loc, diag::warn_deprecated_lax_vec_conv_all) << RHSType << LHSType;
10707 // If we're allowing lax vector conversions, only the total (data) size
10708 // needs to be the same. For non compound assignment, if one of the types is
10709 // scalar, the result is always the vector type.
10710 if (!IsCompAssign) {
10711 *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
10712 return VecType;
10713 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10714 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10715 // type. Note that this is already done by non-compound assignments in
10716 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10717 // <1 x T> -> T. The result is also a vector type.
10718 } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
10719 (OtherType->isScalarType() && VT->getNumElements() == 1)) {
10720 ExprResult *RHSExpr = &RHS;
10721 *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
10722 return VecType;
10723 }
10724 }
10725
10726 // Okay, the expression is invalid.
10727
10728 // If there's a non-vector, non-real operand, diagnose that.
10729 if ((!RHSVecType && !RHSType->isRealType()) ||
10730 (!LHSVecType && !LHSType->isRealType())) {
10731 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10732 << LHSType << RHSType
10733 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10734 return QualType();
10735 }
10736
10737 // OpenCL V1.1 6.2.6.p1:
10738 // If the operands are of more than one vector type, then an error shall
10739 // occur. Implicit conversions between vector types are not permitted, per
10740 // section 6.2.1.
10741 if (getLangOpts().OpenCL &&
10742 RHSVecType && isa<ExtVectorType>(RHSVecType) &&
10743 LHSVecType && isa<ExtVectorType>(LHSVecType)) {
10744 Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
10745 << RHSType;
10746 return QualType();
10747 }
10748
10749
10750 // If there is a vector type that is not a ExtVector and a scalar, we reach
10751 // this point if scalar could not be converted to the vector's element type
10752 // without truncation.
10753 if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
10754 (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
10755 QualType Scalar = LHSVecType ? RHSType : LHSType;
10756 QualType Vector = LHSVecType ? LHSType : RHSType;
10757 unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
10758 Diag(Loc,
10759 diag::err_typecheck_vector_not_convertable_implict_truncation)
10760 << ScalarOrVector << Scalar << Vector;
10761
10762 return QualType();
10763 }
10764
10765 // Otherwise, use the generic diagnostic.
10766 Diag(Loc, DiagID)
10767 << LHSType << RHSType
10768 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10769 return QualType();
10770}
10771
10773 SourceLocation Loc,
10774 bool IsCompAssign,
10775 ArithConvKind OperationKind) {
10776 if (!IsCompAssign) {
10778 if (LHS.isInvalid())
10779 return QualType();
10780 }
10782 if (RHS.isInvalid())
10783 return QualType();
10784
10785 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
10786 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
10787
10788 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
10789 const BuiltinType *RHSBuiltinTy = RHSType->getAs<BuiltinType>();
10790
10791 unsigned DiagID = diag::err_typecheck_invalid_operands;
10792 if ((OperationKind == ACK_Arithmetic) &&
10793 ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
10794 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool()))) {
10795 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10796 << RHS.get()->getSourceRange();
10797 return QualType();
10798 }
10799
10800 if (Context.hasSameType(LHSType, RHSType))
10801 return LHSType;
10802
10803 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10804 if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
10805 return LHSType;
10806 }
10807 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10808 if (LHS.get()->isLValue() ||
10809 !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
10810 return RHSType;
10811 }
10812
10813 if ((!LHSType->isSveVLSBuiltinType() && !LHSType->isRealType()) ||
10814 (!RHSType->isSveVLSBuiltinType() && !RHSType->isRealType())) {
10815 Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
10816 << LHSType << RHSType << LHS.get()->getSourceRange()
10817 << RHS.get()->getSourceRange();
10818 return QualType();
10819 }
10820
10821 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
10822 Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
10823 Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC) {
10824 Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
10825 << LHSType << RHSType << LHS.get()->getSourceRange()
10826 << RHS.get()->getSourceRange();
10827 return QualType();
10828 }
10829
10830 if (LHSType->isSveVLSBuiltinType() || RHSType->isSveVLSBuiltinType()) {
10831 QualType Scalar = LHSType->isSveVLSBuiltinType() ? RHSType : LHSType;
10832 QualType Vector = LHSType->isSveVLSBuiltinType() ? LHSType : RHSType;
10833 bool ScalarOrVector =
10834 LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType();
10835
10836 Diag(Loc, diag::err_typecheck_vector_not_convertable_implict_truncation)
10837 << ScalarOrVector << Scalar << Vector;
10838
10839 return QualType();
10840 }
10841
10842 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
10843 << RHS.get()->getSourceRange();
10844 return QualType();
10845}
10846
10847// checkArithmeticNull - Detect when a NULL constant is used improperly in an
10848// expression. These are mainly cases where the null pointer is used as an
10849// integer instead of a pointer.
10851 SourceLocation Loc, bool IsCompare) {
10852 // The canonical way to check for a GNU null is with isNullPointerConstant,
10853 // but we use a bit of a hack here for speed; this is a relatively
10854 // hot path, and isNullPointerConstant is slow.
10855 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
10856 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
10857
10858 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
10859
10860 // Avoid analyzing cases where the result will either be invalid (and
10861 // diagnosed as such) or entirely valid and not something to warn about.
10862 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
10863 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
10864 return;
10865
10866 // Comparison operations would not make sense with a null pointer no matter
10867 // what the other expression is.
10868 if (!IsCompare) {
10869 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
10870 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
10871 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
10872 return;
10873 }
10874
10875 // The rest of the operations only make sense with a null pointer
10876 // if the other expression is a pointer.
10877 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
10878 NonNullType->canDecayToPointerType())
10879 return;
10880
10881 S.Diag(Loc, diag::warn_null_in_comparison_operation)
10882 << LHSNull /* LHS is NULL */ << NonNullType
10883 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10884}
10885
10887 SourceLocation Loc) {
10888 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
10889 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
10890 if (!LUE || !RUE)
10891 return;
10892 if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
10893 RUE->getKind() != UETT_SizeOf)
10894 return;
10895
10896 const Expr *LHSArg = LUE->getArgumentExpr()->IgnoreParens();
10897 QualType LHSTy = LHSArg->getType();
10898 QualType RHSTy;
10899
10900 if (RUE->isArgumentType())
10901 RHSTy = RUE->getArgumentType().getNonReferenceType();
10902 else
10903 RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
10904
10905 if (LHSTy->isPointerType() && !RHSTy->isPointerType()) {
10906 if (!S.Context.hasSameUnqualifiedType(LHSTy->getPointeeType(), RHSTy))
10907 return;
10908
10909 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10910 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10911 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10912 S.Diag(LHSArgDecl->getLocation(), diag::note_pointer_declared_here)
10913 << LHSArgDecl;
10914 }
10915 } else if (const auto *ArrayTy = S.Context.getAsArrayType(LHSTy)) {
10916 QualType ArrayElemTy = ArrayTy->getElementType();
10917 if (ArrayElemTy != S.Context.getBaseElementType(ArrayTy) ||
10918 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10919 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10920 S.Context.getTypeSize(ArrayElemTy) == S.Context.getTypeSize(RHSTy))
10921 return;
10922 S.Diag(Loc, diag::warn_division_sizeof_array)
10923 << LHSArg->getSourceRange() << ArrayElemTy << RHSTy;
10924 if (const auto *DRE = dyn_cast<DeclRefExpr>(LHSArg)) {
10925 if (const ValueDecl *LHSArgDecl = DRE->getDecl())
10926 S.Diag(LHSArgDecl->getLocation(), diag::note_array_declared_here)
10927 << LHSArgDecl;
10928 }
10929
10930 S.Diag(Loc, diag::note_precedence_silence) << RHS;
10931 }
10932}
10933
10935 ExprResult &RHS,
10936 SourceLocation Loc, bool IsDiv) {
10937 // Check for division/remainder by zero.
10938 Expr::EvalResult RHSValue;
10939 if (!RHS.get()->isValueDependent() &&
10940 RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
10941 RHSValue.Val.getInt() == 0)
10942 S.DiagRuntimeBehavior(Loc, RHS.get(),
10943 S.PDiag(diag::warn_remainder_division_by_zero)
10944 << IsDiv << RHS.get()->getSourceRange());
10945}
10946
10948 SourceLocation Loc,
10949 bool IsCompAssign, bool IsDiv) {
10950 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10951
10952 QualType LHSTy = LHS.get()->getType();
10953 QualType RHSTy = RHS.get()->getType();
10954 if (LHSTy->isVectorType() || RHSTy->isVectorType())
10955 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10956 /*AllowBothBool*/ getLangOpts().AltiVec,
10957 /*AllowBoolConversions*/ false,
10958 /*AllowBooleanOperation*/ false,
10959 /*ReportInvalid*/ true);
10960 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10961 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10963 if (!IsDiv &&
10964 (LHSTy->isConstantMatrixType() || RHSTy->isConstantMatrixType()))
10965 return CheckMatrixMultiplyOperands(LHS, RHS, Loc, IsCompAssign);
10966 // For division, only matrix-by-scalar is supported. Other combinations with
10967 // matrix types are invalid.
10968 if (IsDiv && LHSTy->isConstantMatrixType() && RHSTy->isArithmeticType())
10969 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
10970
10972 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
10973 if (LHS.isInvalid() || RHS.isInvalid())
10974 return QualType();
10975
10976
10977 if (compType.isNull() || !compType->isArithmeticType())
10978 return InvalidOperands(Loc, LHS, RHS);
10979 if (IsDiv) {
10980 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
10981 DiagnoseDivisionSizeofPointerOrArray(*this, LHS.get(), RHS.get(), Loc);
10982 }
10983 return compType;
10984}
10985
10987 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10988 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
10989
10990 if (LHS.get()->getType()->isVectorType() ||
10991 RHS.get()->getType()->isVectorType()) {
10992 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10994 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10995 /*AllowBothBool*/ getLangOpts().AltiVec,
10996 /*AllowBoolConversions*/ false,
10997 /*AllowBooleanOperation*/ false,
10998 /*ReportInvalid*/ true);
10999 return InvalidOperands(Loc, LHS, RHS);
11000 }
11001
11002 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11003 RHS.get()->getType()->isSveVLSBuiltinType()) {
11004 if (LHS.get()->getType()->hasIntegerRepresentation() &&
11006 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11008
11009 return InvalidOperands(Loc, LHS, RHS);
11010 }
11011
11013 LHS, RHS, Loc, IsCompAssign ? ACK_CompAssign : ACK_Arithmetic);
11014 if (LHS.isInvalid() || RHS.isInvalid())
11015 return QualType();
11016
11017 if (compType.isNull() || !compType->isIntegerType())
11018 return InvalidOperands(Loc, LHS, RHS);
11019 DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
11020 return compType;
11021}
11022
11023/// Diagnose invalid arithmetic on two void pointers.
11025 Expr *LHSExpr, Expr *RHSExpr) {
11026 S.Diag(Loc, S.getLangOpts().CPlusPlus
11027 ? diag::err_typecheck_pointer_arith_void_type
11028 : diag::ext_gnu_void_ptr)
11029 << 1 /* two pointers */ << LHSExpr->getSourceRange()
11030 << RHSExpr->getSourceRange();
11031}
11032
11033/// Diagnose invalid arithmetic on a void pointer.
11035 Expr *Pointer) {
11036 S.Diag(Loc, S.getLangOpts().CPlusPlus
11037 ? diag::err_typecheck_pointer_arith_void_type
11038 : diag::ext_gnu_void_ptr)
11039 << 0 /* one pointer */ << Pointer->getSourceRange();
11040}
11041
11042/// Diagnose invalid arithmetic on a null pointer.
11043///
11044/// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11045/// idiom, which we recognize as a GNU extension.
11046///
11048 Expr *Pointer, bool IsGNUIdiom) {
11049 if (IsGNUIdiom)
11050 S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
11051 << Pointer->getSourceRange();
11052 else
11053 S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
11054 << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
11055}
11056
11057/// Diagnose invalid subraction on a null pointer.
11058///
11060 Expr *Pointer, bool BothNull) {
11061 // Null - null is valid in C++ [expr.add]p7
11062 if (BothNull && S.getLangOpts().CPlusPlus)
11063 return;
11064
11065 // Is this s a macro from a system header?
11067 return;
11068
11070 S.PDiag(diag::warn_pointer_sub_null_ptr)
11071 << S.getLangOpts().CPlusPlus
11072 << Pointer->getSourceRange());
11073}
11074
11075/// Diagnose invalid arithmetic on two function pointers.
11077 Expr *LHS, Expr *RHS) {
11078 assert(LHS->getType()->isAnyPointerType());
11079 assert(RHS->getType()->isAnyPointerType());
11080 S.Diag(Loc, S.getLangOpts().CPlusPlus
11081 ? diag::err_typecheck_pointer_arith_function_type
11082 : diag::ext_gnu_ptr_func_arith)
11083 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
11084 // We only show the second type if it differs from the first.
11086 RHS->getType())
11087 << RHS->getType()->getPointeeType()
11088 << LHS->getSourceRange() << RHS->getSourceRange();
11089}
11090
11091/// Diagnose invalid arithmetic on a function pointer.
11093 Expr *Pointer) {
11094 assert(Pointer->getType()->isAnyPointerType());
11095 S.Diag(Loc, S.getLangOpts().CPlusPlus
11096 ? diag::err_typecheck_pointer_arith_function_type
11097 : diag::ext_gnu_ptr_func_arith)
11098 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
11099 << 0 /* one pointer, so only one type */
11100 << Pointer->getSourceRange();
11101}
11102
11103/// Emit error if Operand is incomplete pointer type
11104///
11105/// \returns True if pointer has incomplete type
11107 Expr *Operand) {
11108 QualType ResType = Operand->getType();
11109 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11110 ResType = ResAtomicType->getValueType();
11111
11112 assert(ResType->isAnyPointerType() && !ResType->isDependentType());
11113 QualType PointeeTy = ResType->getPointeeType();
11114 return S.RequireCompleteSizedType(
11115 Loc, PointeeTy,
11116 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type,
11117 Operand->getSourceRange());
11118}
11119
11120/// Check the validity of an arithmetic pointer operand.
11121///
11122/// If the operand has pointer type, this code will check for pointer types
11123/// which are invalid in arithmetic operations. These will be diagnosed
11124/// appropriately, including whether or not the use is supported as an
11125/// extension.
11126///
11127/// \returns True when the operand is valid to use (even if as an extension).
11129 Expr *Operand) {
11130 QualType ResType = Operand->getType();
11131 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11132 ResType = ResAtomicType->getValueType();
11133
11134 if (!ResType->isAnyPointerType()) return true;
11135
11136 QualType PointeeTy = ResType->getPointeeType();
11137 if (PointeeTy->isVoidType()) {
11138 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
11139 return !S.getLangOpts().CPlusPlus;
11140 }
11141 if (PointeeTy->isFunctionType()) {
11142 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
11143 return !S.getLangOpts().CPlusPlus;
11144 }
11145
11146 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
11147
11148 return true;
11149}
11150
11151/// Check the validity of a binary arithmetic operation w.r.t. pointer
11152/// operands.
11153///
11154/// This routine will diagnose any invalid arithmetic on pointer operands much
11155/// like \see checkArithmeticOpPointerOperand. However, it has special logic
11156/// for emitting a single diagnostic even for operations where both LHS and RHS
11157/// are (potentially problematic) pointers.
11158///
11159/// \returns True when the operand is valid to use (even if as an extension).
11161 Expr *LHSExpr, Expr *RHSExpr) {
11162 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
11163 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
11164 if (!isLHSPointer && !isRHSPointer) return true;
11165
11166 QualType LHSPointeeTy, RHSPointeeTy;
11167 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
11168 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
11169
11170 // if both are pointers check if operation is valid wrt address spaces
11171 if (isLHSPointer && isRHSPointer) {
11172 if (!LHSPointeeTy.isAddressSpaceOverlapping(RHSPointeeTy)) {
11173 S.Diag(Loc,
11174 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
11175 << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
11176 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
11177 return false;
11178 }
11179 }
11180
11181 // Check for arithmetic on pointers to incomplete types.
11182 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
11183 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
11184 if (isLHSVoidPtr || isRHSVoidPtr) {
11185 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
11186 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
11187 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
11188
11189 return !S.getLangOpts().CPlusPlus;
11190 }
11191
11192 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
11193 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
11194 if (isLHSFuncPtr || isRHSFuncPtr) {
11195 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
11196 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11197 RHSExpr);
11198 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
11199
11200 return !S.getLangOpts().CPlusPlus;
11201 }
11202
11203 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
11204 return false;
11205 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
11206 return false;
11207
11208 return true;
11209}
11210
11211/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11212/// literal.
11214 Expr *LHSExpr, Expr *RHSExpr) {
11215 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
11216 Expr* IndexExpr = RHSExpr;
11217 if (!StrExpr) {
11218 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
11219 IndexExpr = LHSExpr;
11220 }
11221
11222 bool IsStringPlusInt = StrExpr &&
11224 if (!IsStringPlusInt || IndexExpr->isValueDependent())
11225 return;
11226
11227 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11228 Self.Diag(OpLoc, diag::warn_string_plus_int)
11229 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
11230
11231 // Only print a fixit for "str" + int, not for int + "str".
11232 if (IndexExpr == RHSExpr) {
11233 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11234 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11235 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11237 << FixItHint::CreateInsertion(EndLoc, "]");
11238 } else
11239 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11240}
11241
11242/// Emit a warning when adding a char literal to a string.
11244 Expr *LHSExpr, Expr *RHSExpr) {
11245 const Expr *StringRefExpr = LHSExpr;
11246 const CharacterLiteral *CharExpr =
11247 dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
11248
11249 if (!CharExpr) {
11250 CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
11251 StringRefExpr = RHSExpr;
11252 }
11253
11254 if (!CharExpr || !StringRefExpr)
11255 return;
11256
11257 const QualType StringType = StringRefExpr->getType();
11258
11259 // Return if not a PointerType.
11260 if (!StringType->isAnyPointerType())
11261 return;
11262
11263 // Return if not a CharacterType.
11264 if (!StringType->getPointeeType()->isAnyCharacterType())
11265 return;
11266
11267 ASTContext &Ctx = Self.getASTContext();
11268 SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
11269
11270 const QualType CharType = CharExpr->getType();
11271 if (!CharType->isAnyCharacterType() &&
11272 CharType->isIntegerType() &&
11273 llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
11274 Self.Diag(OpLoc, diag::warn_string_plus_char)
11275 << DiagRange << Ctx.CharTy;
11276 } else {
11277 Self.Diag(OpLoc, diag::warn_string_plus_char)
11278 << DiagRange << CharExpr->getType();
11279 }
11280
11281 // Only print a fixit for str + char, not for char + str.
11282 if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
11283 SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
11284 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11285 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11287 << FixItHint::CreateInsertion(EndLoc, "]");
11288 } else {
11289 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
11290 }
11291}
11292
11293/// Emit error when two pointers are incompatible.
11295 Expr *LHSExpr, Expr *RHSExpr) {
11296 assert(LHSExpr->getType()->isAnyPointerType());
11297 assert(RHSExpr->getType()->isAnyPointerType());
11298 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
11299 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
11300 << RHSExpr->getSourceRange();
11301}
11302
11303// C99 6.5.6
11306 QualType* CompLHSTy) {
11307 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11308
11309 if (LHS.get()->getType()->isVectorType() ||
11310 RHS.get()->getType()->isVectorType()) {
11311 QualType compType =
11312 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11313 /*AllowBothBool*/ getLangOpts().AltiVec,
11314 /*AllowBoolConversions*/ getLangOpts().ZVector,
11315 /*AllowBooleanOperation*/ false,
11316 /*ReportInvalid*/ true);
11317 if (CompLHSTy) *CompLHSTy = compType;
11318 return compType;
11319 }
11320
11321 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11322 RHS.get()->getType()->isSveVLSBuiltinType()) {
11323 QualType compType =
11324 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11325 if (CompLHSTy)
11326 *CompLHSTy = compType;
11327 return compType;
11328 }
11329
11330 if (LHS.get()->getType()->isConstantMatrixType() ||
11331 RHS.get()->getType()->isConstantMatrixType()) {
11332 QualType compType =
11333 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11334 if (CompLHSTy)
11335 *CompLHSTy = compType;
11336 return compType;
11337 }
11338
11340 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11341 if (LHS.isInvalid() || RHS.isInvalid())
11342 return QualType();
11343
11344 // Diagnose "string literal" '+' int and string '+' "char literal".
11345 if (Opc == BO_Add) {
11346 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
11347 diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
11348 }
11349
11350 // handle the common case first (both operands are arithmetic).
11351 if (!compType.isNull() && compType->isArithmeticType()) {
11352 if (CompLHSTy) *CompLHSTy = compType;
11353 return compType;
11354 }
11355
11356 // Type-checking. Ultimately the pointer's going to be in PExp;
11357 // note that we bias towards the LHS being the pointer.
11358 Expr *PExp = LHS.get(), *IExp = RHS.get();
11359
11360 bool isObjCPointer;
11361 if (PExp->getType()->isPointerType()) {
11362 isObjCPointer = false;
11363 } else if (PExp->getType()->isObjCObjectPointerType()) {
11364 isObjCPointer = true;
11365 } else {
11366 std::swap(PExp, IExp);
11367 if (PExp->getType()->isPointerType()) {
11368 isObjCPointer = false;
11369 } else if (PExp->getType()->isObjCObjectPointerType()) {
11370 isObjCPointer = true;
11371 } else {
11372 return InvalidOperands(Loc, LHS, RHS);
11373 }
11374 }
11375 assert(PExp->getType()->isAnyPointerType());
11376
11377 if (!IExp->getType()->isIntegerType())
11378 return InvalidOperands(Loc, LHS, RHS);
11379
11380 // Adding to a null pointer results in undefined behavior.
11383 // In C++ adding zero to a null pointer is defined.
11384 Expr::EvalResult KnownVal;
11385 if (!getLangOpts().CPlusPlus ||
11386 (!IExp->isValueDependent() &&
11387 (!IExp->EvaluateAsInt(KnownVal, Context) ||
11388 KnownVal.Val.getInt() != 0))) {
11389 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11391 Context, BO_Add, PExp, IExp);
11392 diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
11393 }
11394 }
11395
11396 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
11397 return QualType();
11398
11399 if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
11400 return QualType();
11401
11402 // Check array bounds for pointer arithemtic
11403 CheckArrayAccess(PExp, IExp);
11404
11405 if (CompLHSTy) {
11407 if (LHSTy.isNull()) {
11408 LHSTy = LHS.get()->getType();
11410 LHSTy = Context.getPromotedIntegerType(LHSTy);
11411 }
11412 *CompLHSTy = LHSTy;
11413 }
11414
11415 return PExp->getType();
11416}
11417
11418// C99 6.5.6
11420 SourceLocation Loc,
11421 QualType* CompLHSTy) {
11422 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11423
11424 if (LHS.get()->getType()->isVectorType() ||
11425 RHS.get()->getType()->isVectorType()) {
11426 QualType compType =
11427 CheckVectorOperands(LHS, RHS, Loc, CompLHSTy,
11428 /*AllowBothBool*/ getLangOpts().AltiVec,
11429 /*AllowBoolConversions*/ getLangOpts().ZVector,
11430 /*AllowBooleanOperation*/ false,
11431 /*ReportInvalid*/ true);
11432 if (CompLHSTy) *CompLHSTy = compType;
11433 return compType;
11434 }
11435
11436 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11437 RHS.get()->getType()->isSveVLSBuiltinType()) {
11438 QualType compType =
11439 CheckSizelessVectorOperands(LHS, RHS, Loc, CompLHSTy, ACK_Arithmetic);
11440 if (CompLHSTy)
11441 *CompLHSTy = compType;
11442 return compType;
11443 }
11444
11445 if (LHS.get()->getType()->isConstantMatrixType() ||
11446 RHS.get()->getType()->isConstantMatrixType()) {
11447 QualType compType =
11448 CheckMatrixElementwiseOperands(LHS, RHS, Loc, CompLHSTy);
11449 if (CompLHSTy)
11450 *CompLHSTy = compType;
11451 return compType;
11452 }
11453
11455 LHS, RHS, Loc, CompLHSTy ? ACK_CompAssign : ACK_Arithmetic);
11456 if (LHS.isInvalid() || RHS.isInvalid())
11457 return QualType();
11458
11459 // Enforce type constraints: C99 6.5.6p3.
11460
11461 // Handle the common case first (both operands are arithmetic).
11462 if (!compType.isNull() && compType->isArithmeticType()) {
11463 if (CompLHSTy) *CompLHSTy = compType;
11464 return compType;
11465 }
11466
11467 // Either ptr - int or ptr - ptr.
11468 if (LHS.get()->getType()->isAnyPointerType()) {
11469 QualType lpointee = LHS.get()->getType()->getPointeeType();
11470
11471 // Diagnose bad cases where we step over interface counts.
11472 if (LHS.get()->getType()->isObjCObjectPointerType() &&
11473 checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
11474 return QualType();
11475
11476 // The result type of a pointer-int computation is the pointer type.
11477 if (RHS.get()->getType()->isIntegerType()) {
11478 // Subtracting from a null pointer should produce a warning.
11479 // The last argument to the diagnose call says this doesn't match the
11480 // GNU int-to-pointer idiom.
11483 // In C++ adding zero to a null pointer is defined.
11484 Expr::EvalResult KnownVal;
11485 if (!getLangOpts().CPlusPlus ||
11486 (!RHS.get()->isValueDependent() &&
11487 (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
11488 KnownVal.Val.getInt() != 0))) {
11489 diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
11490 }
11491 }
11492
11493 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
11494 return QualType();
11495
11496 // Check array bounds for pointer arithemtic
11497 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
11498 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11499
11500 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11501 return LHS.get()->getType();
11502 }
11503
11504 // Handle pointer-pointer subtractions.
11505 if (const PointerType *RHSPTy
11506 = RHS.get()->getType()->getAs<PointerType>()) {
11507 QualType rpointee = RHSPTy->getPointeeType();
11508
11509 if (getLangOpts().CPlusPlus) {
11510 // Pointee types must be the same: C++ [expr.add]
11511 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
11512 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11513 }
11514 } else {
11515 // Pointee types must be compatible C99 6.5.6p3
11519 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
11520 return QualType();
11521 }
11522 }
11523
11525 LHS.get(), RHS.get()))
11526 return QualType();
11527
11528 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11530 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11532
11533 // Subtracting nullptr or from nullptr is suspect
11534 if (LHSIsNullPtr)
11535 diagnoseSubtractionOnNullPointer(*this, Loc, LHS.get(), RHSIsNullPtr);
11536 if (RHSIsNullPtr)
11537 diagnoseSubtractionOnNullPointer(*this, Loc, RHS.get(), LHSIsNullPtr);
11538
11539 // The pointee type may have zero size. As an extension, a structure or
11540 // union may have zero size or an array may have zero length. In this
11541 // case subtraction does not make sense.
11542 if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
11543 CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
11544 if (ElementSize.isZero()) {
11545 Diag(Loc,diag::warn_sub_ptr_zero_size_types)
11546 << rpointee.getUnqualifiedType()
11547 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11548 }
11549 }
11550
11551 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
11552 return Context.getPointerDiffType();
11553 }
11554 }
11555
11556 return InvalidOperands(Loc, LHS, RHS);
11557}
11558
11560 if (const EnumType *ET = T->getAs<EnumType>())
11561 return ET->getDecl()->isScoped();
11562 return false;
11563}
11564
11567 QualType LHSType) {
11568 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11569 // so skip remaining warnings as we don't want to modify values within Sema.
11570 if (S.getLangOpts().OpenCL)
11571 return;
11572
11573 // Check right/shifter operand
11574 Expr::EvalResult RHSResult;
11575 if (RHS.get()->isValueDependent() ||
11576 !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
11577 return;
11578 llvm::APSInt Right = RHSResult.Val.getInt();
11579
11580 if (Right.isNegative()) {
11581 S.DiagRuntimeBehavior(Loc, RHS.get(),
11582 S.PDiag(diag::warn_shift_negative)
11583 << RHS.get()->getSourceRange());
11584 return;
11585 }
11586
11587 QualType LHSExprType = LHS.get()->getType();
11588 uint64_t LeftSize = S.Context.getTypeSize(LHSExprType);
11589 if (LHSExprType->isBitIntType())
11590 LeftSize = S.Context.getIntWidth(LHSExprType);
11591 else if (LHSExprType->isFixedPointType()) {
11592 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
11593 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11594 }
11595 if (Right.uge(LeftSize)) {
11596 S.DiagRuntimeBehavior(Loc, RHS.get(),
11597 S.PDiag(diag::warn_shift_gt_typewidth)
11598 << RHS.get()->getSourceRange());
11599 return;
11600 }
11601
11602 // FIXME: We probably need to handle fixed point types specially here.
11603 if (Opc != BO_Shl || LHSExprType->isFixedPointType())
11604 return;
11605
11606 // When left shifting an ICE which is signed, we can check for overflow which
11607 // according to C++ standards prior to C++2a has undefined behavior
11608 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11609 // more than the maximum value representable in the result type, so never
11610 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11611 // expression is still probably a bug.)
11612 Expr::EvalResult LHSResult;
11613 if (LHS.get()->isValueDependent() ||
11615 !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
11616 return;
11617 llvm::APSInt Left = LHSResult.Val.getInt();
11618
11619 // Don't warn if signed overflow is defined, then all the rest of the
11620 // diagnostics will not be triggered because the behavior is defined.
11621 // Also don't warn in C++20 mode (and newer), as signed left shifts
11622 // always wrap and never overflow.
11623 if (S.getLangOpts().isSignedOverflowDefined() || S.getLangOpts().CPlusPlus20)
11624 return;
11625
11626 // If LHS does not have a non-negative value then, the
11627 // behavior is undefined before C++2a. Warn about it.
11628 if (Left.isNegative()) {
11629 S.DiagRuntimeBehavior(Loc, LHS.get(),
11630 S.PDiag(diag::warn_shift_lhs_negative)
11631 << LHS.get()->getSourceRange());
11632 return;
11633 }
11634
11635 llvm::APInt ResultBits =
11636 static_cast<llvm::APInt &>(Right) + Left.getSignificantBits();
11637 if (ResultBits.ule(LeftSize))
11638 return;
11639 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
11640 Result = Result.shl(Right);
11641
11642 // Print the bit representation of the signed integer as an unsigned
11643 // hexadecimal number.
11644 SmallString<40> HexResult;
11645 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
11646
11647 // If we are only missing a sign bit, this is less likely to result in actual
11648 // bugs -- if the result is cast back to an unsigned type, it will have the
11649 // expected value. Thus we place this behind a different warning that can be
11650 // turned off separately if needed.
11651 if (ResultBits - 1 == LeftSize) {
11652 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
11653 << HexResult << LHSType
11654 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11655 return;
11656 }
11657
11658 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
11659 << HexResult.str() << Result.getSignificantBits() << LHSType
11660 << Left.getBitWidth() << LHS.get()->getSourceRange()
11661 << RHS.get()->getSourceRange();
11662}
11663
11664/// Return the resulting type when a vector is shifted
11665/// by a scalar or vector shift amount.
11667 SourceLocation Loc, bool IsCompAssign) {
11668 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11669 if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
11670 !LHS.get()->getType()->isVectorType()) {
11671 S.Diag(Loc, diag::err_shift_rhs_only_vector)
11672 << RHS.get()->getType() << LHS.get()->getType()
11673 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11674 return QualType();
11675 }
11676
11677 if (!IsCompAssign) {
11678 LHS = S.UsualUnaryConversions(LHS.get());
11679 if (LHS.isInvalid()) return QualType();
11680 }
11681
11682 RHS = S.UsualUnaryConversions(RHS.get());
11683 if (RHS.isInvalid()) return QualType();
11684
11685 QualType LHSType = LHS.get()->getType();
11686 // Note that LHS might be a scalar because the routine calls not only in
11687 // OpenCL case.
11688 const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
11689 QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
11690
11691 // Note that RHS might not be a vector.
11692 QualType RHSType = RHS.get()->getType();
11693 const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
11694 QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
11695
11696 // Do not allow shifts for boolean vectors.
11697 if ((LHSVecTy && LHSVecTy->isExtVectorBoolType()) ||
11698 (RHSVecTy && RHSVecTy->isExtVectorBoolType())) {
11699 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11700 << LHS.get()->getType() << RHS.get()->getType()
11701 << LHS.get()->getSourceRange();
11702 return QualType();
11703 }
11704
11705 // The operands need to be integers.
11706 if (!LHSEleType->isIntegerType()) {
11707 S.Diag(Loc, diag::err_typecheck_expect_int)
11708 << LHS.get()->getType() << LHS.get()->getSourceRange();
11709 return QualType();
11710 }
11711
11712 if (!RHSEleType->isIntegerType()) {
11713 S.Diag(Loc, diag::err_typecheck_expect_int)
11714 << RHS.get()->getType() << RHS.get()->getSourceRange();
11715 return QualType();
11716 }
11717
11718 if (!LHSVecTy) {
11719 assert(RHSVecTy);
11720 if (IsCompAssign)
11721 return RHSType;
11722 if (LHSEleType != RHSEleType) {
11723 LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
11724 LHSEleType = RHSEleType;
11725 }
11726 QualType VecTy =
11727 S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
11728 LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
11729 LHSType = VecTy;
11730 } else if (RHSVecTy) {
11731 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11732 // are applied component-wise. So if RHS is a vector, then ensure
11733 // that the number of elements is the same as LHS...
11734 if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
11735 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11736 << LHS.get()->getType() << RHS.get()->getType()
11737 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11738 return QualType();
11739 }
11740 if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
11741 const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
11742 const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
11743 if (LHSBT != RHSBT &&
11744 S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
11745 S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
11746 << LHS.get()->getType() << RHS.get()->getType()
11747 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11748 }
11749 }
11750 } else {
11751 // ...else expand RHS to match the number of elements in LHS.
11752 QualType VecTy =
11753 S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
11754 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11755 }
11756
11757 return LHSType;
11758}
11759
11761 ExprResult &RHS, SourceLocation Loc,
11762 bool IsCompAssign) {
11763 if (!IsCompAssign) {
11764 LHS = S.UsualUnaryConversions(LHS.get());
11765 if (LHS.isInvalid())
11766 return QualType();
11767 }
11768
11769 RHS = S.UsualUnaryConversions(RHS.get());
11770 if (RHS.isInvalid())
11771 return QualType();
11772
11773 QualType LHSType = LHS.get()->getType();
11774 const BuiltinType *LHSBuiltinTy = LHSType->castAs<BuiltinType>();
11775 QualType LHSEleType = LHSType->isSveVLSBuiltinType()
11776 ? LHSBuiltinTy->getSveEltType(S.getASTContext())
11777 : LHSType;
11778
11779 // Note that RHS might not be a vector
11780 QualType RHSType = RHS.get()->getType();
11781 const BuiltinType *RHSBuiltinTy = RHSType->castAs<BuiltinType>();
11782 QualType RHSEleType = RHSType->isSveVLSBuiltinType()
11783 ? RHSBuiltinTy->getSveEltType(S.getASTContext())
11784 : RHSType;
11785
11786 if ((LHSBuiltinTy && LHSBuiltinTy->isSVEBool()) ||
11787 (RHSBuiltinTy && RHSBuiltinTy->isSVEBool())) {
11788 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11789 << LHSType << RHSType << LHS.get()->getSourceRange();
11790 return QualType();
11791 }
11792
11793 if (!LHSEleType->isIntegerType()) {
11794 S.Diag(Loc, diag::err_typecheck_expect_int)
11795 << LHS.get()->getType() << LHS.get()->getSourceRange();
11796 return QualType();
11797 }
11798
11799 if (!RHSEleType->isIntegerType()) {
11800 S.Diag(Loc, diag::err_typecheck_expect_int)
11801 << RHS.get()->getType() << RHS.get()->getSourceRange();
11802 return QualType();
11803 }
11804
11805 if (LHSType->isSveVLSBuiltinType() && RHSType->isSveVLSBuiltinType() &&
11806 (S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC !=
11807 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC)) {
11808 S.Diag(Loc, diag::err_typecheck_invalid_operands)
11809 << LHSType << RHSType << LHS.get()->getSourceRange()
11810 << RHS.get()->getSourceRange();
11811 return QualType();
11812 }
11813
11814 if (!LHSType->isSveVLSBuiltinType()) {
11815 assert(RHSType->isSveVLSBuiltinType());
11816 if (IsCompAssign)
11817 return RHSType;
11818 if (LHSEleType != RHSEleType) {
11819 LHS = S.ImpCastExprToType(LHS.get(), RHSEleType, clang::CK_IntegralCast);
11820 LHSEleType = RHSEleType;
11821 }
11822 const llvm::ElementCount VecSize =
11823 S.Context.getBuiltinVectorTypeInfo(RHSBuiltinTy).EC;
11824 QualType VecTy =
11825 S.Context.getScalableVectorType(LHSEleType, VecSize.getKnownMinValue());
11826 LHS = S.ImpCastExprToType(LHS.get(), VecTy, clang::CK_VectorSplat);
11827 LHSType = VecTy;
11828 } else if (RHSBuiltinTy && RHSBuiltinTy->isSveVLSBuiltinType()) {
11829 if (S.Context.getTypeSize(RHSBuiltinTy) !=
11830 S.Context.getTypeSize(LHSBuiltinTy)) {
11831 S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
11832 << LHSType << RHSType << LHS.get()->getSourceRange()
11833 << RHS.get()->getSourceRange();
11834 return QualType();
11835 }
11836 } else {
11837 const llvm::ElementCount VecSize =
11838 S.Context.getBuiltinVectorTypeInfo(LHSBuiltinTy).EC;
11839 if (LHSEleType != RHSEleType) {
11840 RHS = S.ImpCastExprToType(RHS.get(), LHSEleType, clang::CK_IntegralCast);
11841 RHSEleType = LHSEleType;
11842 }
11843 QualType VecTy =
11844 S.Context.getScalableVectorType(RHSEleType, VecSize.getKnownMinValue());
11845 RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
11846 }
11847
11848 return LHSType;
11849}
11850
11851// C99 6.5.7
11854 bool IsCompAssign) {
11855 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
11856
11857 // Vector shifts promote their scalar inputs to vector type.
11858 if (LHS.get()->getType()->isVectorType() ||
11859 RHS.get()->getType()->isVectorType()) {
11860 if (LangOpts.ZVector) {
11861 // The shift operators for the z vector extensions work basically
11862 // like general shifts, except that neither the LHS nor the RHS is
11863 // allowed to be a "vector bool".
11864 if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
11865 if (LHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11866 return InvalidOperands(Loc, LHS, RHS);
11867 if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
11868 if (RHSVecType->getVectorKind() == VectorKind::AltiVecBool)
11869 return InvalidOperands(Loc, LHS, RHS);
11870 }
11871 return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11872 }
11873
11874 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11875 RHS.get()->getType()->isSveVLSBuiltinType())
11876 return checkSizelessVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
11877
11878 // Shifts don't perform usual arithmetic conversions, they just do integer
11879 // promotions on each operand. C99 6.5.7p3
11880
11881 // For the LHS, do usual unary conversions, but then reset them away
11882 // if this is a compound assignment.
11883 ExprResult OldLHS = LHS;
11884 LHS = UsualUnaryConversions(LHS.get());
11885 if (LHS.isInvalid())
11886 return QualType();
11887 QualType LHSType = LHS.get()->getType();
11888 if (IsCompAssign) LHS = OldLHS;
11889
11890 // The RHS is simpler.
11891 RHS = UsualUnaryConversions(RHS.get());
11892 if (RHS.isInvalid())
11893 return QualType();
11894 QualType RHSType = RHS.get()->getType();
11895
11896 // C99 6.5.7p2: Each of the operands shall have integer type.
11897 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
11898 if ((!LHSType->isFixedPointOrIntegerType() &&
11899 !LHSType->hasIntegerRepresentation()) ||
11900 !RHSType->hasIntegerRepresentation())
11901 return InvalidOperands(Loc, LHS, RHS);
11902
11903 // C++0x: Don't allow scoped enums. FIXME: Use something better than
11904 // hasIntegerRepresentation() above instead of this.
11905 if (isScopedEnumerationType(LHSType) ||
11906 isScopedEnumerationType(RHSType)) {
11907 return InvalidOperands(Loc, LHS, RHS);
11908 }
11909 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
11910
11911 // "The type of the result is that of the promoted left operand."
11912 return LHSType;
11913}
11914
11915/// Diagnose bad pointer comparisons.
11917 ExprResult &LHS, ExprResult &RHS,
11918 bool IsError) {
11919 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
11920 : diag::ext_typecheck_comparison_of_distinct_pointers)
11921 << LHS.get()->getType() << RHS.get()->getType()
11922 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11923}
11924
11925/// Returns false if the pointers are converted to a composite type,
11926/// true otherwise.
11928 ExprResult &LHS, ExprResult &RHS) {
11929 // C++ [expr.rel]p2:
11930 // [...] Pointer conversions (4.10) and qualification
11931 // conversions (4.4) are performed on pointer operands (or on
11932 // a pointer operand and a null pointer constant) to bring
11933 // them to their composite pointer type. [...]
11934 //
11935 // C++ [expr.eq]p1 uses the same notion for (in)equality
11936 // comparisons of pointers.
11937
11938 QualType LHSType = LHS.get()->getType();
11939 QualType RHSType = RHS.get()->getType();
11940 assert(LHSType->isPointerType() || RHSType->isPointerType() ||
11941 LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
11942
11943 QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
11944 if (T.isNull()) {
11945 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11946 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11947 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
11948 else
11949 S.InvalidOperands(Loc, LHS, RHS);
11950 return true;
11951 }
11952
11953 return false;
11954}
11955
11957 ExprResult &LHS,
11958 ExprResult &RHS,
11959 bool IsError) {
11960 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
11961 : diag::ext_typecheck_comparison_of_fptr_to_void)
11962 << LHS.get()->getType() << RHS.get()->getType()
11963 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
11964}
11965
11967 switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
11968 case Stmt::ObjCArrayLiteralClass:
11969 case Stmt::ObjCDictionaryLiteralClass:
11970 case Stmt::ObjCStringLiteralClass:
11971 case Stmt::ObjCBoxedExprClass:
11972 return true;
11973 default:
11974 // Note that ObjCBoolLiteral is NOT an object literal!
11975 return false;
11976 }
11977}
11978
11979static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
11982
11983 // If this is not actually an Objective-C object, bail out.
11984 if (!Type)
11985 return false;
11986
11987 // Get the LHS object's interface type.
11988 QualType InterfaceType = Type->getPointeeType();
11989
11990 // If the RHS isn't an Objective-C object, bail out.
11991 if (!RHS->getType()->isObjCObjectPointerType())
11992 return false;
11993
11994 // Try to find the -isEqual: method.
11995 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
11996 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
11997 InterfaceType,
11998 /*IsInstance=*/true);
11999 if (!Method) {
12000 if (Type->isObjCIdType()) {
12001 // For 'id', just check the global pool.
12002 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
12003 /*receiverId=*/true);
12004 } else {
12005 // Check protocols.
12006 Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
12007 /*IsInstance=*/true);
12008 }
12009 }
12010
12011 if (!Method)
12012 return false;
12013
12014 QualType T = Method->parameters()[0]->getType();
12015 if (!T->isObjCObjectPointerType())
12016 return false;
12017
12018 QualType R = Method->getReturnType();
12019 if (!R->isScalarType())
12020 return false;
12021
12022 return true;
12023}
12024
12026 FromE = FromE->IgnoreParenImpCasts();
12027 switch (FromE->getStmtClass()) {
12028 default:
12029 break;
12030 case Stmt::ObjCStringLiteralClass:
12031 // "string literal"
12032 return LK_String;
12033 case Stmt::ObjCArrayLiteralClass:
12034 // "array literal"
12035 return LK_Array;
12036 case Stmt::ObjCDictionaryLiteralClass:
12037 // "dictionary literal"
12038 return LK_Dictionary;
12039 case Stmt::BlockExprClass:
12040 return LK_Block;
12041 case Stmt::ObjCBoxedExprClass: {
12042 Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
12043 switch (Inner->getStmtClass()) {
12044 case Stmt::IntegerLiteralClass:
12045 case Stmt::FloatingLiteralClass:
12046 case Stmt::CharacterLiteralClass:
12047 case Stmt::ObjCBoolLiteralExprClass:
12048 case Stmt::CXXBoolLiteralExprClass:
12049 // "numeric literal"
12050 return LK_Numeric;
12051 case Stmt::ImplicitCastExprClass: {
12052 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
12053 // Boolean literals can be represented by implicit casts.
12054 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
12055 return LK_Numeric;
12056 break;
12057 }
12058 default:
12059 break;
12060 }
12061 return LK_Boxed;
12062 }
12063 }
12064 return LK_None;
12065}
12066
12068 ExprResult &LHS, ExprResult &RHS,
12070 Expr *Literal;
12071 Expr *Other;
12072 if (isObjCObjectLiteral(LHS)) {
12073 Literal = LHS.get();
12074 Other = RHS.get();
12075 } else {
12076 Literal = RHS.get();
12077 Other = LHS.get();
12078 }
12079
12080 // Don't warn on comparisons against nil.
12081 Other = Other->IgnoreParenCasts();
12082 if (Other->isNullPointerConstant(S.getASTContext(),
12084 return;
12085
12086 // This should be kept in sync with warn_objc_literal_comparison.
12087 // LK_String should always be after the other literals, since it has its own
12088 // warning flag.
12089 Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
12090 assert(LiteralKind != Sema::LK_Block);
12091 if (LiteralKind == Sema::LK_None) {
12092 llvm_unreachable("Unknown Objective-C object literal kind");
12093 }
12094
12095 if (LiteralKind == Sema::LK_String)
12096 S.Diag(Loc, diag::warn_objc_string_literal_comparison)
12097 << Literal->getSourceRange();
12098 else
12099 S.Diag(Loc, diag::warn_objc_literal_comparison)
12100 << LiteralKind << Literal->getSourceRange();
12101
12103 hasIsEqualMethod(S, LHS.get(), RHS.get())) {
12104 SourceLocation Start = LHS.get()->getBeginLoc();
12106 CharSourceRange OpRange =
12108
12109 S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
12110 << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
12111 << FixItHint::CreateReplacement(OpRange, " isEqual:")
12112 << FixItHint::CreateInsertion(End, "]");
12113 }
12114}
12115
12116/// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12118 ExprResult &RHS, SourceLocation Loc,
12119 BinaryOperatorKind Opc) {
12120 // Check that left hand side is !something.
12121 UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
12122 if (!UO || UO->getOpcode() != UO_LNot) return;
12123
12124 // Only check if the right hand side is non-bool arithmetic type.
12125 if (RHS.get()->isKnownToHaveBooleanValue()) return;
12126
12127 // Make sure that the something in !something is not bool.
12128 Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
12129 if (SubExpr->isKnownToHaveBooleanValue()) return;
12130
12131 // Emit warning.
12132 bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
12133 S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
12134 << Loc << IsBitwiseOp;
12135
12136 // First note suggest !(x < y)
12137 SourceLocation FirstOpen = SubExpr->getBeginLoc();
12138 SourceLocation FirstClose = RHS.get()->getEndLoc();
12139 FirstClose = S.getLocForEndOfToken(FirstClose);
12140 if (FirstClose.isInvalid())
12141 FirstOpen = SourceLocation();
12142 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
12143 << IsBitwiseOp
12144 << FixItHint::CreateInsertion(FirstOpen, "(")
12145 << FixItHint::CreateInsertion(FirstClose, ")");
12146
12147 // Second note suggests (!x) < y
12148 SourceLocation SecondOpen = LHS.get()->getBeginLoc();
12149 SourceLocation SecondClose = LHS.get()->getEndLoc();
12150 SecondClose = S.getLocForEndOfToken(SecondClose);
12151 if (SecondClose.isInvalid())
12152 SecondOpen = SourceLocation();
12153 S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
12154 << FixItHint::CreateInsertion(SecondOpen, "(")
12155 << FixItHint::CreateInsertion(SecondClose, ")");
12156}
12157
12158// Returns true if E refers to a non-weak array.
12159static bool checkForArray(const Expr *E) {
12160 const ValueDecl *D = nullptr;
12161 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
12162 D = DR->getDecl();
12163 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
12164 if (Mem->isImplicitAccess())
12165 D = Mem->getMemberDecl();
12166 }
12167 if (!D)
12168 return false;
12169 return D->getType()->isArrayType() && !D->isWeak();
12170}
12171
12172/// Diagnose some forms of syntactically-obvious tautological comparison.
12174 Expr *LHS, Expr *RHS,
12175 BinaryOperatorKind Opc) {
12176 Expr *LHSStripped = LHS->IgnoreParenImpCasts();
12177 Expr *RHSStripped = RHS->IgnoreParenImpCasts();
12178
12179 QualType LHSType = LHS->getType();
12180 QualType RHSType = RHS->getType();
12181 if (LHSType->hasFloatingRepresentation() ||
12182 (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
12184 return;
12185
12186 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12187 // Tautological diagnostics.
12188 if (LHSType->isWebAssemblyTableType() || RHSType->isWebAssemblyTableType())
12189 return;
12190
12191 // Comparisons between two array types are ill-formed for operator<=>, so
12192 // we shouldn't emit any additional warnings about it.
12193 if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
12194 return;
12195
12196 // For non-floating point types, check for self-comparisons of the form
12197 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12198 // often indicate logic errors in the program.
12199 //
12200 // NOTE: Don't warn about comparison expressions resulting from macro
12201 // expansion. Also don't warn about comparisons which are only self
12202 // comparisons within a template instantiation. The warnings should catch
12203 // obvious cases in the definition of the template anyways. The idea is to
12204 // warn when the typed comparison operator will always evaluate to the same
12205 // result.
12206
12207 // Used for indexing into %select in warn_comparison_always
12208 enum {
12209 AlwaysConstant,
12210 AlwaysTrue,
12211 AlwaysFalse,
12212 AlwaysEqual, // std::strong_ordering::equal from operator<=>
12213 };
12214
12215 // C++2a [depr.array.comp]:
12216 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12217 // operands of array type are deprecated.
12218 if (S.getLangOpts().CPlusPlus20 && LHSStripped->getType()->isArrayType() &&
12219 RHSStripped->getType()->isArrayType()) {
12220 S.Diag(Loc, diag::warn_depr_array_comparison)
12221 << LHS->getSourceRange() << RHS->getSourceRange()
12222 << LHSStripped->getType() << RHSStripped->getType();
12223 // Carry on to produce the tautological comparison warning, if this
12224 // expression is potentially-evaluated, we can resolve the array to a
12225 // non-weak declaration, and so on.
12226 }
12227
12228 if (!LHS->getBeginLoc().isMacroID() && !RHS->getBeginLoc().isMacroID()) {
12229 if (Expr::isSameComparisonOperand(LHS, RHS)) {
12230 unsigned Result;
12231 switch (Opc) {
12232 case BO_EQ:
12233 case BO_LE:
12234 case BO_GE:
12235 Result = AlwaysTrue;
12236 break;
12237 case BO_NE:
12238 case BO_LT:
12239 case BO_GT:
12240 Result = AlwaysFalse;
12241 break;
12242 case BO_Cmp:
12243 Result = AlwaysEqual;
12244 break;
12245 default:
12246 Result = AlwaysConstant;
12247 break;
12248 }
12249 S.DiagRuntimeBehavior(Loc, nullptr,
12250 S.PDiag(diag::warn_comparison_always)
12251 << 0 /*self-comparison*/
12252 << Result);
12253 } else if (checkForArray(LHSStripped) && checkForArray(RHSStripped)) {
12254 // What is it always going to evaluate to?
12255 unsigned Result;
12256 switch (Opc) {
12257 case BO_EQ: // e.g. array1 == array2
12258 Result = AlwaysFalse;
12259 break;
12260 case BO_NE: // e.g. array1 != array2
12261 Result = AlwaysTrue;
12262 break;
12263 default: // e.g. array1 <= array2
12264 // The best we can say is 'a constant'
12265 Result = AlwaysConstant;
12266 break;
12267 }
12268 S.DiagRuntimeBehavior(Loc, nullptr,
12269 S.PDiag(diag::warn_comparison_always)
12270 << 1 /*array comparison*/
12271 << Result);
12272 }
12273 }
12274
12275 if (isa<CastExpr>(LHSStripped))
12276 LHSStripped = LHSStripped->IgnoreParenCasts();
12277 if (isa<CastExpr>(RHSStripped))
12278 RHSStripped = RHSStripped->IgnoreParenCasts();
12279
12280 // Warn about comparisons against a string constant (unless the other
12281 // operand is null); the user probably wants string comparison function.
12282 Expr *LiteralString = nullptr;
12283 Expr *LiteralStringStripped = nullptr;
12284 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
12285 !RHSStripped->isNullPointerConstant(S.Context,
12287 LiteralString = LHS;
12288 LiteralStringStripped = LHSStripped;
12289 } else if ((isa<StringLiteral>(RHSStripped) ||
12290 isa<ObjCEncodeExpr>(RHSStripped)) &&
12291 !LHSStripped->isNullPointerConstant(S.Context,
12293 LiteralString = RHS;
12294 LiteralStringStripped = RHSStripped;
12295 }
12296
12297 if (LiteralString) {
12298 S.DiagRuntimeBehavior(Loc, nullptr,
12299 S.PDiag(diag::warn_stringcompare)
12300 << isa<ObjCEncodeExpr>(LiteralStringStripped)
12301 << LiteralString->getSourceRange());
12302 }
12303}
12304
12306 switch (CK) {
12307 default: {
12308#ifndef NDEBUG
12309 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
12310 << "\n";
12311#endif
12312 llvm_unreachable("unhandled cast kind");
12313 }
12314 case CK_UserDefinedConversion:
12315 return ICK_Identity;
12316 case CK_LValueToRValue:
12317 return ICK_Lvalue_To_Rvalue;
12318 case CK_ArrayToPointerDecay:
12319 return ICK_Array_To_Pointer;
12320 case CK_FunctionToPointerDecay:
12322 case CK_IntegralCast:
12324 case CK_FloatingCast:
12326 case CK_IntegralToFloating:
12327 case CK_FloatingToIntegral:
12328 return ICK_Floating_Integral;
12329 case CK_IntegralComplexCast:
12330 case CK_FloatingComplexCast:
12331 case CK_FloatingComplexToIntegralComplex:
12332 case CK_IntegralComplexToFloatingComplex:
12334 case CK_FloatingComplexToReal:
12335 case CK_FloatingRealToComplex:
12336 case CK_IntegralComplexToReal:
12337 case CK_IntegralRealToComplex:
12338 return ICK_Complex_Real;
12339 case CK_HLSLArrayRValue:
12340 return ICK_HLSL_Array_RValue;
12341 }
12342}
12343
12345 QualType FromType,
12346 SourceLocation Loc) {
12347 // Check for a narrowing implicit conversion.
12350 SCS.setToType(0, FromType);
12351 SCS.setToType(1, ToType);
12352 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
12353 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12354
12355 APValue PreNarrowingValue;
12356 QualType PreNarrowingType;
12357 switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
12358 PreNarrowingType,
12359 /*IgnoreFloatToIntegralConversion*/ true)) {
12361 // Implicit conversion to a narrower type, but the expression is
12362 // value-dependent so we can't tell whether it's actually narrowing.
12363 case NK_Not_Narrowing:
12364 return false;
12365
12367 // Implicit conversion to a narrower type, and the value is not a constant
12368 // expression.
12369 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12370 << /*Constant*/ 1
12371 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
12372 return true;
12373
12375 // Implicit conversion to a narrower type, and the value is not a constant
12376 // expression.
12377 case NK_Type_Narrowing:
12378 S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
12379 << /*Constant*/ 0 << FromType << ToType;
12380 // TODO: It's not a constant expression, but what if the user intended it
12381 // to be? Can we produce notes to help them figure out why it isn't?
12382 return true;
12383 }
12384 llvm_unreachable("unhandled case in switch");
12385}
12386
12388 ExprResult &LHS,
12389 ExprResult &RHS,
12390 SourceLocation Loc) {
12391 QualType LHSType = LHS.get()->getType();
12392 QualType RHSType = RHS.get()->getType();
12393 // Dig out the original argument type and expression before implicit casts
12394 // were applied. These are the types/expressions we need to check the
12395 // [expr.spaceship] requirements against.
12396 ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
12397 ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
12398 QualType LHSStrippedType = LHSStripped.get()->getType();
12399 QualType RHSStrippedType = RHSStripped.get()->getType();
12400
12401 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12402 // other is not, the program is ill-formed.
12403 if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
12404 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12405 return QualType();
12406 }
12407
12408 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12409 int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
12410 RHSStrippedType->isEnumeralType();
12411 if (NumEnumArgs == 1) {
12412 bool LHSIsEnum = LHSStrippedType->isEnumeralType();
12413 QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
12414 if (OtherTy->hasFloatingRepresentation()) {
12415 S.InvalidOperands(Loc, LHSStripped, RHSStripped);
12416 return QualType();
12417 }
12418 }
12419 if (NumEnumArgs == 2) {
12420 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12421 // type E, the operator yields the result of converting the operands
12422 // to the underlying type of E and applying <=> to the converted operands.
12423 if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
12424 S.InvalidOperands(Loc, LHS, RHS);
12425 return QualType();
12426 }
12427 QualType IntType =
12428 LHSStrippedType->castAs<EnumType>()->getDecl()->getIntegerType();
12429 assert(IntType->isArithmeticType());
12430
12431 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12432 // promote the boolean type, and all other promotable integer types, to
12433 // avoid this.
12434 if (S.Context.isPromotableIntegerType(IntType))
12435 IntType = S.Context.getPromotedIntegerType(IntType);
12436
12437 LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
12438 RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
12439 LHSType = RHSType = IntType;
12440 }
12441
12442 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12443 // usual arithmetic conversions are applied to the operands.
12444 QualType Type =
12446 if (LHS.isInvalid() || RHS.isInvalid())
12447 return QualType();
12448 if (Type.isNull())
12449 return S.InvalidOperands(Loc, LHS, RHS);
12450
12451 std::optional<ComparisonCategoryType> CCT =
12453 if (!CCT)
12454 return S.InvalidOperands(Loc, LHS, RHS);
12455
12456 bool HasNarrowing = checkThreeWayNarrowingConversion(
12457 S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
12458 HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
12459 RHS.get()->getBeginLoc());
12460 if (HasNarrowing)
12461 return QualType();
12462
12463 assert(!Type.isNull() && "composite type for <=> has not been set");
12464
12467}
12468
12470 ExprResult &RHS,
12471 SourceLocation Loc,
12472 BinaryOperatorKind Opc) {
12473 if (Opc == BO_Cmp)
12474 return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
12475
12476 // C99 6.5.8p3 / C99 6.5.9p4
12477 QualType Type =
12479 if (LHS.isInvalid() || RHS.isInvalid())
12480 return QualType();
12481 if (Type.isNull())
12482 return S.InvalidOperands(Loc, LHS, RHS);
12483 assert(Type->isArithmeticType() || Type->isEnumeralType());
12484
12486 return S.InvalidOperands(Loc, LHS, RHS);
12487
12488 // Check for comparisons of floating point operands using != and ==.
12490 S.CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
12491
12492 // The result of comparisons is 'bool' in C++, 'int' in C.
12494}
12495
12497 if (!NullE.get()->getType()->isAnyPointerType())
12498 return;
12499 int NullValue = PP.isMacroDefined("NULL") ? 0 : 1;
12500 if (!E.get()->getType()->isAnyPointerType() &&
12504 if (const auto *CL = dyn_cast<CharacterLiteral>(E.get())) {
12505 if (CL->getValue() == 0)
12506 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12507 << NullValue
12509 NullValue ? "NULL" : "(void *)0");
12510 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(E.get())) {
12511 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12513 if (T == Context.CharTy)
12514 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12515 << NullValue
12517 NullValue ? "NULL" : "(void *)0");
12518 }
12519 }
12520}
12521
12522// C99 6.5.8, C++ [expr.rel]
12524 SourceLocation Loc,
12525 BinaryOperatorKind Opc) {
12526 bool IsRelational = BinaryOperator::isRelationalOp(Opc);
12527 bool IsThreeWay = Opc == BO_Cmp;
12528 bool IsOrdered = IsRelational || IsThreeWay;
12529 auto IsAnyPointerType = [](ExprResult E) {
12530 QualType Ty = E.get()->getType();
12531 return Ty->isPointerType() || Ty->isMemberPointerType();
12532 };
12533
12534 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12535 // type, array-to-pointer, ..., conversions are performed on both operands to
12536 // bring them to their composite type.
12537 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12538 // any type-related checks.
12539 if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
12541 if (LHS.isInvalid())
12542 return QualType();
12544 if (RHS.isInvalid())
12545 return QualType();
12546 } else {
12547 LHS = DefaultLvalueConversion(LHS.get());
12548 if (LHS.isInvalid())
12549 return QualType();
12550 RHS = DefaultLvalueConversion(RHS.get());
12551 if (RHS.isInvalid())
12552 return QualType();
12553 }
12554
12555 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/true);
12559 }
12560
12561 // Handle vector comparisons separately.
12562 if (LHS.get()->getType()->isVectorType() ||
12563 RHS.get()->getType()->isVectorType())
12564 return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
12565
12566 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
12567 RHS.get()->getType()->isSveVLSBuiltinType())
12568 return CheckSizelessVectorCompareOperands(LHS, RHS, Loc, Opc);
12569
12570 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
12571 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
12572
12573 QualType LHSType = LHS.get()->getType();
12574 QualType RHSType = RHS.get()->getType();
12575 if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
12576 (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
12577 return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
12578
12579 if ((LHSType->isPointerType() &&
12581 (RHSType->isPointerType() &&
12583 return InvalidOperands(Loc, LHS, RHS);
12584
12585 const Expr::NullPointerConstantKind LHSNullKind =
12587 const Expr::NullPointerConstantKind RHSNullKind =
12589 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12590 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12591
12592 auto computeResultTy = [&]() {
12593 if (Opc != BO_Cmp)
12595 assert(getLangOpts().CPlusPlus);
12596 assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
12597
12598 QualType CompositeTy = LHS.get()->getType();
12599 assert(!CompositeTy->isReferenceType());
12600
12601 std::optional<ComparisonCategoryType> CCT =
12603 if (!CCT)
12604 return InvalidOperands(Loc, LHS, RHS);
12605
12606 if (CompositeTy->isPointerType() && LHSIsNull != RHSIsNull) {
12607 // P0946R0: Comparisons between a null pointer constant and an object
12608 // pointer result in std::strong_equality, which is ill-formed under
12609 // P1959R0.
12610 Diag(Loc, diag::err_typecheck_three_way_comparison_of_pointer_and_zero)
12611 << (LHSIsNull ? LHS.get()->getSourceRange()
12612 : RHS.get()->getSourceRange());
12613 return QualType();
12614 }
12615
12618 };
12619
12620 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12621 bool IsEquality = Opc == BO_EQ;
12622 if (RHSIsNull)
12623 DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
12624 RHS.get()->getSourceRange());
12625 else
12626 DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
12627 LHS.get()->getSourceRange());
12628 }
12629
12630 if (IsOrdered && LHSType->isFunctionPointerType() &&
12631 RHSType->isFunctionPointerType()) {
12632 // Valid unless a relational comparison of function pointers
12633 bool IsError = Opc == BO_Cmp;
12634 auto DiagID =
12635 IsError ? diag::err_typecheck_ordered_comparison_of_function_pointers
12636 : getLangOpts().CPlusPlus
12637 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12638 : diag::ext_typecheck_ordered_comparison_of_function_pointers;
12639 Diag(Loc, DiagID) << LHSType << RHSType << LHS.get()->getSourceRange()
12640 << RHS.get()->getSourceRange();
12641 if (IsError)
12642 return QualType();
12643 }
12644
12645 if ((LHSType->isIntegerType() && !LHSIsNull) ||
12646 (RHSType->isIntegerType() && !RHSIsNull)) {
12647 // Skip normal pointer conversion checks in this case; we have better
12648 // diagnostics for this below.
12649 } else if (getLangOpts().CPlusPlus) {
12650 // Equality comparison of a function pointer to a void pointer is invalid,
12651 // but we allow it as an extension.
12652 // FIXME: If we really want to allow this, should it be part of composite
12653 // pointer type computation so it works in conditionals too?
12654 if (!IsOrdered &&
12655 ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
12656 (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
12657 // This is a gcc extension compatibility comparison.
12658 // In a SFINAE context, we treat this as a hard error to maintain
12659 // conformance with the C++ standard.
12661 *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
12662
12663 if (isSFINAEContext())
12664 return QualType();
12665
12666 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12667 return computeResultTy();
12668 }
12669
12670 // C++ [expr.eq]p2:
12671 // If at least one operand is a pointer [...] bring them to their
12672 // composite pointer type.
12673 // C++ [expr.spaceship]p6
12674 // If at least one of the operands is of pointer type, [...] bring them
12675 // to their composite pointer type.
12676 // C++ [expr.rel]p2:
12677 // If both operands are pointers, [...] bring them to their composite
12678 // pointer type.
12679 // For <=>, the only valid non-pointer types are arrays and functions, and
12680 // we already decayed those, so this is really the same as the relational
12681 // comparison rule.
12682 if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
12683 (IsOrdered ? 2 : 1) &&
12684 (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
12685 RHSType->isObjCObjectPointerType()))) {
12686 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12687 return QualType();
12688 return computeResultTy();
12689 }
12690 } else if (LHSType->isPointerType() &&
12691 RHSType->isPointerType()) { // C99 6.5.8p2
12692 // All of the following pointer-related warnings are GCC extensions, except
12693 // when handling null pointer constants.
12694 QualType LCanPointeeTy =
12695 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12696 QualType RCanPointeeTy =
12697 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
12698
12699 // C99 6.5.9p2 and C99 6.5.8p2
12700 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
12701 RCanPointeeTy.getUnqualifiedType())) {
12702 if (IsRelational) {
12703 // Pointers both need to point to complete or incomplete types
12704 if ((LCanPointeeTy->isIncompleteType() !=
12705 RCanPointeeTy->isIncompleteType()) &&
12706 !getLangOpts().C11) {
12707 Diag(Loc, diag::ext_typecheck_compare_complete_incomplete_pointers)
12708 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange()
12709 << LHSType << RHSType << LCanPointeeTy->isIncompleteType()
12710 << RCanPointeeTy->isIncompleteType();
12711 }
12712 }
12713 } else if (!IsRelational &&
12714 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
12715 // Valid unless comparison between non-null pointer and function pointer
12716 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
12717 && !LHSIsNull && !RHSIsNull)
12718 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
12719 /*isError*/false);
12720 } else {
12721 // Invalid
12722 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
12723 }
12724 if (LCanPointeeTy != RCanPointeeTy) {
12725 // Treat NULL constant as a special case in OpenCL.
12726 if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
12727 if (!LCanPointeeTy.isAddressSpaceOverlapping(RCanPointeeTy)) {
12728 Diag(Loc,
12729 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
12730 << LHSType << RHSType << 0 /* comparison */
12731 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
12732 }
12733 }
12734 LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
12735 LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
12736 CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
12737 : CK_BitCast;
12738 if (LHSIsNull && !RHSIsNull)
12739 LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
12740 else
12741 RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
12742 }
12743 return computeResultTy();
12744 }
12745
12746
12747 // C++ [expr.eq]p4:
12748 // Two operands of type std::nullptr_t or one operand of type
12749 // std::nullptr_t and the other a null pointer constant compare
12750 // equal.
12751 // C23 6.5.9p5:
12752 // If both operands have type nullptr_t or one operand has type nullptr_t
12753 // and the other is a null pointer constant, they compare equal if the
12754 // former is a null pointer.
12755 if (!IsOrdered && LHSIsNull && RHSIsNull) {
12756 if (LHSType->isNullPtrType()) {
12757 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12758 return computeResultTy();
12759 }
12760 if (RHSType->isNullPtrType()) {
12761 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12762 return computeResultTy();
12763 }
12764 }
12765
12766 if (!getLangOpts().CPlusPlus && !IsOrdered && (LHSIsNull || RHSIsNull)) {
12767 // C23 6.5.9p6:
12768 // Otherwise, at least one operand is a pointer. If one is a pointer and
12769 // the other is a null pointer constant or has type nullptr_t, they
12770 // compare equal
12771 if (LHSIsNull && RHSType->isPointerType()) {
12772 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12773 return computeResultTy();
12774 }
12775 if (RHSIsNull && LHSType->isPointerType()) {
12776 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12777 return computeResultTy();
12778 }
12779 }
12780
12781 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12782 // These aren't covered by the composite pointer type rules.
12783 if (!IsOrdered && RHSType->isNullPtrType() &&
12784 (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
12785 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12786 return computeResultTy();
12787 }
12788 if (!IsOrdered && LHSType->isNullPtrType() &&
12789 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12790 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12791 return computeResultTy();
12792 }
12793
12794 if (getLangOpts().CPlusPlus) {
12795 if (IsRelational &&
12796 ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
12797 (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
12798 // HACK: Relational comparison of nullptr_t against a pointer type is
12799 // invalid per DR583, but we allow it within std::less<> and friends,
12800 // since otherwise common uses of it break.
12801 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12802 // friends to have std::nullptr_t overload candidates.
12803 DeclContext *DC = CurContext;
12804 if (isa<FunctionDecl>(DC))
12805 DC = DC->getParent();
12806 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
12807 if (CTSD->isInStdNamespace() &&
12808 llvm::StringSwitch<bool>(CTSD->getName())
12809 .Cases("less", "less_equal", "greater", "greater_equal", true)
12810 .Default(false)) {
12811 if (RHSType->isNullPtrType())
12812 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12813 else
12814 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12815 return computeResultTy();
12816 }
12817 }
12818 }
12819
12820 // C++ [expr.eq]p2:
12821 // If at least one operand is a pointer to member, [...] bring them to
12822 // their composite pointer type.
12823 if (!IsOrdered &&
12824 (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
12825 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
12826 return QualType();
12827 else
12828 return computeResultTy();
12829 }
12830 }
12831
12832 // Handle block pointer types.
12833 if (!IsOrdered && LHSType->isBlockPointerType() &&
12834 RHSType->isBlockPointerType()) {
12835 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
12836 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
12837
12838 if (!LHSIsNull && !RHSIsNull &&
12839 !Context.typesAreCompatible(lpointee, rpointee)) {
12840 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12841 << LHSType << RHSType << LHS.get()->getSourceRange()
12842 << RHS.get()->getSourceRange();
12843 }
12844 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12845 return computeResultTy();
12846 }
12847
12848 // Allow block pointers to be compared with null pointer constants.
12849 if (!IsOrdered
12850 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
12851 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
12852 if (!LHSIsNull && !RHSIsNull) {
12853 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
12855 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
12856 ->getPointeeType()->isVoidType())))
12857 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
12858 << LHSType << RHSType << LHS.get()->getSourceRange()
12859 << RHS.get()->getSourceRange();
12860 }
12861 if (LHSIsNull && !RHSIsNull)
12862 LHS = ImpCastExprToType(LHS.get(), RHSType,
12863 RHSType->isPointerType() ? CK_BitCast
12864 : CK_AnyPointerToBlockPointerCast);
12865 else
12866 RHS = ImpCastExprToType(RHS.get(), LHSType,
12867 LHSType->isPointerType() ? CK_BitCast
12868 : CK_AnyPointerToBlockPointerCast);
12869 return computeResultTy();
12870 }
12871
12872 if (LHSType->isObjCObjectPointerType() ||
12873 RHSType->isObjCObjectPointerType()) {
12874 const PointerType *LPT = LHSType->getAs<PointerType>();
12875 const PointerType *RPT = RHSType->getAs<PointerType>();
12876 if (LPT || RPT) {
12877 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
12878 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
12879
12880 if (!LPtrToVoid && !RPtrToVoid &&
12881 !Context.typesAreCompatible(LHSType, RHSType)) {
12882 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12883 /*isError*/false);
12884 }
12885 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12886 // the RHS, but we have test coverage for this behavior.
12887 // FIXME: Consider using convertPointersToCompositeType in C++.
12888 if (LHSIsNull && !RHSIsNull) {
12889 Expr *E = LHS.get();
12890 if (getLangOpts().ObjCAutoRefCount)
12891 CheckObjCConversion(SourceRange(), RHSType, E,
12893 LHS = ImpCastExprToType(E, RHSType,
12894 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12895 }
12896 else {
12897 Expr *E = RHS.get();
12898 if (getLangOpts().ObjCAutoRefCount)
12899 CheckObjCConversion(SourceRange(), LHSType, E,
12901 /*Diagnose=*/true,
12902 /*DiagnoseCFAudited=*/false, Opc);
12903 RHS = ImpCastExprToType(E, LHSType,
12904 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12905 }
12906 return computeResultTy();
12907 }
12908 if (LHSType->isObjCObjectPointerType() &&
12909 RHSType->isObjCObjectPointerType()) {
12910 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
12911 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
12912 /*isError*/false);
12914 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
12915
12916 if (LHSIsNull && !RHSIsNull)
12917 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
12918 else
12919 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
12920 return computeResultTy();
12921 }
12922
12923 if (!IsOrdered && LHSType->isBlockPointerType() &&
12925 LHS = ImpCastExprToType(LHS.get(), RHSType,
12926 CK_BlockPointerToObjCPointerCast);
12927 return computeResultTy();
12928 } else if (!IsOrdered &&
12930 RHSType->isBlockPointerType()) {
12931 RHS = ImpCastExprToType(RHS.get(), LHSType,
12932 CK_BlockPointerToObjCPointerCast);
12933 return computeResultTy();
12934 }
12935 }
12936 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
12937 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
12938 unsigned DiagID = 0;
12939 bool isError = false;
12940 if (LangOpts.DebuggerSupport) {
12941 // Under a debugger, allow the comparison of pointers to integers,
12942 // since users tend to want to compare addresses.
12943 } else if ((LHSIsNull && LHSType->isIntegerType()) ||
12944 (RHSIsNull && RHSType->isIntegerType())) {
12945 if (IsOrdered) {
12946 isError = getLangOpts().CPlusPlus;
12947 DiagID =
12948 isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
12949 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
12950 }
12951 } else if (getLangOpts().CPlusPlus) {
12952 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
12953 isError = true;
12954 } else if (IsOrdered)
12955 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
12956 else
12957 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
12958
12959 if (DiagID) {
12960 Diag(Loc, DiagID)
12961 << LHSType << RHSType << LHS.get()->getSourceRange()
12962 << RHS.get()->getSourceRange();
12963 if (isError)
12964 return QualType();
12965 }
12966
12967 if (LHSType->isIntegerType())
12968 LHS = ImpCastExprToType(LHS.get(), RHSType,
12969 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12970 else
12971 RHS = ImpCastExprToType(RHS.get(), LHSType,
12972 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12973 return computeResultTy();
12974 }
12975
12976 // Handle block pointers.
12977 if (!IsOrdered && RHSIsNull
12978 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
12979 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
12980 return computeResultTy();
12981 }
12982 if (!IsOrdered && LHSIsNull
12983 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12984 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12985 return computeResultTy();
12986 }
12987
12988 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
12989 if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
12990 return computeResultTy();
12991 }
12992
12993 if (LHSType->isQueueT() && RHSType->isQueueT()) {
12994 return computeResultTy();
12995 }
12996
12997 if (LHSIsNull && RHSType->isQueueT()) {
12998 LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
12999 return computeResultTy();
13000 }
13001
13002 if (LHSType->isQueueT() && RHSIsNull) {
13003 RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
13004 return computeResultTy();
13005 }
13006 }
13007
13008 return InvalidOperands(Loc, LHS, RHS);
13009}
13010
13011// Return a signed ext_vector_type that is of identical size and number of
13012// elements. For floating point vectors, return an integer type of identical
13013// size and number of elements. In the non ext_vector_type case, search from
13014// the largest type to the smallest type to avoid cases where long long == long,
13015// where long gets picked over long long.
13017 const VectorType *VTy = V->castAs<VectorType>();
13018 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
13019
13020 if (isa<ExtVectorType>(VTy)) {
13021 if (VTy->isExtVectorBoolType())
13023 if (TypeSize == Context.getTypeSize(Context.CharTy))
13025 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13027 if (TypeSize == Context.getTypeSize(Context.IntTy))
13029 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13031 if (TypeSize == Context.getTypeSize(Context.LongTy))
13033 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13034 "Unhandled vector element size in vector compare");
13036 }
13037
13038 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13041 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13044 if (TypeSize == Context.getTypeSize(Context.LongTy))
13047 if (TypeSize == Context.getTypeSize(Context.IntTy))
13050 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13053 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13054 "Unhandled vector element size in vector compare");
13057}
13058
13060 const BuiltinType *VTy = V->castAs<BuiltinType>();
13061 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13062
13063 const QualType ETy = V->getSveEltType(Context);
13064 const auto TypeSize = Context.getTypeSize(ETy);
13065
13066 const QualType IntTy = Context.getIntTypeForBitwidth(TypeSize, true);
13067 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VTy).EC;
13068 return Context.getScalableVectorType(IntTy, VecSize.getKnownMinValue());
13069}
13070
13071/// CheckVectorCompareOperands - vector comparisons are a clang extension that
13072/// operates on extended vector types. Instead of producing an IntTy result,
13073/// like a scalar comparison, a vector comparison produces a vector of integer
13074/// types.
13076 SourceLocation Loc,
13077 BinaryOperatorKind Opc) {
13078 if (Opc == BO_Cmp) {
13079 Diag(Loc, diag::err_three_way_vector_comparison);
13080 return QualType();
13081 }
13082
13083 // Check to make sure we're operating on vectors of the same type and width,
13084 // Allowing one side to be a scalar of element type.
13085 QualType vType =
13086 CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/ false,
13087 /*AllowBothBool*/ true,
13088 /*AllowBoolConversions*/ getLangOpts().ZVector,
13089 /*AllowBooleanOperation*/ true,
13090 /*ReportInvalid*/ true);
13091 if (vType.isNull())
13092 return vType;
13093
13094 QualType LHSType = LHS.get()->getType();
13095
13096 // Determine the return type of a vector compare. By default clang will return
13097 // a scalar for all vector compares except vector bool and vector pixel.
13098 // With the gcc compiler we will always return a vector type and with the xl
13099 // compiler we will always return a scalar type. This switch allows choosing
13100 // which behavior is prefered.
13101 if (getLangOpts().AltiVec) {
13102 switch (getLangOpts().getAltivecSrcCompat()) {
13104 // If AltiVec, the comparison results in a numeric type, i.e.
13105 // bool for C++, int for C
13106 if (vType->castAs<VectorType>()->getVectorKind() ==
13109 else
13110 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13111 break;
13113 // For GCC we always return the vector type.
13114 break;
13117 break;
13118 }
13119 }
13120
13121 // For non-floating point types, check for self-comparisons of the form
13122 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13123 // often indicate logic errors in the program.
13124 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13125
13126 // Check for comparisons of floating point operands using != and ==.
13127 if (LHSType->hasFloatingRepresentation()) {
13128 assert(RHS.get()->getType()->hasFloatingRepresentation());
13129 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13130 }
13131
13132 // Return a signed type for the vector.
13133 return GetSignedVectorType(vType);
13134}
13135
13137 ExprResult &RHS,
13138 SourceLocation Loc,
13139 BinaryOperatorKind Opc) {
13140 if (Opc == BO_Cmp) {
13141 Diag(Loc, diag::err_three_way_vector_comparison);
13142 return QualType();
13143 }
13144
13145 // Check to make sure we're operating on vectors of the same type and width,
13146 // Allowing one side to be a scalar of element type.
13148 LHS, RHS, Loc, /*isCompAssign*/ false, ACK_Comparison);
13149
13150 if (vType.isNull())
13151 return vType;
13152
13153 QualType LHSType = LHS.get()->getType();
13154
13155 // For non-floating point types, check for self-comparisons of the form
13156 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13157 // often indicate logic errors in the program.
13158 diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
13159
13160 // Check for comparisons of floating point operands using != and ==.
13161 if (LHSType->hasFloatingRepresentation()) {
13162 assert(RHS.get()->getType()->hasFloatingRepresentation());
13163 CheckFloatComparison(Loc, LHS.get(), RHS.get(), Opc);
13164 }
13165
13166 const BuiltinType *LHSBuiltinTy = LHSType->getAs<BuiltinType>();
13167 const BuiltinType *RHSBuiltinTy = RHS.get()->getType()->getAs<BuiltinType>();
13168
13169 if (LHSBuiltinTy && RHSBuiltinTy && LHSBuiltinTy->isSVEBool() &&
13170 RHSBuiltinTy->isSVEBool())
13171 return LHSType;
13172
13173 // Return a signed type for the vector.
13174 return GetSignedSizelessVectorType(vType);
13175}
13176
13177static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS,
13178 const ExprResult &XorRHS,
13179 const SourceLocation Loc) {
13180 // Do not diagnose macros.
13181 if (Loc.isMacroID())
13182 return;
13183
13184 // Do not diagnose if both LHS and RHS are macros.
13185 if (XorLHS.get()->getExprLoc().isMacroID() &&
13186 XorRHS.get()->getExprLoc().isMacroID())
13187 return;
13188
13189 bool Negative = false;
13190 bool ExplicitPlus = false;
13191 const auto *LHSInt = dyn_cast<IntegerLiteral>(XorLHS.get());
13192 const auto *RHSInt = dyn_cast<IntegerLiteral>(XorRHS.get());
13193
13194 if (!LHSInt)
13195 return;
13196 if (!RHSInt) {
13197 // Check negative literals.
13198 if (const auto *UO = dyn_cast<UnaryOperator>(XorRHS.get())) {
13199 UnaryOperatorKind Opc = UO->getOpcode();
13200 if (Opc != UO_Minus && Opc != UO_Plus)
13201 return;
13202 RHSInt = dyn_cast<IntegerLiteral>(UO->getSubExpr());
13203 if (!RHSInt)
13204 return;
13205 Negative = (Opc == UO_Minus);
13206 ExplicitPlus = !Negative;
13207 } else {
13208 return;
13209 }
13210 }
13211
13212 const llvm::APInt &LeftSideValue = LHSInt->getValue();
13213 llvm::APInt RightSideValue = RHSInt->getValue();
13214 if (LeftSideValue != 2 && LeftSideValue != 10)
13215 return;
13216
13217 if (LeftSideValue.getBitWidth() != RightSideValue.getBitWidth())
13218 return;
13219
13221 LHSInt->getBeginLoc(), S.getLocForEndOfToken(RHSInt->getLocation()));
13222 llvm::StringRef ExprStr =
13224
13225 CharSourceRange XorRange =
13227 llvm::StringRef XorStr =
13229 // Do not diagnose if xor keyword/macro is used.
13230 if (XorStr == "xor")
13231 return;
13232
13233 std::string LHSStr = std::string(Lexer::getSourceText(
13234 CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13235 S.getSourceManager(), S.getLangOpts()));
13236 std::string RHSStr = std::string(Lexer::getSourceText(
13237 CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13238 S.getSourceManager(), S.getLangOpts()));
13239
13240 if (Negative) {
13241 RightSideValue = -RightSideValue;
13242 RHSStr = "-" + RHSStr;
13243 } else if (ExplicitPlus) {
13244 RHSStr = "+" + RHSStr;
13245 }
13246
13247 StringRef LHSStrRef = LHSStr;
13248 StringRef RHSStrRef = RHSStr;
13249 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13250 // literals.
13251 if (LHSStrRef.starts_with("0b") || LHSStrRef.starts_with("0B") ||
13252 RHSStrRef.starts_with("0b") || RHSStrRef.starts_with("0B") ||
13253 LHSStrRef.starts_with("0x") || LHSStrRef.starts_with("0X") ||
13254 RHSStrRef.starts_with("0x") || RHSStrRef.starts_with("0X") ||
13255 (LHSStrRef.size() > 1 && LHSStrRef.starts_with("0")) ||
13256 (RHSStrRef.size() > 1 && RHSStrRef.starts_with("0")) ||
13257 LHSStrRef.contains('\'') || RHSStrRef.contains('\''))
13258 return;
13259
13260 bool SuggestXor =
13261 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined("xor");
13262 const llvm::APInt XorValue = LeftSideValue ^ RightSideValue;
13263 int64_t RightSideIntValue = RightSideValue.getSExtValue();
13264 if (LeftSideValue == 2 && RightSideIntValue >= 0) {
13265 std::string SuggestedExpr = "1 << " + RHSStr;
13266 bool Overflow = false;
13267 llvm::APInt One = (LeftSideValue - 1);
13268 llvm::APInt PowValue = One.sshl_ov(RightSideValue, Overflow);
13269 if (Overflow) {
13270 if (RightSideIntValue < 64)
13271 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13272 << ExprStr << toString(XorValue, 10, true) << ("1LL << " + RHSStr)
13273 << FixItHint::CreateReplacement(ExprRange, "1LL << " + RHSStr);
13274 else if (RightSideIntValue == 64)
13275 S.Diag(Loc, diag::warn_xor_used_as_pow)
13276 << ExprStr << toString(XorValue, 10, true);
13277 else
13278 return;
13279 } else {
13280 S.Diag(Loc, diag::warn_xor_used_as_pow_base_extra)
13281 << ExprStr << toString(XorValue, 10, true) << SuggestedExpr
13282 << toString(PowValue, 10, true)
13284 ExprRange, (RightSideIntValue == 0) ? "1" : SuggestedExpr);
13285 }
13286
13287 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13288 << ("0x2 ^ " + RHSStr) << SuggestXor;
13289 } else if (LeftSideValue == 10) {
13290 std::string SuggestedValue = "1e" + std::to_string(RightSideIntValue);
13291 S.Diag(Loc, diag::warn_xor_used_as_pow_base)
13292 << ExprStr << toString(XorValue, 10, true) << SuggestedValue
13293 << FixItHint::CreateReplacement(ExprRange, SuggestedValue);
13294 S.Diag(Loc, diag::note_xor_used_as_pow_silence)
13295 << ("0xA ^ " + RHSStr) << SuggestXor;
13296 }
13297}
13298
13300 SourceLocation Loc) {
13301 // Ensure that either both operands are of the same vector type, or
13302 // one operand is of a vector type and the other is of its element type.
13303 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
13304 /*AllowBothBool*/ true,
13305 /*AllowBoolConversions*/ false,
13306 /*AllowBooleanOperation*/ false,
13307 /*ReportInvalid*/ false);
13308 if (vType.isNull())
13309 return InvalidOperands(Loc, LHS, RHS);
13310 if (getLangOpts().OpenCL &&
13311 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13313 return InvalidOperands(Loc, LHS, RHS);
13314 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13315 // usage of the logical operators && and || with vectors in C. This
13316 // check could be notionally dropped.
13317 if (!getLangOpts().CPlusPlus &&
13318 !(isa<ExtVectorType>(vType->getAs<VectorType>())))
13319 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13320
13321 return GetSignedVectorType(LHS.get()->getType());
13322}
13323
13325 SourceLocation Loc,
13326 bool IsCompAssign) {
13327 if (!IsCompAssign) {
13329 if (LHS.isInvalid())
13330 return QualType();
13331 }
13333 if (RHS.isInvalid())
13334 return QualType();
13335
13336 // For conversion purposes, we ignore any qualifiers.
13337 // For example, "const float" and "float" are equivalent.
13338 QualType LHSType = LHS.get()->getType().getUnqualifiedType();
13339 QualType RHSType = RHS.get()->getType().getUnqualifiedType();
13340
13341 const MatrixType *LHSMatType = LHSType->getAs<MatrixType>();
13342 const MatrixType *RHSMatType = RHSType->getAs<MatrixType>();
13343 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13344
13345 if (Context.hasSameType(LHSType, RHSType))
13346 return Context.getCommonSugaredType(LHSType, RHSType);
13347
13348 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13349 // case we have to return InvalidOperands.
13350 ExprResult OriginalLHS = LHS;
13351 ExprResult OriginalRHS = RHS;
13352 if (LHSMatType && !RHSMatType) {
13353 RHS = tryConvertExprToType(RHS.get(), LHSMatType->getElementType());
13354 if (!RHS.isInvalid())
13355 return LHSType;
13356
13357 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13358 }
13359
13360 if (!LHSMatType && RHSMatType) {
13361 LHS = tryConvertExprToType(LHS.get(), RHSMatType->getElementType());
13362 if (!LHS.isInvalid())
13363 return RHSType;
13364 return InvalidOperands(Loc, OriginalLHS, OriginalRHS);
13365 }
13366
13367 return InvalidOperands(Loc, LHS, RHS);
13368}
13369
13371 SourceLocation Loc,
13372 bool IsCompAssign) {
13373 if (!IsCompAssign) {
13375 if (LHS.isInvalid())
13376 return QualType();
13377 }
13379 if (RHS.isInvalid())
13380 return QualType();
13381
13382 auto *LHSMatType = LHS.get()->getType()->getAs<ConstantMatrixType>();
13383 auto *RHSMatType = RHS.get()->getType()->getAs<ConstantMatrixType>();
13384 assert((LHSMatType || RHSMatType) && "At least one operand must be a matrix");
13385
13386 if (LHSMatType && RHSMatType) {
13387 if (LHSMatType->getNumColumns() != RHSMatType->getNumRows())
13388 return InvalidOperands(Loc, LHS, RHS);
13389
13390 if (Context.hasSameType(LHSMatType, RHSMatType))
13392 LHS.get()->getType().getUnqualifiedType(),
13393 RHS.get()->getType().getUnqualifiedType());
13394
13395 QualType LHSELTy = LHSMatType->getElementType(),
13396 RHSELTy = RHSMatType->getElementType();
13397 if (!Context.hasSameType(LHSELTy, RHSELTy))
13398 return InvalidOperands(Loc, LHS, RHS);
13399
13401 Context.getCommonSugaredType(LHSELTy, RHSELTy),
13402 LHSMatType->getNumRows(), RHSMatType->getNumColumns());
13403 }
13404 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13405}
13406
13408 switch (Opc) {
13409 default:
13410 return false;
13411 case BO_And:
13412 case BO_AndAssign:
13413 case BO_Or:
13414 case BO_OrAssign:
13415 case BO_Xor:
13416 case BO_XorAssign:
13417 return true;
13418 }
13419}
13420
13422 SourceLocation Loc,
13423 BinaryOperatorKind Opc) {
13424 checkArithmeticNull(*this, LHS, RHS, Loc, /*IsCompare=*/false);
13425
13426 bool IsCompAssign =
13427 Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
13428
13429 bool LegalBoolVecOperator = isLegalBoolVectorBinaryOp(Opc);
13430
13431 if (LHS.get()->getType()->isVectorType() ||
13432 RHS.get()->getType()->isVectorType()) {
13433 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13435 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13436 /*AllowBothBool*/ true,
13437 /*AllowBoolConversions*/ getLangOpts().ZVector,
13438 /*AllowBooleanOperation*/ LegalBoolVecOperator,
13439 /*ReportInvalid*/ true);
13440 return InvalidOperands(Loc, LHS, RHS);
13441 }
13442
13443 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13444 RHS.get()->getType()->isSveVLSBuiltinType()) {
13445 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13447 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13449 return InvalidOperands(Loc, LHS, RHS);
13450 }
13451
13452 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
13453 RHS.get()->getType()->isSveVLSBuiltinType()) {
13454 if (LHS.get()->getType()->hasIntegerRepresentation() &&
13456 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13458 return InvalidOperands(Loc, LHS, RHS);
13459 }
13460
13461 if (Opc == BO_And)
13462 diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
13463
13464 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13466 return InvalidOperands(Loc, LHS, RHS);
13467
13468 ExprResult LHSResult = LHS, RHSResult = RHS;
13470 LHSResult, RHSResult, Loc, IsCompAssign ? ACK_CompAssign : ACK_BitwiseOp);
13471 if (LHSResult.isInvalid() || RHSResult.isInvalid())
13472 return QualType();
13473 LHS = LHSResult.get();
13474 RHS = RHSResult.get();
13475
13476 if (Opc == BO_Xor)
13477 diagnoseXorMisusedAsPow(*this, LHS, RHS, Loc);
13478
13479 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
13480 return compType;
13481 return InvalidOperands(Loc, LHS, RHS);
13482}
13483
13484// C99 6.5.[13,14]
13486 SourceLocation Loc,
13487 BinaryOperatorKind Opc) {
13488 // Check vector operands differently.
13489 if (LHS.get()->getType()->isVectorType() ||
13490 RHS.get()->getType()->isVectorType())
13491 return CheckVectorLogicalOperands(LHS, RHS, Loc);
13492
13493 bool EnumConstantInBoolContext = false;
13494 for (const ExprResult &HS : {LHS, RHS}) {
13495 if (const auto *DREHS = dyn_cast<DeclRefExpr>(HS.get())) {
13496 const auto *ECDHS = dyn_cast<EnumConstantDecl>(DREHS->getDecl());
13497 if (ECDHS && ECDHS->getInitVal() != 0 && ECDHS->getInitVal() != 1)
13498 EnumConstantInBoolContext = true;
13499 }
13500 }
13501
13502 if (EnumConstantInBoolContext)
13503 Diag(Loc, diag::warn_enum_constant_in_bool_context);
13504
13505 // WebAssembly tables can't be used with logical operators.
13506 QualType LHSTy = LHS.get()->getType();
13507 QualType RHSTy = RHS.get()->getType();
13508 const auto *LHSATy = dyn_cast<ArrayType>(LHSTy);
13509 const auto *RHSATy = dyn_cast<ArrayType>(RHSTy);
13510 if ((LHSATy && LHSATy->getElementType().isWebAssemblyReferenceType()) ||
13511 (RHSATy && RHSATy->getElementType().isWebAssemblyReferenceType())) {
13512 return InvalidOperands(Loc, LHS, RHS);
13513 }
13514
13515 // Diagnose cases where the user write a logical and/or but probably meant a
13516 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13517 // is a constant.
13518 if (!EnumConstantInBoolContext && LHS.get()->getType()->isIntegerType() &&
13519 !LHS.get()->getType()->isBooleanType() &&
13520 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
13521 // Don't warn in macros or template instantiations.
13522 !Loc.isMacroID() && !inTemplateInstantiation()) {
13523 // If the RHS can be constant folded, and if it constant folds to something
13524 // that isn't 0 or 1 (which indicate a potential logical operation that
13525 // happened to fold to true/false) then warn.
13526 // Parens on the RHS are ignored.
13527 Expr::EvalResult EVResult;
13528 if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
13529 llvm::APSInt Result = EVResult.Val.getInt();
13530 if ((getLangOpts().CPlusPlus && !RHS.get()->getType()->isBooleanType() &&
13531 !RHS.get()->getExprLoc().isMacroID()) ||
13532 (Result != 0 && Result != 1)) {
13533 Diag(Loc, diag::warn_logical_instead_of_bitwise)
13534 << RHS.get()->getSourceRange() << (Opc == BO_LAnd ? "&&" : "||");
13535 // Suggest replacing the logical operator with the bitwise version
13536 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
13537 << (Opc == BO_LAnd ? "&" : "|")
13540 Opc == BO_LAnd ? "&" : "|");
13541 if (Opc == BO_LAnd)
13542 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13543 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
13546 RHS.get()->getEndLoc()));
13547 }
13548 }
13549 }
13550
13551 if (!Context.getLangOpts().CPlusPlus) {
13552 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13553 // not operate on the built-in scalar and vector float types.
13554 if (Context.getLangOpts().OpenCL &&
13555 Context.getLangOpts().OpenCLVersion < 120) {
13556 if (LHS.get()->getType()->isFloatingType() ||
13557 RHS.get()->getType()->isFloatingType())
13558 return InvalidOperands(Loc, LHS, RHS);
13559 }
13560
13561 LHS = UsualUnaryConversions(LHS.get());
13562 if (LHS.isInvalid())
13563 return QualType();
13564
13565 RHS = UsualUnaryConversions(RHS.get());
13566 if (RHS.isInvalid())
13567 return QualType();
13568
13569 if (!LHS.get()->getType()->isScalarType() ||
13570 !RHS.get()->getType()->isScalarType())
13571 return InvalidOperands(Loc, LHS, RHS);
13572
13573 return Context.IntTy;
13574 }
13575
13576 // The following is safe because we only use this method for
13577 // non-overloadable operands.
13578
13579 // C++ [expr.log.and]p1
13580 // C++ [expr.log.or]p1
13581 // The operands are both contextually converted to type bool.
13583 if (LHSRes.isInvalid())
13584 return InvalidOperands(Loc, LHS, RHS);
13585 LHS = LHSRes;
13586
13588 if (RHSRes.isInvalid())
13589 return InvalidOperands(Loc, LHS, RHS);
13590 RHS = RHSRes;
13591
13592 // C++ [expr.log.and]p2
13593 // C++ [expr.log.or]p2
13594 // The result is a bool.
13595 return Context.BoolTy;
13596}
13597
13598static bool IsReadonlyMessage(Expr *E, Sema &S) {
13599 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13600 if (!ME) return false;
13601 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
13602 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13604 if (!Base) return false;
13605 return Base->getMethodDecl() != nullptr;
13606}
13607
13608/// Is the given expression (which must be 'const') a reference to a
13609/// variable which was originally non-const, but which has become
13610/// 'const' due to being captured within a block?
13613 assert(E->isLValue() && E->getType().isConstQualified());
13614 E = E->IgnoreParens();
13615
13616 // Must be a reference to a declaration from an enclosing scope.
13617 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
13618 if (!DRE) return NCCK_None;
13620
13621 // The declaration must be a variable which is not declared 'const'.
13622 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
13623 if (!var) return NCCK_None;
13624 if (var->getType().isConstQualified()) return NCCK_None;
13625 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
13626
13627 // Decide whether the first capture was for a block or a lambda.
13628 DeclContext *DC = S.CurContext, *Prev = nullptr;
13629 // Decide whether the first capture was for a block or a lambda.
13630 while (DC) {
13631 // For init-capture, it is possible that the variable belongs to the
13632 // template pattern of the current context.
13633 if (auto *FD = dyn_cast<FunctionDecl>(DC))
13634 if (var->isInitCapture() &&
13635 FD->getTemplateInstantiationPattern() == var->getDeclContext())
13636 break;
13637 if (DC == var->getDeclContext())
13638 break;
13639 Prev = DC;
13640 DC = DC->getParent();
13641 }
13642 // Unless we have an init-capture, we've gone one step too far.
13643 if (!var->isInitCapture())
13644 DC = Prev;
13645 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
13646}
13647
13648static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
13649 Ty = Ty.getNonReferenceType();
13650 if (IsDereference && Ty->isPointerType())
13651 Ty = Ty->getPointeeType();
13652 return !Ty.isConstQualified();
13653}
13654
13655// Update err_typecheck_assign_const and note_typecheck_assign_const
13656// when this enum is changed.
13657enum {
13663 ConstUnknown, // Keep as last element
13664};
13665
13666/// Emit the "read-only variable not assignable" error and print notes to give
13667/// more information about why the variable is not assignable, such as pointing
13668/// to the declaration of a const variable, showing that a method is const, or
13669/// that the function is returning a const reference.
13670static void DiagnoseConstAssignment(Sema &S, const Expr *E,
13671 SourceLocation Loc) {
13672 SourceRange ExprRange = E->getSourceRange();
13673
13674 // Only emit one error on the first const found. All other consts will emit
13675 // a note to the error.
13676 bool DiagnosticEmitted = false;
13677
13678 // Track if the current expression is the result of a dereference, and if the
13679 // next checked expression is the result of a dereference.
13680 bool IsDereference = false;
13681 bool NextIsDereference = false;
13682
13683 // Loop to process MemberExpr chains.
13684 while (true) {
13685 IsDereference = NextIsDereference;
13686
13688 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13689 NextIsDereference = ME->isArrow();
13690 const ValueDecl *VD = ME->getMemberDecl();
13691 if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
13692 // Mutable fields can be modified even if the class is const.
13693 if (Field->isMutable()) {
13694 assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
13695 break;
13696 }
13697
13698 if (!IsTypeModifiable(Field->getType(), IsDereference)) {
13699 if (!DiagnosticEmitted) {
13700 S.Diag(Loc, diag::err_typecheck_assign_const)
13701 << ExprRange << ConstMember << false /*static*/ << Field
13702 << Field->getType();
13703 DiagnosticEmitted = true;
13704 }
13705 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13706 << ConstMember << false /*static*/ << Field << Field->getType()
13707 << Field->getSourceRange();
13708 }
13709 E = ME->getBase();
13710 continue;
13711 } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
13712 if (VDecl->getType().isConstQualified()) {
13713 if (!DiagnosticEmitted) {
13714 S.Diag(Loc, diag::err_typecheck_assign_const)
13715 << ExprRange << ConstMember << true /*static*/ << VDecl
13716 << VDecl->getType();
13717 DiagnosticEmitted = true;
13718 }
13719 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13720 << ConstMember << true /*static*/ << VDecl << VDecl->getType()
13721 << VDecl->getSourceRange();
13722 }
13723 // Static fields do not inherit constness from parents.
13724 break;
13725 }
13726 break; // End MemberExpr
13727 } else if (const ArraySubscriptExpr *ASE =
13728 dyn_cast<ArraySubscriptExpr>(E)) {
13729 E = ASE->getBase()->IgnoreParenImpCasts();
13730 continue;
13731 } else if (const ExtVectorElementExpr *EVE =
13732 dyn_cast<ExtVectorElementExpr>(E)) {
13733 E = EVE->getBase()->IgnoreParenImpCasts();
13734 continue;
13735 }
13736 break;
13737 }
13738
13739 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
13740 // Function calls
13741 const FunctionDecl *FD = CE->getDirectCallee();
13742 if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
13743 if (!DiagnosticEmitted) {
13744 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13745 << ConstFunction << FD;
13746 DiagnosticEmitted = true;
13747 }
13749 diag::note_typecheck_assign_const)
13750 << ConstFunction << FD << FD->getReturnType()
13751 << FD->getReturnTypeSourceRange();
13752 }
13753 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13754 // Point to variable declaration.
13755 if (const ValueDecl *VD = DRE->getDecl()) {
13756 if (!IsTypeModifiable(VD->getType(), IsDereference)) {
13757 if (!DiagnosticEmitted) {
13758 S.Diag(Loc, diag::err_typecheck_assign_const)
13759 << ExprRange << ConstVariable << VD << VD->getType();
13760 DiagnosticEmitted = true;
13761 }
13762 S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
13763 << ConstVariable << VD << VD->getType() << VD->getSourceRange();
13764 }
13765 }
13766 } else if (isa<CXXThisExpr>(E)) {
13767 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13768 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
13769 if (MD->isConst()) {
13770 if (!DiagnosticEmitted) {
13771 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13772 << ConstMethod << MD;
13773 DiagnosticEmitted = true;
13774 }
13775 S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
13776 << ConstMethod << MD << MD->getSourceRange();
13777 }
13778 }
13779 }
13780 }
13781
13782 if (DiagnosticEmitted)
13783 return;
13784
13785 // Can't determine a more specific message, so display the generic error.
13786 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
13787}
13788
13794
13796 const RecordType *Ty,
13797 SourceLocation Loc, SourceRange Range,
13798 OriginalExprKind OEK,
13799 bool &DiagnosticEmitted) {
13800 std::vector<const RecordType *> RecordTypeList;
13801 RecordTypeList.push_back(Ty);
13802 unsigned NextToCheckIndex = 0;
13803 // We walk the record hierarchy breadth-first to ensure that we print
13804 // diagnostics in field nesting order.
13805 while (RecordTypeList.size() > NextToCheckIndex) {
13806 bool IsNested = NextToCheckIndex > 0;
13807 for (const FieldDecl *Field :
13808 RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
13809 // First, check every field for constness.
13810 QualType FieldTy = Field->getType();
13811 if (FieldTy.isConstQualified()) {
13812 if (!DiagnosticEmitted) {
13813 S.Diag(Loc, diag::err_typecheck_assign_const)
13814 << Range << NestedConstMember << OEK << VD
13815 << IsNested << Field;
13816 DiagnosticEmitted = true;
13817 }
13818 S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
13819 << NestedConstMember << IsNested << Field
13820 << FieldTy << Field->getSourceRange();
13821 }
13822
13823 // Then we append it to the list to check next in order.
13824 FieldTy = FieldTy.getCanonicalType();
13825 if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
13826 if (!llvm::is_contained(RecordTypeList, FieldRecTy))
13827 RecordTypeList.push_back(FieldRecTy);
13828 }
13829 }
13830 ++NextToCheckIndex;
13831 }
13832}
13833
13834/// Emit an error for the case where a record we are trying to assign to has a
13835/// const-qualified field somewhere in its hierarchy.
13836static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
13837 SourceLocation Loc) {
13838 QualType Ty = E->getType();
13839 assert(Ty->isRecordType() && "lvalue was not record?");
13840 SourceRange Range = E->getSourceRange();
13841 const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
13842 bool DiagEmitted = false;
13843
13844 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
13845 DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
13846 Range, OEK_Member, DiagEmitted);
13847 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13848 DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
13849 Range, OEK_Variable, DiagEmitted);
13850 else
13851 DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
13852 Range, OEK_LValue, DiagEmitted);
13853 if (!DiagEmitted)
13854 DiagnoseConstAssignment(S, E, Loc);
13855}
13856
13857/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13858/// emit an error and return true. If so, return false.
13860 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13861
13863
13864 SourceLocation OrigLoc = Loc;
13866 &Loc);
13867 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13869 if (IsLV == Expr::MLV_Valid)
13870 return false;
13871
13872 unsigned DiagID = 0;
13873 bool NeedType = false;
13874 switch (IsLV) { // C99 6.5.16p2
13876 // Use a specialized diagnostic when we're assigning to an object
13877 // from an enclosing function or block.
13879 if (NCCK == NCCK_Block)
13880 DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
13881 else
13882 DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
13883 break;
13884 }
13885
13886 // In ARC, use some specialized diagnostics for occasions where we
13887 // infer 'const'. These are always pseudo-strong variables.
13888 if (S.getLangOpts().ObjCAutoRefCount) {
13889 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
13890 if (declRef && isa<VarDecl>(declRef->getDecl())) {
13891 VarDecl *var = cast<VarDecl>(declRef->getDecl());
13892
13893 // Use the normal diagnostic if it's pseudo-__strong but the
13894 // user actually wrote 'const'.
13895 if (var->isARCPseudoStrong() &&
13896 (!var->getTypeSourceInfo() ||
13898 // There are three pseudo-strong cases:
13899 // - self
13900 ObjCMethodDecl *method = S.getCurMethodDecl();
13901 if (method && var == method->getSelfDecl()) {
13902 DiagID = method->isClassMethod()
13903 ? diag::err_typecheck_arc_assign_self_class_method
13904 : diag::err_typecheck_arc_assign_self;
13905
13906 // - Objective-C externally_retained attribute.
13907 } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
13908 isa<ParmVarDecl>(var)) {
13909 DiagID = diag::err_typecheck_arc_assign_externally_retained;
13910
13911 // - fast enumeration variables
13912 } else {
13913 DiagID = diag::err_typecheck_arr_assign_enumeration;
13914 }
13915
13916 SourceRange Assign;
13917 if (Loc != OrigLoc)
13918 Assign = SourceRange(OrigLoc, OrigLoc);
13919 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13920 // We need to preserve the AST regardless, so migration tool
13921 // can do its job.
13922 return false;
13923 }
13924 }
13925 }
13926
13927 // If none of the special cases above are triggered, then this is a
13928 // simple const assignment.
13929 if (DiagID == 0) {
13930 DiagnoseConstAssignment(S, E, Loc);
13931 return true;
13932 }
13933
13934 break;
13936 DiagnoseConstAssignment(S, E, Loc);
13937 return true;
13940 return true;
13943 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13944 NeedType = true;
13945 break;
13947 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13948 NeedType = true;
13949 break;
13951 DiagID = diag::err_typecheck_lvalue_casts_not_supported;
13952 break;
13953 case Expr::MLV_Valid:
13954 llvm_unreachable("did not take early return for MLV_Valid");
13958 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13959 break;
13962 return S.RequireCompleteType(Loc, E->getType(),
13963 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13965 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13966 break;
13968 llvm_unreachable("readonly properties should be processed differently");
13970 DiagID = diag::err_readonly_message_assignment;
13971 break;
13973 DiagID = diag::err_no_subobject_property_setting;
13974 break;
13975 }
13976
13977 SourceRange Assign;
13978 if (Loc != OrigLoc)
13979 Assign = SourceRange(OrigLoc, OrigLoc);
13980 if (NeedType)
13981 S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
13982 else
13983 S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
13984 return true;
13985}
13986
13987static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
13988 SourceLocation Loc,
13989 Sema &Sema) {
13991 return;
13993 return;
13994 if (Loc.isInvalid() || Loc.isMacroID())
13995 return;
13996 if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
13997 return;
13998
13999 // C / C++ fields
14000 MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
14001 MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
14002 if (ML && MR) {
14003 if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
14004 return;
14005 const ValueDecl *LHSDecl =
14006 cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
14007 const ValueDecl *RHSDecl =
14008 cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
14009 if (LHSDecl != RHSDecl)
14010 return;
14011 if (LHSDecl->getType().isVolatileQualified())
14012 return;
14013 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14014 if (RefTy->getPointeeType().isVolatileQualified())
14015 return;
14016
14017 Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
14018 }
14019
14020 // Objective-C instance variables
14021 ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
14022 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
14023 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14024 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
14025 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
14026 if (RL && RR && RL->getDecl() == RR->getDecl())
14027 Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
14028 }
14029}
14030
14031// C99 6.5.16.1
14033 SourceLocation Loc,
14034 QualType CompoundType,
14035 BinaryOperatorKind Opc) {
14036 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
14037
14038 // Verify that LHS is a modifiable lvalue, and emit error if not.
14039 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
14040 return QualType();
14041
14042 QualType LHSType = LHSExpr->getType();
14043 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
14044 CompoundType;
14045 // OpenCL v1.2 s6.1.1.1 p2:
14046 // The half data type can only be used to declare a pointer to a buffer that
14047 // contains half values
14048 if (getLangOpts().OpenCL &&
14049 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14050 LHSType->isHalfType()) {
14051 Diag(Loc, diag::err_opencl_half_load_store) << 1
14052 << LHSType.getUnqualifiedType();
14053 return QualType();
14054 }
14055
14056 // WebAssembly tables can't be used on RHS of an assignment expression.
14057 if (RHSType->isWebAssemblyTableType()) {
14058 Diag(Loc, diag::err_wasm_table_art) << 0;
14059 return QualType();
14060 }
14061
14062 AssignConvertType ConvTy;
14063 if (CompoundType.isNull()) {
14064 Expr *RHSCheck = RHS.get();
14065
14066 CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
14067
14068 QualType LHSTy(LHSType);
14069 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
14070 if (RHS.isInvalid())
14071 return QualType();
14072 // Special case of NSObject attributes on c-style pointer types.
14073 if (ConvTy == IncompatiblePointer &&
14074 ((Context.isObjCNSObjectType(LHSType) &&
14075 RHSType->isObjCObjectPointerType()) ||
14076 (Context.isObjCNSObjectType(RHSType) &&
14077 LHSType->isObjCObjectPointerType())))
14078 ConvTy = Compatible;
14079
14080 if (ConvTy == Compatible &&
14081 LHSType->isObjCObjectType())
14082 Diag(Loc, diag::err_objc_object_assignment)
14083 << LHSType;
14084
14085 // If the RHS is a unary plus or minus, check to see if they = and + are
14086 // right next to each other. If so, the user may have typo'd "x =+ 4"
14087 // instead of "x += 4".
14088 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
14089 RHSCheck = ICE->getSubExpr();
14090 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
14091 if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
14092 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
14093 // Only if the two operators are exactly adjacent.
14094 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
14095 // And there is a space or other character before the subexpr of the
14096 // unary +/-. We don't want to warn on "x=-1".
14097 Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
14098 UO->getSubExpr()->getBeginLoc().isFileID()) {
14099 Diag(Loc, diag::warn_not_compound_assign)
14100 << (UO->getOpcode() == UO_Plus ? "+" : "-")
14101 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
14102 }
14103 }
14104
14105 if (ConvTy == Compatible) {
14106 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
14107 // Warn about retain cycles where a block captures the LHS, but
14108 // not if the LHS is a simple variable into which the block is
14109 // being stored...unless that variable can be captured by reference!
14110 const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
14111 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
14112 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14113 checkRetainCycles(LHSExpr, RHS.get());
14114 }
14115
14116 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14118 // It is safe to assign a weak reference into a strong variable.
14119 // Although this code can still have problems:
14120 // id x = self.weakProp;
14121 // id y = self.weakProp;
14122 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14123 // paths through the function. This should be revisited if
14124 // -Wrepeated-use-of-weak is made flow-sensitive.
14125 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14126 // variable, which will be valid for the current autorelease scope.
14127 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
14128 RHS.get()->getBeginLoc()))
14130
14131 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14132 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
14133 }
14134 }
14135 } else {
14136 // Compound assignment "x += y"
14137 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14138 }
14139
14140 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
14141 RHS.get(), AA_Assigning))
14142 return QualType();
14143
14144 CheckForNullPointerDereference(*this, LHSExpr);
14145
14146 if (getLangOpts().CPlusPlus20 && LHSType.isVolatileQualified()) {
14147 if (CompoundType.isNull()) {
14148 // C++2a [expr.ass]p5:
14149 // A simple-assignment whose left operand is of a volatile-qualified
14150 // type is deprecated unless the assignment is either a discarded-value
14151 // expression or an unevaluated operand
14152 ExprEvalContexts.back().VolatileAssignmentLHSs.push_back(LHSExpr);
14153 }
14154 }
14155
14156 // C11 6.5.16p3: The type of an assignment expression is the type of the
14157 // left operand would have after lvalue conversion.
14158 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14159 // qualified type, the value has the unqualified version of the type of the
14160 // lvalue; additionally, if the lvalue has atomic type, the value has the
14161 // non-atomic version of the type of the lvalue.
14162 // C++ 5.17p1: the type of the assignment expression is that of its left
14163 // operand.
14164 return getLangOpts().CPlusPlus ? LHSType : LHSType.getAtomicUnqualifiedType();
14165}
14166
14167// Scenarios to ignore if expression E is:
14168// 1. an explicit cast expression into void
14169// 2. a function call expression that returns void
14170static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context) {
14171 E = E->IgnoreParens();
14172
14173 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
14174 if (CE->getCastKind() == CK_ToVoid) {
14175 return true;
14176 }
14177
14178 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14179 if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
14180 CE->getSubExpr()->getType()->isDependentType()) {
14181 return true;
14182 }
14183 }
14184
14185 if (const auto *CE = dyn_cast<CallExpr>(E))
14186 return CE->getCallReturnType(Context)->isVoidType();
14187 return false;
14188}
14189
14190// Look for instances where it is likely the comma operator is confused with
14191// another operator. There is an explicit list of acceptable expressions for
14192// the left hand side of the comma operator, otherwise emit a warning.
14194 // No warnings in macros
14195 if (Loc.isMacroID())
14196 return;
14197
14198 // Don't warn in template instantiations.
14200 return;
14201
14202 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14203 // instead, skip more than needed, then call back into here with the
14204 // CommaVisitor in SemaStmt.cpp.
14205 // The listed locations are the initialization and increment portions
14206 // of a for loop. The additional checks are on the condition of
14207 // if statements, do/while loops, and for loops.
14208 // Differences in scope flags for C89 mode requires the extra logic.
14209 const unsigned ForIncrementFlags =
14210 getLangOpts().C99 || getLangOpts().CPlusPlus
14213 const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
14214 const unsigned ScopeFlags = getCurScope()->getFlags();
14215 if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
14216 (ScopeFlags & ForInitFlags) == ForInitFlags)
14217 return;
14218
14219 // If there are multiple comma operators used together, get the RHS of the
14220 // of the comma operator as the LHS.
14221 while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
14222 if (BO->getOpcode() != BO_Comma)
14223 break;
14224 LHS = BO->getRHS();
14225 }
14226
14227 // Only allow some expressions on LHS to not warn.
14228 if (IgnoreCommaOperand(LHS, Context))
14229 return;
14230
14231 Diag(Loc, diag::warn_comma_operator);
14232 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14233 << LHS->getSourceRange()
14235 LangOpts.CPlusPlus ? "static_cast<void>("
14236 : "(void)(")
14238 ")");
14239}
14240
14241// C99 6.5.17
14243 SourceLocation Loc) {
14244 LHS = S.CheckPlaceholderExpr(LHS.get());
14245 RHS = S.CheckPlaceholderExpr(RHS.get());
14246 if (LHS.isInvalid() || RHS.isInvalid())
14247 return QualType();
14248
14249 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14250 // operands, but not unary promotions.
14251 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14252
14253 // So we treat the LHS as a ignored value, and in C++ we allow the
14254 // containing site to determine what should be done with the RHS.
14255 LHS = S.IgnoredValueConversions(LHS.get());
14256 if (LHS.isInvalid())
14257 return QualType();
14258
14259 S.DiagnoseUnusedExprResult(LHS.get(), diag::warn_unused_comma_left_operand);
14260
14261 if (!S.getLangOpts().CPlusPlus) {
14263 if (RHS.isInvalid())
14264 return QualType();
14265 if (!RHS.get()->getType()->isVoidType())
14266 S.RequireCompleteType(Loc, RHS.get()->getType(),
14267 diag::err_incomplete_type);
14268 }
14269
14270 if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
14271 S.DiagnoseCommaOperator(LHS.get(), Loc);
14272
14273 return RHS.get()->getType();
14274}
14275
14276/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14277/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14279 ExprValueKind &VK,
14280 ExprObjectKind &OK,
14281 SourceLocation OpLoc,
14282 bool IsInc, bool IsPrefix) {
14283 if (Op->isTypeDependent())
14284 return S.Context.DependentTy;
14285
14286 QualType ResType = Op->getType();
14287 // Atomic types can be used for increment / decrement where the non-atomic
14288 // versions can, so ignore the _Atomic() specifier for the purpose of
14289 // checking.
14290 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
14291 ResType = ResAtomicType->getValueType();
14292
14293 assert(!ResType.isNull() && "no type for increment/decrement expression");
14294
14295 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
14296 // Decrement of bool is not allowed.
14297 if (!IsInc) {
14298 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
14299 return QualType();
14300 }
14301 // Increment of bool sets it to true, but is deprecated.
14302 S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
14303 : diag::warn_increment_bool)
14304 << Op->getSourceRange();
14305 } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
14306 // Error on enum increments and decrements in C++ mode
14307 S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
14308 return QualType();
14309 } else if (ResType->isRealType()) {
14310 // OK!
14311 } else if (ResType->isPointerType()) {
14312 // C99 6.5.2.4p2, 6.5.6p2
14313 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
14314 return QualType();
14315 } else if (ResType->isObjCObjectPointerType()) {
14316 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14317 // Otherwise, we just need a complete type.
14318 if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
14319 checkArithmeticOnObjCPointer(S, OpLoc, Op))
14320 return QualType();
14321 } else if (ResType->isAnyComplexType()) {
14322 // C99 does not support ++/-- on complex types, we allow as an extension.
14323 S.Diag(OpLoc, diag::ext_increment_complex)
14324 << IsInc << Op->getSourceRange();
14325 } else if (ResType->isPlaceholderType()) {
14327 if (PR.isInvalid()) return QualType();
14328 return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
14329 IsInc, IsPrefix);
14330 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
14331 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14332 } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
14333 (ResType->castAs<VectorType>()->getVectorKind() !=
14335 // The z vector extensions allow ++ and -- for non-bool vectors.
14336 } else if (S.getLangOpts().OpenCL && ResType->isVectorType() &&
14337 ResType->castAs<VectorType>()->getElementType()->isIntegerType()) {
14338 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14339 } else {
14340 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
14341 << ResType << int(IsInc) << Op->getSourceRange();
14342 return QualType();
14343 }
14344 // At this point, we know we have a real, complex or pointer type.
14345 // Now make sure the operand is a modifiable lvalue.
14346 if (CheckForModifiableLvalue(Op, OpLoc, S))
14347 return QualType();
14348 if (S.getLangOpts().CPlusPlus20 && ResType.isVolatileQualified()) {
14349 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14350 // An operand with volatile-qualified type is deprecated
14351 S.Diag(OpLoc, diag::warn_deprecated_increment_decrement_volatile)
14352 << IsInc << ResType;
14353 }
14354 // In C++, a prefix increment is the same type as the operand. Otherwise
14355 // (in C or with postfix), the increment is the unqualified type of the
14356 // operand.
14357 if (IsPrefix && S.getLangOpts().CPlusPlus) {
14358 VK = VK_LValue;
14359 OK = Op->getObjectKind();
14360 return ResType;
14361 } else {
14362 VK = VK_PRValue;
14363 return ResType.getUnqualifiedType();
14364 }
14365}
14366
14367
14368/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14369/// This routine allows us to typecheck complex/recursive expressions
14370/// where the declaration is needed for type checking. We only need to
14371/// handle cases when the expression references a function designator
14372/// or is an lvalue. Here are some examples:
14373/// - &(x) => x
14374/// - &*****f => f for f a function designator.
14375/// - &s.xx => s
14376/// - &s.zz[1].yy -> s, if zz is an array
14377/// - *(x + 1) -> x, if x is an array
14378/// - &"123"[2] -> 0
14379/// - & __real__ x -> x
14380///
14381/// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14382/// members.
14384 switch (E->getStmtClass()) {
14385 case Stmt::DeclRefExprClass:
14386 return cast<DeclRefExpr>(E)->getDecl();
14387 case Stmt::MemberExprClass:
14388 // If this is an arrow operator, the address is an offset from
14389 // the base's value, so the object the base refers to is
14390 // irrelevant.
14391 if (cast<MemberExpr>(E)->isArrow())
14392 return nullptr;
14393 // Otherwise, the expression refers to a part of the base
14394 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
14395 case Stmt::ArraySubscriptExprClass: {
14396 // FIXME: This code shouldn't be necessary! We should catch the implicit
14397 // promotion of register arrays earlier.
14398 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
14399 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
14400 if (ICE->getSubExpr()->getType()->isArrayType())
14401 return getPrimaryDecl(ICE->getSubExpr());
14402 }
14403 return nullptr;
14404 }
14405 case Stmt::UnaryOperatorClass: {
14406 UnaryOperator *UO = cast<UnaryOperator>(E);
14407
14408 switch(UO->getOpcode()) {
14409 case UO_Real:
14410 case UO_Imag:
14411 case UO_Extension:
14412 return getPrimaryDecl(UO->getSubExpr());
14413 default:
14414 return nullptr;
14415 }
14416 }
14417 case Stmt::ParenExprClass:
14418 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
14419 case Stmt::ImplicitCastExprClass:
14420 // If the result of an implicit cast is an l-value, we care about
14421 // the sub-expression; otherwise, the result here doesn't matter.
14422 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
14423 case Stmt::CXXUuidofExprClass:
14424 return cast<CXXUuidofExpr>(E)->getGuidDecl();
14425 default:
14426 return nullptr;
14427 }
14428}
14429
14430namespace {
14431enum {
14432 AO_Bit_Field = 0,
14433 AO_Vector_Element = 1,
14434 AO_Property_Expansion = 2,
14435 AO_Register_Variable = 3,
14436 AO_Matrix_Element = 4,
14437 AO_No_Error = 5
14438};
14439}
14440/// Diagnose invalid operand for address of operations.
14441///
14442/// \param Type The type of operand which cannot have its address taken.
14444 Expr *E, unsigned Type) {
14445 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14446}
14447
14449 const Expr *Op,
14450 const CXXMethodDecl *MD) {
14451 const auto *DRE = cast<DeclRefExpr>(Op->IgnoreParens());
14452
14453 if (Op != DRE)
14454 return Diag(OpLoc, diag::err_parens_pointer_member_function)
14455 << Op->getSourceRange();
14456
14457 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14458 if (isa<CXXDestructorDecl>(MD))
14459 return Diag(OpLoc, diag::err_typecheck_addrof_dtor)
14460 << DRE->getSourceRange();
14461
14462 if (DRE->getQualifier())
14463 return false;
14464
14465 if (MD->getParent()->getName().empty())
14466 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14467 << DRE->getSourceRange();
14468
14469 SmallString<32> Str;
14470 StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
14471 return Diag(OpLoc, diag::err_unqualified_pointer_member_function)
14472 << DRE->getSourceRange()
14473 << FixItHint::CreateInsertion(DRE->getSourceRange().getBegin(), Qual);
14474}
14475
14476/// CheckAddressOfOperand - The operand of & must be either a function
14477/// designator or an lvalue designating an object. If it is an lvalue, the
14478/// object cannot be declared with storage class register or be a bit field.
14479/// Note: The usual conversions are *not* applied to the operand of the &
14480/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14481/// In C++, the operand might be an overloaded function name, in which case
14482/// we allow the '&' but retain the overloaded-function type.
14484 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
14485 if (PTy->getKind() == BuiltinType::Overload) {
14486 Expr *E = OrigOp.get()->IgnoreParens();
14487 if (!isa<OverloadExpr>(E)) {
14488 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
14489 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
14490 << OrigOp.get()->getSourceRange();
14491 return QualType();
14492 }
14493
14494 OverloadExpr *Ovl = cast<OverloadExpr>(E);
14495 if (isa<UnresolvedMemberExpr>(Ovl))
14497 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14498 << OrigOp.get()->getSourceRange();
14499 return QualType();
14500 }
14501
14502 return Context.OverloadTy;
14503 }
14504
14505 if (PTy->getKind() == BuiltinType::UnknownAny)
14506 return Context.UnknownAnyTy;
14507
14508 if (PTy->getKind() == BuiltinType::BoundMember) {
14509 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14510 << OrigOp.get()->getSourceRange();
14511 return QualType();
14512 }
14513
14514 OrigOp = CheckPlaceholderExpr(OrigOp.get());
14515 if (OrigOp.isInvalid()) return QualType();
14516 }
14517
14518 if (OrigOp.get()->isTypeDependent())
14519 return Context.DependentTy;
14520
14521 assert(!OrigOp.get()->hasPlaceholderType());
14522
14523 // Make sure to ignore parentheses in subsequent checks
14524 Expr *op = OrigOp.get()->IgnoreParens();
14525
14526 // In OpenCL captures for blocks called as lambda functions
14527 // are located in the private address space. Blocks used in
14528 // enqueue_kernel can be located in a different address space
14529 // depending on a vendor implementation. Thus preventing
14530 // taking an address of the capture to avoid invalid AS casts.
14531 if (LangOpts.OpenCL) {
14532 auto* VarRef = dyn_cast<DeclRefExpr>(op);
14533 if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
14534 Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
14535 return QualType();
14536 }
14537 }
14538
14539 if (getLangOpts().C99) {
14540 // Implement C99-only parts of addressof rules.
14541 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
14542 if (uOp->getOpcode() == UO_Deref)
14543 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14544 // (assuming the deref expression is valid).
14545 return uOp->getSubExpr()->getType();
14546 }
14547 // Technically, there should be a check for array subscript
14548 // expressions here, but the result of one is always an lvalue anyway.
14549 }
14550 ValueDecl *dcl = getPrimaryDecl(op);
14551
14552 if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
14553 if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14554 op->getBeginLoc()))
14555 return QualType();
14556
14558 unsigned AddressOfError = AO_No_Error;
14559
14560 if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
14561 bool sfinae = (bool)isSFINAEContext();
14562 Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14563 : diag::ext_typecheck_addrof_temporary)
14564 << op->getType() << op->getSourceRange();
14565 if (sfinae)
14566 return QualType();
14567 // Materialize the temporary as an lvalue so that we can take its address.
14568 OrigOp = op =
14569 CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
14570 } else if (isa<ObjCSelectorExpr>(op)) {
14571 return Context.getPointerType(op->getType());
14572 } else if (lval == Expr::LV_MemberFunction) {
14573 // If it's an instance method, make a member pointer.
14574 // The expression must have exactly the form &A::foo.
14575
14576 // If the underlying expression isn't a decl ref, give up.
14577 if (!isa<DeclRefExpr>(op)) {
14578 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14579 << OrigOp.get()->getSourceRange();
14580 return QualType();
14581 }
14582 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
14583 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
14584
14585 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14586
14589 // Under the MS ABI, lock down the inheritance model now.
14591 (void)isCompleteType(OpLoc, MPTy);
14592 return MPTy;
14593 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
14594 // C99 6.5.3.2p1
14595 // The operand must be either an l-value or a function designator
14596 if (!op->getType()->isFunctionType()) {
14597 // Use a special diagnostic for loads from property references.
14598 if (isa<PseudoObjectExpr>(op)) {
14599 AddressOfError = AO_Property_Expansion;
14600 } else {
14601 Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
14602 << op->getType() << op->getSourceRange();
14603 return QualType();
14604 }
14605 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(op)) {
14606 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(DRE->getDecl()))
14607 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, OrigOp.get(), MD);
14608 }
14609
14610 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
14611 // The operand cannot be a bit-field
14612 AddressOfError = AO_Bit_Field;
14613 } else if (op->getObjectKind() == OK_VectorComponent) {
14614 // The operand cannot be an element of a vector
14615 AddressOfError = AO_Vector_Element;
14616 } else if (op->getObjectKind() == OK_MatrixComponent) {
14617 // The operand cannot be an element of a matrix.
14618 AddressOfError = AO_Matrix_Element;
14619 } else if (dcl) { // C99 6.5.3.2p1
14620 // We have an lvalue with a decl. Make sure the decl is not declared
14621 // with the register storage-class specifier.
14622 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
14623 // in C++ it is not error to take address of a register
14624 // variable (c++03 7.1.1P3)
14625 if (vd->getStorageClass() == SC_Register &&
14627 AddressOfError = AO_Register_Variable;
14628 }
14629 } else if (isa<MSPropertyDecl>(dcl)) {
14630 AddressOfError = AO_Property_Expansion;
14631 } else if (isa<FunctionTemplateDecl>(dcl)) {
14632 return Context.OverloadTy;
14633 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
14634 // Okay: we can take the address of a field.
14635 // Could be a pointer to member, though, if there is an explicit
14636 // scope qualifier for the class.
14637 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
14638 DeclContext *Ctx = dcl->getDeclContext();
14639 if (Ctx && Ctx->isRecord()) {
14640 if (dcl->getType()->isReferenceType()) {
14641 Diag(OpLoc,
14642 diag::err_cannot_form_pointer_to_member_of_reference_type)
14643 << dcl->getDeclName() << dcl->getType();
14644 return QualType();
14645 }
14646
14647 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
14648 Ctx = Ctx->getParent();
14649
14651 op->getType(),
14652 Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
14653 // Under the MS ABI, lock down the inheritance model now.
14655 (void)isCompleteType(OpLoc, MPTy);
14656 return MPTy;
14657 }
14658 }
14661 llvm_unreachable("Unknown/unexpected decl type");
14662 }
14663
14664 if (AddressOfError != AO_No_Error) {
14665 diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
14666 return QualType();
14667 }
14668
14669 if (lval == Expr::LV_IncompleteVoidType) {
14670 // Taking the address of a void variable is technically illegal, but we
14671 // allow it in cases which are otherwise valid.
14672 // Example: "extern void x; void* y = &x;".
14673 Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
14674 }
14675
14676 // If the operand has type "type", the result has type "pointer to type".
14677 if (op->getType()->isObjCObjectType())
14679
14680 // Cannot take the address of WebAssembly references or tables.
14681 if (Context.getTargetInfo().getTriple().isWasm()) {
14682 QualType OpTy = op->getType();
14683 if (OpTy.isWebAssemblyReferenceType()) {
14684 Diag(OpLoc, diag::err_wasm_ca_reference)
14685 << 1 << OrigOp.get()->getSourceRange();
14686 return QualType();
14687 }
14688 if (OpTy->isWebAssemblyTableType()) {
14689 Diag(OpLoc, diag::err_wasm_table_pr)
14690 << 1 << OrigOp.get()->getSourceRange();
14691 return QualType();
14692 }
14693 }
14694
14695 CheckAddressOfPackedMember(op);
14696
14697 return Context.getPointerType(op->getType());
14698}
14699
14700static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14701 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
14702 if (!DRE)
14703 return;
14704 const Decl *D = DRE->getDecl();
14705 if (!D)
14706 return;
14707 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
14708 if (!Param)
14709 return;
14710 if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
14711 if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
14712 return;
14713 if (FunctionScopeInfo *FD = S.getCurFunction())
14714 FD->ModifiedNonNullParams.insert(Param);
14715}
14716
14717/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14719 SourceLocation OpLoc,
14720 bool IsAfterAmp = false) {
14721 if (Op->isTypeDependent())
14722 return S.Context.DependentTy;
14723
14724 ExprResult ConvResult = S.UsualUnaryConversions(Op);
14725 if (ConvResult.isInvalid())
14726 return QualType();
14727 Op = ConvResult.get();
14728 QualType OpTy = Op->getType();
14730
14731 if (isa<CXXReinterpretCastExpr>(Op)) {
14732 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14733 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
14734 Op->getSourceRange());
14735 }
14736
14737 if (const PointerType *PT = OpTy->getAs<PointerType>())
14738 {
14739 Result = PT->getPointeeType();
14740 }
14741 else if (const ObjCObjectPointerType *OPT =
14743 Result = OPT->getPointeeType();
14744 else {
14746 if (PR.isInvalid()) return QualType();
14747 if (PR.get() != Op)
14748 return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
14749 }
14750
14751 if (Result.isNull()) {
14752 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
14753 << OpTy << Op->getSourceRange();
14754 return QualType();
14755 }
14756
14757 if (Result->isVoidType()) {
14758 // C++ [expr.unary.op]p1:
14759 // [...] the expression to which [the unary * operator] is applied shall
14760 // be a pointer to an object type, or a pointer to a function type
14761 LangOptions LO = S.getLangOpts();
14762 if (LO.CPlusPlus)
14763 S.Diag(OpLoc, diag::err_typecheck_indirection_through_void_pointer_cpp)
14764 << OpTy << Op->getSourceRange();
14765 else if (!(LO.C99 && IsAfterAmp) && !S.isUnevaluatedContext())
14766 S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
14767 << OpTy << Op->getSourceRange();
14768 }
14769
14770 // Dereferences are usually l-values...
14771 VK = VK_LValue;
14772
14773 // ...except that certain expressions are never l-values in C.
14774 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
14775 VK = VK_PRValue;
14776
14777 return Result;
14778}
14779
14780BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
14782 switch (Kind) {
14783 default: llvm_unreachable("Unknown binop!");
14784 case tok::periodstar: Opc = BO_PtrMemD; break;
14785 case tok::arrowstar: Opc = BO_PtrMemI; break;
14786 case tok::star: Opc = BO_Mul; break;
14787 case tok::slash: Opc = BO_Div; break;
14788 case tok::percent: Opc = BO_Rem; break;
14789 case tok::plus: Opc = BO_Add; break;
14790 case tok::minus: Opc = BO_Sub; break;
14791 case tok::lessless: Opc = BO_Shl; break;
14792 case tok::greatergreater: Opc = BO_Shr; break;
14793 case tok::lessequal: Opc = BO_LE; break;
14794 case tok::less: Opc = BO_LT; break;
14795 case tok::greaterequal: Opc = BO_GE; break;
14796 case tok::greater: Opc = BO_GT; break;
14797 case tok::exclaimequal: Opc = BO_NE; break;
14798 case tok::equalequal: Opc = BO_EQ; break;
14799 case tok::spaceship: Opc = BO_Cmp; break;
14800 case tok::amp: Opc = BO_And; break;
14801 case tok::caret: Opc = BO_Xor; break;
14802 case tok::pipe: Opc = BO_Or; break;
14803 case tok::ampamp: Opc = BO_LAnd; break;
14804 case tok::pipepipe: Opc = BO_LOr; break;
14805 case tok::equal: Opc = BO_Assign; break;
14806 case tok::starequal: Opc = BO_MulAssign; break;
14807 case tok::slashequal: Opc = BO_DivAssign; break;
14808 case tok::percentequal: Opc = BO_RemAssign; break;
14809 case tok::plusequal: Opc = BO_AddAssign; break;
14810 case tok::minusequal: Opc = BO_SubAssign; break;
14811 case tok::lesslessequal: Opc = BO_ShlAssign; break;
14812 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
14813 case tok::ampequal: Opc = BO_AndAssign; break;
14814 case tok::caretequal: Opc = BO_XorAssign; break;
14815 case tok::pipeequal: Opc = BO_OrAssign; break;
14816 case tok::comma: Opc = BO_Comma; break;
14817 }
14818 return Opc;
14819}
14820
14822 tok::TokenKind Kind) {
14824 switch (Kind) {
14825 default: llvm_unreachable("Unknown unary op!");
14826 case tok::plusplus: Opc = UO_PreInc; break;
14827 case tok::minusminus: Opc = UO_PreDec; break;
14828 case tok::amp: Opc = UO_AddrOf; break;
14829 case tok::star: Opc = UO_Deref; break;
14830 case tok::plus: Opc = UO_Plus; break;
14831 case tok::minus: Opc = UO_Minus; break;
14832 case tok::tilde: Opc = UO_Not; break;
14833 case tok::exclaim: Opc = UO_LNot; break;
14834 case tok::kw___real: Opc = UO_Real; break;
14835 case tok::kw___imag: Opc = UO_Imag; break;
14836 case tok::kw___extension__: Opc = UO_Extension; break;
14837 }
14838 return Opc;
14839}
14840
14841const FieldDecl *
14843 // Explore the case for adding 'this->' to the LHS of a self assignment, very
14844 // common for setters.
14845 // struct A {
14846 // int X;
14847 // -void setX(int X) { X = X; }
14848 // +void setX(int X) { this->X = X; }
14849 // };
14850
14851 // Only consider parameters for self assignment fixes.
14852 if (!isa<ParmVarDecl>(SelfAssigned))
14853 return nullptr;
14854 const auto *Method =
14855 dyn_cast_or_null<CXXMethodDecl>(getCurFunctionDecl(true));
14856 if (!Method)
14857 return nullptr;
14858
14859 const CXXRecordDecl *Parent = Method->getParent();
14860 // In theory this is fixable if the lambda explicitly captures this, but
14861 // that's added complexity that's rarely going to be used.
14862 if (Parent->isLambda())
14863 return nullptr;
14864
14865 // FIXME: Use an actual Lookup operation instead of just traversing fields
14866 // in order to get base class fields.
14867 auto Field =
14868 llvm::find_if(Parent->fields(),
14869 [Name(SelfAssigned->getDeclName())](const FieldDecl *F) {
14870 return F->getDeclName() == Name;
14871 });
14872 return (Field != Parent->field_end()) ? *Field : nullptr;
14873}
14874
14875/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14876/// This warning suppressed in the event of macro expansions.
14877static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
14878 SourceLocation OpLoc, bool IsBuiltin) {
14880 return;
14881 if (S.isUnevaluatedContext())
14882 return;
14883 if (OpLoc.isInvalid() || OpLoc.isMacroID())
14884 return;
14885 LHSExpr = LHSExpr->IgnoreParenImpCasts();
14886 RHSExpr = RHSExpr->IgnoreParenImpCasts();
14887 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
14888 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
14889 if (!LHSDeclRef || !RHSDeclRef ||
14890 LHSDeclRef->getLocation().isMacroID() ||
14891 RHSDeclRef->getLocation().isMacroID())
14892 return;
14893 const ValueDecl *LHSDecl =
14894 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
14895 const ValueDecl *RHSDecl =
14896 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
14897 if (LHSDecl != RHSDecl)
14898 return;
14899 if (LHSDecl->getType().isVolatileQualified())
14900 return;
14901 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
14902 if (RefTy->getPointeeType().isVolatileQualified())
14903 return;
14904
14905 auto Diag = S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
14906 : diag::warn_self_assignment_overloaded)
14907 << LHSDeclRef->getType() << LHSExpr->getSourceRange()
14908 << RHSExpr->getSourceRange();
14909 if (const FieldDecl *SelfAssignField =
14911 Diag << 1 << SelfAssignField
14912 << FixItHint::CreateInsertion(LHSDeclRef->getBeginLoc(), "this->");
14913 else
14914 Diag << 0;
14915}
14916
14917/// Check if a bitwise-& is performed on an Objective-C pointer. This
14918/// is usually indicative of introspection within the Objective-C pointer.
14920 SourceLocation OpLoc) {
14921 if (!S.getLangOpts().ObjC)
14922 return;
14923
14924 const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
14925 const Expr *LHS = L.get();
14926 const Expr *RHS = R.get();
14927
14929 ObjCPointerExpr = LHS;
14930 OtherExpr = RHS;
14931 }
14932 else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14933 ObjCPointerExpr = RHS;
14934 OtherExpr = LHS;
14935 }
14936
14937 // This warning is deliberately made very specific to reduce false
14938 // positives with logic that uses '&' for hashing. This logic mainly
14939 // looks for code trying to introspect into tagged pointers, which
14940 // code should generally never do.
14941 if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
14942 unsigned Diag = diag::warn_objc_pointer_masking;
14943 // Determine if we are introspecting the result of performSelectorXXX.
14944 const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
14945 // Special case messages to -performSelector and friends, which
14946 // can return non-pointer values boxed in a pointer value.
14947 // Some clients may wish to silence warnings in this subcase.
14948 if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
14949 Selector S = ME->getSelector();
14950 StringRef SelArg0 = S.getNameForSlot(0);
14951 if (SelArg0.starts_with("performSelector"))
14952 Diag = diag::warn_objc_pointer_masking_performSelector;
14953 }
14954
14955 S.Diag(OpLoc, Diag)
14956 << ObjCPointerExpr->getSourceRange();
14957 }
14958}
14959
14961 if (!E)
14962 return nullptr;
14963 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
14964 return DRE->getDecl();
14965 if (auto *ME = dyn_cast<MemberExpr>(E))
14966 return ME->getMemberDecl();
14967 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
14968 return IRE->getDecl();
14969 return nullptr;
14970}
14971
14972// This helper function promotes a binary operator's operands (which are of a
14973// half vector type) to a vector of floats and then truncates the result to
14974// a vector of either half or short.
14976 BinaryOperatorKind Opc, QualType ResultTy,
14978 bool IsCompAssign, SourceLocation OpLoc,
14979 FPOptionsOverride FPFeatures) {
14980 auto &Context = S.getASTContext();
14981 assert((isVector(ResultTy, Context.HalfTy) ||
14982 isVector(ResultTy, Context.ShortTy)) &&
14983 "Result must be a vector of half or short");
14984 assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
14985 isVector(RHS.get()->getType(), Context.HalfTy) &&
14986 "both operands expected to be a half vector");
14987
14988 RHS = convertVector(RHS.get(), Context.FloatTy, S);
14989 QualType BinOpResTy = RHS.get()->getType();
14990
14991 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
14992 // change BinOpResTy to a vector of ints.
14993 if (isVector(ResultTy, Context.ShortTy))
14994 BinOpResTy = S.GetSignedVectorType(BinOpResTy);
14995
14996 if (IsCompAssign)
14997 return CompoundAssignOperator::Create(Context, LHS.get(), RHS.get(), Opc,
14998 ResultTy, VK, OK, OpLoc, FPFeatures,
14999 BinOpResTy, BinOpResTy);
15000
15001 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15002 auto *BO = BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc,
15003 BinOpResTy, VK, OK, OpLoc, FPFeatures);
15004 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15005}
15006
15007static std::pair<ExprResult, ExprResult>
15009 Expr *RHSExpr) {
15010 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15011 if (!S.Context.isDependenceAllowed()) {
15012 // C cannot handle TypoExpr nodes on either side of a binop because it
15013 // doesn't handle dependent types properly, so make sure any TypoExprs have
15014 // been dealt with before checking the operands.
15015 LHS = S.CorrectDelayedTyposInExpr(LHS);
15017 RHS, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
15018 [Opc, LHS](Expr *E) {
15019 if (Opc != BO_Assign)
15020 return ExprResult(E);
15021 // Avoid correcting the RHS to the same Expr as the LHS.
15022 Decl *D = getDeclFromExpr(E);
15023 return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
15024 });
15025 }
15026 return std::make_pair(LHS, RHS);
15027}
15028
15029/// Returns true if conversion between vectors of halfs and vectors of floats
15030/// is needed.
15031static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
15032 Expr *E0, Expr *E1 = nullptr) {
15033 if (!OpRequiresConversion || Ctx.getLangOpts().NativeHalfType ||
15035 return false;
15036
15037 auto HasVectorOfHalfType = [&Ctx](Expr *E) {
15038 QualType Ty = E->IgnoreImplicit()->getType();
15039
15040 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15041 // to vectors of floats. Although the element type of the vectors is __fp16,
15042 // the vectors shouldn't be treated as storage-only types. See the
15043 // discussion here: https://reviews.llvm.org/rG825235c140e7
15044 if (const VectorType *VT = Ty->getAs<VectorType>()) {
15045 if (VT->getVectorKind() == VectorKind::Neon)
15046 return false;
15047 return VT->getElementType().getCanonicalType() == Ctx.HalfTy;
15048 }
15049 return false;
15050 };
15051
15052 return HasVectorOfHalfType(E0) && (!E1 || HasVectorOfHalfType(E1));
15053}
15054
15055/// CreateBuiltinBinOp - Creates a new built-in binary operation with
15056/// operator @p Opc at location @c TokLoc. This routine only supports
15057/// built-in operations; ActOnBinOp handles overloaded operators.
15060 Expr *LHSExpr, Expr *RHSExpr) {
15061 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
15062 // The syntax only allows initializer lists on the RHS of assignment,
15063 // so we don't need to worry about accepting invalid code for
15064 // non-assignment operators.
15065 // C++11 5.17p9:
15066 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15067 // of x = {} is x = T().
15069 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15070 InitializedEntity Entity =
15072 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15073 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
15074 if (Init.isInvalid())
15075 return Init;
15076 RHSExpr = Init.get();
15077 }
15078
15079 ExprResult LHS = LHSExpr, RHS = RHSExpr;
15080 QualType ResultTy; // Result type of the binary operator.
15081 // The following two variables are used for compound assignment operators
15082 QualType CompLHSTy; // Type of LHS after promotions for computation
15083 QualType CompResultTy; // Type of computation result
15086 bool ConvertHalfVec = false;
15087
15088 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15089 if (!LHS.isUsable() || !RHS.isUsable())
15090 return ExprError();
15091
15092 if (getLangOpts().OpenCL) {
15093 QualType LHSTy = LHSExpr->getType();
15094 QualType RHSTy = RHSExpr->getType();
15095 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15096 // the ATOMIC_VAR_INIT macro.
15097 if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
15098 SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15099 if (BO_Assign == Opc)
15100 Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
15101 else
15102 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15103 return ExprError();
15104 }
15105
15106 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15107 // only with a builtin functions and therefore should be disallowed here.
15108 if (LHSTy->isImageType() || RHSTy->isImageType() ||
15109 LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
15110 LHSTy->isPipeType() || RHSTy->isPipeType() ||
15111 LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
15112 ResultTy = InvalidOperands(OpLoc, LHS, RHS);
15113 return ExprError();
15114 }
15115 }
15116
15117 checkTypeSupport(LHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15118 checkTypeSupport(RHSExpr->getType(), OpLoc, /*ValueDecl*/ nullptr);
15119
15120 switch (Opc) {
15121 case BO_Assign:
15122 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType(), Opc);
15123 if (getLangOpts().CPlusPlus &&
15124 LHS.get()->getObjectKind() != OK_ObjCProperty) {
15125 VK = LHS.get()->getValueKind();
15126 OK = LHS.get()->getObjectKind();
15127 }
15128 if (!ResultTy.isNull()) {
15129 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15130 DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
15131
15132 // Avoid copying a block to the heap if the block is assigned to a local
15133 // auto variable that is declared in the same scope as the block. This
15134 // optimization is unsafe if the local variable is declared in an outer
15135 // scope. For example:
15136 //
15137 // BlockTy b;
15138 // {
15139 // b = ^{...};
15140 // }
15141 // // It is unsafe to invoke the block here if it wasn't copied to the
15142 // // heap.
15143 // b();
15144
15145 if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
15146 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
15147 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
15148 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15149 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15150
15152 checkNonTrivialCUnion(LHS.get()->getType(), LHS.get()->getExprLoc(),
15154 }
15155 RecordModifiableNonNullParam(*this, LHS.get());
15156 break;
15157 case BO_PtrMemD:
15158 case BO_PtrMemI:
15159 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15160 Opc == BO_PtrMemI);
15161 break;
15162 case BO_Mul:
15163 case BO_Div:
15164 ConvertHalfVec = true;
15165 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
15166 Opc == BO_Div);
15167 break;
15168 case BO_Rem:
15169 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
15170 break;
15171 case BO_Add:
15172 ConvertHalfVec = true;
15173 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
15174 break;
15175 case BO_Sub:
15176 ConvertHalfVec = true;
15177 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
15178 break;
15179 case BO_Shl:
15180 case BO_Shr:
15181 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
15182 break;
15183 case BO_LE:
15184 case BO_LT:
15185 case BO_GE:
15186 case BO_GT:
15187 ConvertHalfVec = true;
15188 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15189 break;
15190 case BO_EQ:
15191 case BO_NE:
15192 ConvertHalfVec = true;
15193 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15194 break;
15195 case BO_Cmp:
15196 ConvertHalfVec = true;
15197 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
15198 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15199 break;
15200 case BO_And:
15201 checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
15202 [[fallthrough]];
15203 case BO_Xor:
15204 case BO_Or:
15205 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15206 break;
15207 case BO_LAnd:
15208 case BO_LOr:
15209 ConvertHalfVec = true;
15210 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
15211 break;
15212 case BO_MulAssign:
15213 case BO_DivAssign:
15214 ConvertHalfVec = true;
15215 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
15216 Opc == BO_DivAssign);
15217 CompLHSTy = CompResultTy;
15218 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15219 ResultTy =
15220 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15221 break;
15222 case BO_RemAssign:
15223 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
15224 CompLHSTy = CompResultTy;
15225 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15226 ResultTy =
15227 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15228 break;
15229 case BO_AddAssign:
15230 ConvertHalfVec = true;
15231 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
15232 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15233 ResultTy =
15234 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15235 break;
15236 case BO_SubAssign:
15237 ConvertHalfVec = true;
15238 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
15239 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15240 ResultTy =
15241 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15242 break;
15243 case BO_ShlAssign:
15244 case BO_ShrAssign:
15245 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
15246 CompLHSTy = CompResultTy;
15247 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15248 ResultTy =
15249 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15250 break;
15251 case BO_AndAssign:
15252 case BO_OrAssign: // fallthrough
15253 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
15254 [[fallthrough]];
15255 case BO_XorAssign:
15256 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
15257 CompLHSTy = CompResultTy;
15258 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15259 ResultTy =
15260 CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy, Opc);
15261 break;
15262 case BO_Comma:
15263 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
15264 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
15265 VK = RHS.get()->getValueKind();
15266 OK = RHS.get()->getObjectKind();
15267 }
15268 break;
15269 }
15270 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
15271 return ExprError();
15272
15273 // Some of the binary operations require promoting operands of half vector to
15274 // float vectors and truncating the result back to half vector. For now, we do
15275 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15276 // arm64).
15277 assert(
15278 (Opc == BO_Comma || isVector(RHS.get()->getType(), Context.HalfTy) ==
15279 isVector(LHS.get()->getType(), Context.HalfTy)) &&
15280 "both sides are half vectors or neither sides are");
15281 ConvertHalfVec =
15282 needsConversionOfHalfVec(ConvertHalfVec, Context, LHS.get(), RHS.get());
15283
15284 // Check for array bounds violations for both sides of the BinaryOperator
15285 CheckArrayAccess(LHS.get());
15286 CheckArrayAccess(RHS.get());
15287
15288 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
15289 NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
15290 &Context.Idents.get("object_setClass"),
15292 if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
15293 SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
15294 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15296 "object_setClass(")
15297 << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
15298 ",")
15299 << FixItHint::CreateInsertion(RHSLocEnd, ")");
15300 }
15301 else
15302 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
15303 }
15304 else if (const ObjCIvarRefExpr *OIRE =
15305 dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
15306 DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
15307
15308 // Opc is not a compound assignment if CompResultTy is null.
15309 if (CompResultTy.isNull()) {
15310 if (ConvertHalfVec)
15311 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
15312 OpLoc, CurFPFeatureOverrides());
15313 return BinaryOperator::Create(Context, LHS.get(), RHS.get(), Opc, ResultTy,
15314 VK, OK, OpLoc, CurFPFeatureOverrides());
15315 }
15316
15317 // Handle compound assignments.
15318 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15320 VK = VK_LValue;
15321 OK = LHS.get()->getObjectKind();
15322 }
15323
15324 // The LHS is not converted to the result type for fixed-point compound
15325 // assignment as the common type is computed on demand. Reset the CompLHSTy
15326 // to the LHS type we would have gotten after unary conversions.
15327 if (CompResultTy->isFixedPointType())
15328 CompLHSTy = UsualUnaryConversions(LHS.get()).get()->getType();
15329
15330 if (ConvertHalfVec)
15331 return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
15332 OpLoc, CurFPFeatureOverrides());
15333
15335 Context, LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, OpLoc,
15336 CurFPFeatureOverrides(), CompLHSTy, CompResultTy);
15337}
15338
15339/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15340/// operators are mixed in a way that suggests that the programmer forgot that
15341/// comparison operators have higher precedence. The most typical example of
15342/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15344 SourceLocation OpLoc, Expr *LHSExpr,
15345 Expr *RHSExpr) {
15346 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
15347 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
15348
15349 // Check that one of the sides is a comparison operator and the other isn't.
15350 bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
15351 bool isRightComp = RHSBO && RHSBO->isComparisonOp();
15352 if (isLeftComp == isRightComp)
15353 return;
15354
15355 // Bitwise operations are sometimes used as eager logical ops.
15356 // Don't diagnose this.
15357 bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
15358 bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
15359 if (isLeftBitwise || isRightBitwise)
15360 return;
15361
15362 SourceRange DiagRange = isLeftComp
15363 ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
15364 : SourceRange(OpLoc, RHSExpr->getEndLoc());
15365 StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
15366 SourceRange ParensRange =
15367 isLeftComp
15368 ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
15369 : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
15370
15371 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
15372 << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
15373 SuggestParentheses(Self, OpLoc,
15374 Self.PDiag(diag::note_precedence_silence) << OpStr,
15375 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
15376 SuggestParentheses(Self, OpLoc,
15377 Self.PDiag(diag::note_precedence_bitwise_first)
15379 ParensRange);
15380}
15381
15382/// It accepts a '&&' expr that is inside a '||' one.
15383/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15384/// in parentheses.
15385static void
15387 BinaryOperator *Bop) {
15388 assert(Bop->getOpcode() == BO_LAnd);
15389 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
15390 << Bop->getSourceRange() << OpLoc;
15392 Self.PDiag(diag::note_precedence_silence)
15393 << Bop->getOpcodeStr(),
15394 Bop->getSourceRange());
15395}
15396
15397/// Look for '&&' in the left hand of a '||' expr.
15399 Expr *LHSExpr, Expr *RHSExpr) {
15400 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
15401 if (Bop->getOpcode() == BO_LAnd) {
15402 // If it's "string_literal && a || b" don't warn since the precedence
15403 // doesn't matter.
15404 if (!isa<StringLiteral>(Bop->getLHS()->IgnoreParenImpCasts()))
15405 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15406 } else if (Bop->getOpcode() == BO_LOr) {
15407 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
15408 // If it's "a || b && string_literal || c" we didn't warn earlier for
15409 // "a || b && string_literal", but warn now.
15410 if (RBop->getOpcode() == BO_LAnd &&
15411 isa<StringLiteral>(RBop->getRHS()->IgnoreParenImpCasts()))
15412 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
15413 }
15414 }
15415 }
15416}
15417
15418/// Look for '&&' in the right hand of a '||' expr.
15420 Expr *LHSExpr, Expr *RHSExpr) {
15421 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
15422 if (Bop->getOpcode() == BO_LAnd) {
15423 // If it's "a || b && string_literal" don't warn since the precedence
15424 // doesn't matter.
15425 if (!isa<StringLiteral>(Bop->getRHS()->IgnoreParenImpCasts()))
15426 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
15427 }
15428 }
15429}
15430
15431/// Look for bitwise op in the left or right hand of a bitwise op with
15432/// lower precedence and emit a diagnostic together with a fixit hint that wraps
15433/// the '&' expression in parentheses.
15435 SourceLocation OpLoc, Expr *SubExpr) {
15436 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15437 if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
15438 S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
15439 << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
15440 << Bop->getSourceRange() << OpLoc;
15441 SuggestParentheses(S, Bop->getOperatorLoc(),
15442 S.PDiag(diag::note_precedence_silence)
15443 << Bop->getOpcodeStr(),
15444 Bop->getSourceRange());
15445 }
15446 }
15447}
15448
15450 Expr *SubExpr, StringRef Shift) {
15451 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
15452 if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
15453 StringRef Op = Bop->getOpcodeStr();
15454 S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
15455 << Bop->getSourceRange() << OpLoc << Shift << Op;
15456 SuggestParentheses(S, Bop->getOperatorLoc(),
15457 S.PDiag(diag::note_precedence_silence) << Op,
15458 Bop->getSourceRange());
15459 }
15460 }
15461}
15462
15464 Expr *LHSExpr, Expr *RHSExpr) {
15465 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
15466 if (!OCE)
15467 return;
15468
15469 FunctionDecl *FD = OCE->getDirectCallee();
15470 if (!FD || !FD->isOverloadedOperator())
15471 return;
15472
15474 if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
15475 return;
15476
15477 S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
15478 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
15479 << (Kind == OO_LessLess);
15481 S.PDiag(diag::note_precedence_silence)
15482 << (Kind == OO_LessLess ? "<<" : ">>"),
15483 OCE->getSourceRange());
15485 S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
15486 SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
15487}
15488
15489/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15490/// precedence.
15492 SourceLocation OpLoc, Expr *LHSExpr,
15493 Expr *RHSExpr){
15494 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15496 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
15497
15498 // Diagnose "arg1 & arg2 | arg3"
15499 if ((Opc == BO_Or || Opc == BO_Xor) &&
15500 !OpLoc.isMacroID()/* Don't warn in macros. */) {
15501 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
15502 DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
15503 }
15504
15505 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15506 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15507 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
15508 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
15509 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
15510 }
15511
15512 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
15513 || Opc == BO_Shr) {
15514 StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
15515 DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
15516 DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
15517 }
15518
15519 // Warn on overloaded shift operators and comparisons, such as:
15520 // cout << 5 == 4;
15522 DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
15523}
15524
15525// Binary Operators. 'Tok' is the token for the operator.
15527 tok::TokenKind Kind,
15528 Expr *LHSExpr, Expr *RHSExpr) {
15529 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
15530 assert(LHSExpr && "ActOnBinOp(): missing left expression");
15531 assert(RHSExpr && "ActOnBinOp(): missing right expression");
15532
15533 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15534 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
15535
15536 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
15537}
15538
15540 UnresolvedSetImpl &Functions) {
15542 if (OverOp != OO_None && OverOp != OO_Equal)
15543 LookupOverloadedOperatorName(OverOp, S, Functions);
15544
15545 // In C++20 onwards, we may have a second operator to look up.
15546 if (getLangOpts().CPlusPlus20) {
15548 LookupOverloadedOperatorName(ExtraOp, S, Functions);
15549 }
15550}
15551
15552/// Build an overloaded binary operator expression in the given scope.
15555 Expr *LHS, Expr *RHS) {
15556 switch (Opc) {
15557 case BO_Assign:
15558 // In the non-overloaded case, we warn about self-assignment (x = x) for
15559 // both simple assignment and certain compound assignments where algebra
15560 // tells us the operation yields a constant result. When the operator is
15561 // overloaded, we can't do the latter because we don't want to assume that
15562 // those algebraic identities still apply; for example, a path-building
15563 // library might use operator/= to append paths. But it's still reasonable
15564 // to assume that simple assignment is just moving/copying values around
15565 // and so self-assignment is likely a bug.
15566 DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
15567 [[fallthrough]];
15568 case BO_DivAssign:
15569 case BO_RemAssign:
15570 case BO_SubAssign:
15571 case BO_AndAssign:
15572 case BO_OrAssign:
15573 case BO_XorAssign:
15574 CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
15575 break;
15576 default:
15577 break;
15578 }
15579
15580 // Find all of the overloaded operators visible from this point.
15581 UnresolvedSet<16> Functions;
15582 S.LookupBinOp(Sc, OpLoc, Opc, Functions);
15583
15584 // Build the (potentially-overloaded, potentially-dependent)
15585 // binary operation.
15586 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
15587}
15588
15591 Expr *LHSExpr, Expr *RHSExpr) {
15592 ExprResult LHS, RHS;
15593 std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
15594 if (!LHS.isUsable() || !RHS.isUsable())
15595 return ExprError();
15596 LHSExpr = LHS.get();
15597 RHSExpr = RHS.get();
15598
15599 // We want to end up calling one of checkPseudoObjectAssignment
15600 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15601 // both expressions are overloadable or either is type-dependent),
15602 // or CreateBuiltinBinOp (in any other case). We also want to get
15603 // any placeholder types out of the way.
15604
15605 // Handle pseudo-objects in the LHS.
15606 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
15607 // Assignments with a pseudo-object l-value need special analysis.
15608 if (pty->getKind() == BuiltinType::PseudoObject &&
15610 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
15611
15612 // Don't resolve overloads if the other type is overloadable.
15613 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
15614 // We can't actually test that if we still have a placeholder,
15615 // though. Fortunately, none of the exceptions we see in that
15616 // code below are valid when the LHS is an overload set. Note
15617 // that an overload set can be dependently-typed, but it never
15618 // instantiates to having an overloadable type.
15619 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15620 if (resolvedRHS.isInvalid()) return ExprError();
15621 RHSExpr = resolvedRHS.get();
15622
15623 if (RHSExpr->isTypeDependent() ||
15624 RHSExpr->getType()->isOverloadableType())
15625 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15626 }
15627
15628 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15629 // template, diagnose the missing 'template' keyword instead of diagnosing
15630 // an invalid use of a bound member function.
15631 //
15632 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15633 // to C++1z [over.over]/1.4, but we already checked for that case above.
15634 if (Opc == BO_LT && inTemplateInstantiation() &&
15635 (pty->getKind() == BuiltinType::BoundMember ||
15636 pty->getKind() == BuiltinType::Overload)) {
15637 auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
15638 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15639 llvm::any_of(OE->decls(), [](NamedDecl *ND) {
15640 return isa<FunctionTemplateDecl>(ND);
15641 })) {
15642 Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
15643 : OE->getNameLoc(),
15644 diag::err_template_kw_missing)
15645 << OE->getName().getAsString() << "";
15646 return ExprError();
15647 }
15648 }
15649
15650 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
15651 if (LHS.isInvalid()) return ExprError();
15652 LHSExpr = LHS.get();
15653 }
15654
15655 // Handle pseudo-objects in the RHS.
15656 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
15657 // An overload in the RHS can potentially be resolved by the type
15658 // being assigned to.
15659 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
15660 if (getLangOpts().CPlusPlus &&
15661 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
15662 LHSExpr->getType()->isOverloadableType()))
15663 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15664
15665 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15666 }
15667
15668 // Don't resolve overloads if the other type is overloadable.
15669 if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
15670 LHSExpr->getType()->isOverloadableType())
15671 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15672
15673 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
15674 if (!resolvedRHS.isUsable()) return ExprError();
15675 RHSExpr = resolvedRHS.get();
15676 }
15677
15678 if (getLangOpts().CPlusPlus) {
15679 // If either expression is type-dependent, always build an
15680 // overloaded op.
15681 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
15682 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15683
15684 // Otherwise, build an overloaded op if either expression has an
15685 // overloadable type.
15686 if (LHSExpr->getType()->isOverloadableType() ||
15687 RHSExpr->getType()->isOverloadableType())
15688 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
15689 }
15690
15691 if (getLangOpts().RecoveryAST &&
15692 (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())) {
15693 assert(!getLangOpts().CPlusPlus);
15694 assert((LHSExpr->containsErrors() || RHSExpr->containsErrors()) &&
15695 "Should only occur in error-recovery path.");
15697 // C [6.15.16] p3:
15698 // An assignment expression has the value of the left operand after the
15699 // assignment, but is not an lvalue.
15701 Context, LHSExpr, RHSExpr, Opc,
15703 OpLoc, CurFPFeatureOverrides());
15704 QualType ResultType;
15705 switch (Opc) {
15706 case BO_Assign:
15707 ResultType = LHSExpr->getType().getUnqualifiedType();
15708 break;
15709 case BO_LT:
15710 case BO_GT:
15711 case BO_LE:
15712 case BO_GE:
15713 case BO_EQ:
15714 case BO_NE:
15715 case BO_LAnd:
15716 case BO_LOr:
15717 // These operators have a fixed result type regardless of operands.
15718 ResultType = Context.IntTy;
15719 break;
15720 case BO_Comma:
15721 ResultType = RHSExpr->getType();
15722 break;
15723 default:
15724 ResultType = Context.DependentTy;
15725 break;
15726 }
15727 return BinaryOperator::Create(Context, LHSExpr, RHSExpr, Opc, ResultType,
15728 VK_PRValue, OK_Ordinary, OpLoc,
15730 }
15731
15732 // Build a built-in binary operation.
15733 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15734}
15735
15737 if (T.isNull() || T->isDependentType())
15738 return false;
15739
15740 if (!Ctx.isPromotableIntegerType(T))
15741 return true;
15742
15743 return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
15744}
15745
15747 UnaryOperatorKind Opc, Expr *InputExpr,
15748 bool IsAfterAmp) {
15749 ExprResult Input = InputExpr;
15752 QualType resultType;
15753 bool CanOverflow = false;
15754
15755 bool ConvertHalfVec = false;
15756 if (getLangOpts().OpenCL) {
15757 QualType Ty = InputExpr->getType();
15758 // The only legal unary operation for atomics is '&'.
15759 if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
15760 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15761 // only with a builtin functions and therefore should be disallowed here.
15762 (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
15763 || Ty->isBlockPointerType())) {
15764 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15765 << InputExpr->getType()
15766 << Input.get()->getSourceRange());
15767 }
15768 }
15769
15770 if (getLangOpts().HLSL && OpLoc.isValid()) {
15771 if (Opc == UO_AddrOf)
15772 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 0);
15773 if (Opc == UO_Deref)
15774 return ExprError(Diag(OpLoc, diag::err_hlsl_operator_unsupported) << 1);
15775 }
15776
15777 switch (Opc) {
15778 case UO_PreInc:
15779 case UO_PreDec:
15780 case UO_PostInc:
15781 case UO_PostDec:
15782 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
15783 OpLoc,
15784 Opc == UO_PreInc ||
15785 Opc == UO_PostInc,
15786 Opc == UO_PreInc ||
15787 Opc == UO_PreDec);
15788 CanOverflow = isOverflowingIntegerType(Context, resultType);
15789 break;
15790 case UO_AddrOf:
15791 resultType = CheckAddressOfOperand(Input, OpLoc);
15792 CheckAddressOfNoDeref(InputExpr);
15793 RecordModifiableNonNullParam(*this, InputExpr);
15794 break;
15795 case UO_Deref: {
15797 if (Input.isInvalid()) return ExprError();
15798 resultType =
15799 CheckIndirectionOperand(*this, Input.get(), VK, OpLoc, IsAfterAmp);
15800 break;
15801 }
15802 case UO_Plus:
15803 case UO_Minus:
15804 CanOverflow = Opc == UO_Minus &&
15806 Input = UsualUnaryConversions(Input.get());
15807 if (Input.isInvalid()) return ExprError();
15808 // Unary plus and minus require promoting an operand of half vector to a
15809 // float vector and truncating the result back to a half vector. For now, we
15810 // do this only when HalfArgsAndReturns is set (that is, when the target is
15811 // arm or arm64).
15812 ConvertHalfVec = needsConversionOfHalfVec(true, Context, Input.get());
15813
15814 // If the operand is a half vector, promote it to a float vector.
15815 if (ConvertHalfVec)
15816 Input = convertVector(Input.get(), Context.FloatTy, *this);
15817 resultType = Input.get()->getType();
15818 if (resultType->isDependentType())
15819 break;
15820 if (resultType->isArithmeticType()) // C99 6.5.3.3p1
15821 break;
15822 else if (resultType->isVectorType() &&
15823 // The z vector extensions don't allow + or - with bool vectors.
15824 (!Context.getLangOpts().ZVector ||
15825 resultType->castAs<VectorType>()->getVectorKind() !=
15827 break;
15828 else if (resultType->isSveVLSBuiltinType()) // SVE vectors allow + and -
15829 break;
15830 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
15831 Opc == UO_Plus &&
15832 resultType->isPointerType())
15833 break;
15834
15835 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15836 << resultType << Input.get()->getSourceRange());
15837
15838 case UO_Not: // bitwise complement
15839 Input = UsualUnaryConversions(Input.get());
15840 if (Input.isInvalid())
15841 return ExprError();
15842 resultType = Input.get()->getType();
15843 if (resultType->isDependentType())
15844 break;
15845 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15846 if (resultType->isComplexType() || resultType->isComplexIntegerType())
15847 // C99 does not support '~' for complex conjugation.
15848 Diag(OpLoc, diag::ext_integer_complement_complex)
15849 << resultType << Input.get()->getSourceRange();
15850 else if (resultType->hasIntegerRepresentation())
15851 break;
15852 else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
15853 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15854 // on vector float types.
15855 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15856 if (!T->isIntegerType())
15857 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15858 << resultType << Input.get()->getSourceRange());
15859 } else {
15860 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15861 << resultType << Input.get()->getSourceRange());
15862 }
15863 break;
15864
15865 case UO_LNot: // logical negation
15866 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15868 if (Input.isInvalid()) return ExprError();
15869 resultType = Input.get()->getType();
15870
15871 // Though we still have to promote half FP to float...
15872 if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
15873 Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
15874 resultType = Context.FloatTy;
15875 }
15876
15877 // WebAsembly tables can't be used in unary expressions.
15878 if (resultType->isPointerType() &&
15880 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15881 << resultType << Input.get()->getSourceRange());
15882 }
15883
15884 if (resultType->isDependentType())
15885 break;
15886 if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
15887 // C99 6.5.3.3p1: ok, fallthrough;
15888 if (Context.getLangOpts().CPlusPlus) {
15889 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15890 // operand contextually converted to bool.
15891 Input = ImpCastExprToType(Input.get(), Context.BoolTy,
15892 ScalarTypeToBooleanCastKind(resultType));
15893 } else if (Context.getLangOpts().OpenCL &&
15894 Context.getLangOpts().OpenCLVersion < 120) {
15895 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15896 // operate on scalar float types.
15897 if (!resultType->isIntegerType() && !resultType->isPointerType())
15898 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15899 << resultType << Input.get()->getSourceRange());
15900 }
15901 } else if (resultType->isExtVectorType()) {
15902 if (Context.getLangOpts().OpenCL &&
15904 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15905 // operate on vector float types.
15906 QualType T = resultType->castAs<ExtVectorType>()->getElementType();
15907 if (!T->isIntegerType())
15908 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15909 << resultType << Input.get()->getSourceRange());
15910 }
15911 // Vector logical not returns the signed variant of the operand type.
15912 resultType = GetSignedVectorType(resultType);
15913 break;
15914 } else if (Context.getLangOpts().CPlusPlus && resultType->isVectorType()) {
15915 const VectorType *VTy = resultType->castAs<VectorType>();
15916 if (VTy->getVectorKind() != VectorKind::Generic)
15917 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15918 << resultType << Input.get()->getSourceRange());
15919
15920 // Vector logical not returns the signed variant of the operand type.
15921 resultType = GetSignedVectorType(resultType);
15922 break;
15923 } else {
15924 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
15925 << resultType << Input.get()->getSourceRange());
15926 }
15927
15928 // LNot always has type int. C99 6.5.3.3p5.
15929 // In C++, it's bool. C++ 5.3.1p8
15930 resultType = Context.getLogicalOperationType();
15931 break;
15932 case UO_Real:
15933 case UO_Imag:
15934 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
15935 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
15936 // complex l-values to ordinary l-values and all other values to r-values.
15937 if (Input.isInvalid()) return ExprError();
15938 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
15939 if (Input.get()->isGLValue() &&
15940 Input.get()->getObjectKind() == OK_Ordinary)
15941 VK = Input.get()->getValueKind();
15942 } else if (!getLangOpts().CPlusPlus) {
15943 // In C, a volatile scalar is read by __imag. In C++, it is not.
15944 Input = DefaultLvalueConversion(Input.get());
15945 }
15946 break;
15947 case UO_Extension:
15948 resultType = Input.get()->getType();
15949 VK = Input.get()->getValueKind();
15950 OK = Input.get()->getObjectKind();
15951 break;
15952 case UO_Coawait:
15953 // It's unnecessary to represent the pass-through operator co_await in the
15954 // AST; just return the input expression instead.
15955 assert(!Input.get()->getType()->isDependentType() &&
15956 "the co_await expression must be non-dependant before "
15957 "building operator co_await");
15958 return Input;
15959 }
15960 if (resultType.isNull() || Input.isInvalid())
15961 return ExprError();
15962
15963 // Check for array bounds violations in the operand of the UnaryOperator,
15964 // except for the '*' and '&' operators that have to be handled specially
15965 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15966 // that are explicitly defined as valid by the standard).
15967 if (Opc != UO_AddrOf && Opc != UO_Deref)
15968 CheckArrayAccess(Input.get());
15969
15970 auto *UO =
15971 UnaryOperator::Create(Context, Input.get(), Opc, resultType, VK, OK,
15972 OpLoc, CanOverflow, CurFPFeatureOverrides());
15973
15974 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15975 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15977 ExprEvalContexts.back().PossibleDerefs.insert(UO);
15978
15979 // Convert the result back to a half vector.
15980 if (ConvertHalfVec)
15981 return convertVector(UO, Context.HalfTy, *this);
15982 return UO;
15983}
15984
15985/// Determine whether the given expression is a qualified member
15986/// access expression, of a form that could be turned into a pointer to member
15987/// with the address-of operator.
15989 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15990 if (!DRE->getQualifier())
15991 return false;
15992
15993 ValueDecl *VD = DRE->getDecl();
15994 if (!VD->isCXXClassMember())
15995 return false;
15996
15997 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
15998 return true;
15999 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
16000 return Method->isImplicitObjectMemberFunction();
16001
16002 return false;
16003 }
16004
16005 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16006 if (!ULE->getQualifier())
16007 return false;
16008
16009 for (NamedDecl *D : ULE->decls()) {
16010 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
16011 if (Method->isImplicitObjectMemberFunction())
16012 return true;
16013 } else {
16014 // Overload set does not contain methods.
16015 break;
16016 }
16017 }
16018
16019 return false;
16020 }
16021
16022 return false;
16023}
16024
16026 UnaryOperatorKind Opc, Expr *Input,
16027 bool IsAfterAmp) {
16028 // First things first: handle placeholders so that the
16029 // overloaded-operator check considers the right type.
16030 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
16031 // Increment and decrement of pseudo-object references.
16032 if (pty->getKind() == BuiltinType::PseudoObject &&
16034 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
16035
16036 // extension is always a builtin operator.
16037 if (Opc == UO_Extension)
16038 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16039
16040 // & gets special logic for several kinds of placeholder.
16041 // The builtin code knows what to do.
16042 if (Opc == UO_AddrOf &&
16043 (pty->getKind() == BuiltinType::Overload ||
16044 pty->getKind() == BuiltinType::UnknownAny ||
16045 pty->getKind() == BuiltinType::BoundMember))
16046 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
16047
16048 // Anything else needs to be handled now.
16050 if (Result.isInvalid()) return ExprError();
16051 Input = Result.get();
16052 }
16053
16054 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16056 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
16057 // Find all of the overloaded operators visible from this point.
16058 UnresolvedSet<16> Functions;
16060 if (S && OverOp != OO_None)
16061 LookupOverloadedOperatorName(OverOp, S, Functions);
16062
16063 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
16064 }
16065
16066 return CreateBuiltinUnaryOp(OpLoc, Opc, Input, IsAfterAmp);
16067}
16068
16069// Unary Operators. 'Tok' is the token for the operator.
16071 Expr *Input, bool IsAfterAmp) {
16072 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input,
16073 IsAfterAmp);
16074}
16075
16076/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
16078 LabelDecl *TheDecl) {
16079 TheDecl->markUsed(Context);
16080 // Create the AST node. The address of a label always has type 'void*'.
16081 auto *Res = new (Context) AddrLabelExpr(
16082 OpLoc, LabLoc, TheDecl, Context.getPointerType(Context.VoidTy));
16083
16084 if (getCurFunction())
16085 getCurFunction()->AddrLabels.push_back(Res);
16086
16087 return Res;
16088}
16089
16092 // Make sure we diagnose jumping into a statement expression.
16094}
16095
16097 // Note that function is also called by TreeTransform when leaving a
16098 // StmtExpr scope without rebuilding anything.
16099
16102}
16103
16105 SourceLocation RPLoc) {
16106 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, getTemplateDepth(S));
16107}
16108
16110 SourceLocation RPLoc, unsigned TemplateDepth) {
16111 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16112 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
16113
16116 assert(!Cleanup.exprNeedsCleanups() &&
16117 "cleanups within StmtExpr not correctly bound!");
16119
16120 // FIXME: there are a variety of strange constraints to enforce here, for
16121 // example, it is not possible to goto into a stmt expression apparently.
16122 // More semantic analysis is needed.
16123
16124 // If there are sub-stmts in the compound stmt, take the type of the last one
16125 // as the type of the stmtexpr.
16126 QualType Ty = Context.VoidTy;
16127 bool StmtExprMayBindToTemp = false;
16128 if (!Compound->body_empty()) {
16129 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
16130 if (const auto *LastStmt =
16131 dyn_cast<ValueStmt>(Compound->getStmtExprResult())) {
16132 if (const Expr *Value = LastStmt->getExprStmt()) {
16133 StmtExprMayBindToTemp = true;
16134 Ty = Value->getType();
16135 }
16136 }
16137 }
16138
16139 // FIXME: Check that expression type is complete/non-abstract; statement
16140 // expressions are not lvalues.
16141 Expr *ResStmtExpr =
16142 new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc, TemplateDepth);
16143 if (StmtExprMayBindToTemp)
16144 return MaybeBindToTemporary(ResStmtExpr);
16145 return ResStmtExpr;
16146}
16147
16149 if (ER.isInvalid())
16150 return ExprError();
16151
16152 // Do function/array conversion on the last expression, but not
16153 // lvalue-to-rvalue. However, initialize an unqualified type.
16155 if (ER.isInvalid())
16156 return ExprError();
16157 Expr *E = ER.get();
16158
16159 if (E->isTypeDependent())
16160 return E;
16161
16162 // In ARC, if the final expression ends in a consume, splice
16163 // the consume out and bind it later. In the alternate case
16164 // (when dealing with a retainable type), the result
16165 // initialization will create a produce. In both cases the
16166 // result will be +1, and we'll need to balance that out with
16167 // a bind.
16168 auto *Cast = dyn_cast<ImplicitCastExpr>(E);
16169 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16170 return Cast->getSubExpr();
16171
16172 // FIXME: Provide a better location for the initialization.
16176 SourceLocation(), E);
16177}
16178
16180 TypeSourceInfo *TInfo,
16181 ArrayRef<OffsetOfComponent> Components,
16182 SourceLocation RParenLoc) {
16183 QualType ArgTy = TInfo->getType();
16184 bool Dependent = ArgTy->isDependentType();
16185 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
16186
16187 // We must have at least one component that refers to the type, and the first
16188 // one is known to be a field designator. Verify that the ArgTy represents
16189 // a struct/union/class.
16190 if (!Dependent && !ArgTy->isRecordType())
16191 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
16192 << ArgTy << TypeRange);
16193
16194 // Type must be complete per C99 7.17p3 because a declaring a variable
16195 // with an incomplete type would be ill-formed.
16196 if (!Dependent
16197 && RequireCompleteType(BuiltinLoc, ArgTy,
16198 diag::err_offsetof_incomplete_type, TypeRange))
16199 return ExprError();
16200
16201 bool DidWarnAboutNonPOD = false;
16202 QualType CurrentType = ArgTy;
16205 for (const OffsetOfComponent &OC : Components) {
16206 if (OC.isBrackets) {
16207 // Offset of an array sub-field. TODO: Should we allow vector elements?
16208 if (!CurrentType->isDependentType()) {
16209 const ArrayType *AT = Context.getAsArrayType(CurrentType);
16210 if(!AT)
16211 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
16212 << CurrentType);
16213 CurrentType = AT->getElementType();
16214 } else
16215 CurrentType = Context.DependentTy;
16216
16217 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
16218 if (IdxRval.isInvalid())
16219 return ExprError();
16220 Expr *Idx = IdxRval.get();
16221
16222 // The expression must be an integral expression.
16223 // FIXME: An integral constant expression?
16224 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
16225 !Idx->getType()->isIntegerType())
16226 return ExprError(
16227 Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
16228 << Idx->getSourceRange());
16229
16230 // Record this array index.
16231 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16232 Exprs.push_back(Idx);
16233 continue;
16234 }
16235
16236 // Offset of a field.
16237 if (CurrentType->isDependentType()) {
16238 // We have the offset of a field, but we can't look into the dependent
16239 // type. Just record the identifier of the field.
16240 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
16241 CurrentType = Context.DependentTy;
16242 continue;
16243 }
16244
16245 // We need to have a complete type to look into.
16246 if (RequireCompleteType(OC.LocStart, CurrentType,
16247 diag::err_offsetof_incomplete_type))
16248 return ExprError();
16249
16250 // Look for the designated field.
16251 const RecordType *RC = CurrentType->getAs<RecordType>();
16252 if (!RC)
16253 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
16254 << CurrentType);
16255 RecordDecl *RD = RC->getDecl();
16256
16257 // C++ [lib.support.types]p5:
16258 // The macro offsetof accepts a restricted set of type arguments in this
16259 // International Standard. type shall be a POD structure or a POD union
16260 // (clause 9).
16261 // C++11 [support.types]p4:
16262 // If type is not a standard-layout class (Clause 9), the results are
16263 // undefined.
16264 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
16265 bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
16266 unsigned DiagID =
16267 LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
16268 : diag::ext_offsetof_non_pod_type;
16269
16270 if (!IsSafe && !DidWarnAboutNonPOD && !isUnevaluatedContext()) {
16271 Diag(BuiltinLoc, DiagID)
16272 << SourceRange(Components[0].LocStart, OC.LocEnd) << CurrentType;
16273 DidWarnAboutNonPOD = true;
16274 }
16275 }
16276
16277 // Look for the field.
16278 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
16279 LookupQualifiedName(R, RD);
16280 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
16281 IndirectFieldDecl *IndirectMemberDecl = nullptr;
16282 if (!MemberDecl) {
16283 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
16284 MemberDecl = IndirectMemberDecl->getAnonField();
16285 }
16286
16287 if (!MemberDecl) {
16288 // Lookup could be ambiguous when looking up a placeholder variable
16289 // __builtin_offsetof(S, _).
16290 // In that case we would already have emitted a diagnostic
16291 if (!R.isAmbiguous())
16292 Diag(BuiltinLoc, diag::err_no_member)
16293 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd);
16294 return ExprError();
16295 }
16296
16297 // C99 7.17p3:
16298 // (If the specified member is a bit-field, the behavior is undefined.)
16299 //
16300 // We diagnose this as an error.
16301 if (MemberDecl->isBitField()) {
16302 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
16303 << MemberDecl->getDeclName()
16304 << SourceRange(BuiltinLoc, RParenLoc);
16305 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
16306 return ExprError();
16307 }
16308
16309 RecordDecl *Parent = MemberDecl->getParent();
16310 if (IndirectMemberDecl)
16311 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
16312
16313 // If the member was found in a base class, introduce OffsetOfNodes for
16314 // the base class indirections.
16315 CXXBasePaths Paths;
16316 if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
16317 Paths)) {
16318 if (Paths.getDetectedVirtual()) {
16319 Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
16320 << MemberDecl->getDeclName()
16321 << SourceRange(BuiltinLoc, RParenLoc);
16322 return ExprError();
16323 }
16324
16325 CXXBasePath &Path = Paths.front();
16326 for (const CXXBasePathElement &B : Path)
16327 Comps.push_back(OffsetOfNode(B.Base));
16328 }
16329
16330 if (IndirectMemberDecl) {
16331 for (auto *FI : IndirectMemberDecl->chain()) {
16332 assert(isa<FieldDecl>(FI));
16333 Comps.push_back(OffsetOfNode(OC.LocStart,
16334 cast<FieldDecl>(FI), OC.LocEnd));
16335 }
16336 } else
16337 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16338
16339 CurrentType = MemberDecl->getType().getNonReferenceType();
16340 }
16341
16342 return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
16343 Comps, Exprs, RParenLoc);
16344}
16345
16347 SourceLocation BuiltinLoc,
16349 ParsedType ParsedArgTy,
16350 ArrayRef<OffsetOfComponent> Components,
16351 SourceLocation RParenLoc) {
16352
16353 TypeSourceInfo *ArgTInfo;
16354 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
16355 if (ArgTy.isNull())
16356 return ExprError();
16357
16358 if (!ArgTInfo)
16359 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
16360
16361 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
16362}
16363
16364
16366 Expr *CondExpr,
16367 Expr *LHSExpr, Expr *RHSExpr,
16368 SourceLocation RPLoc) {
16369 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16370
16373 QualType resType;
16374 bool CondIsTrue = false;
16375 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
16376 resType = Context.DependentTy;
16377 } else {
16378 // The conditional expression is required to be a constant expression.
16379 llvm::APSInt condEval(32);
16381 CondExpr, &condEval, diag::err_typecheck_choose_expr_requires_constant);
16382 if (CondICE.isInvalid())
16383 return ExprError();
16384 CondExpr = CondICE.get();
16385 CondIsTrue = condEval.getZExtValue();
16386
16387 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16388 Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
16389
16390 resType = ActiveExpr->getType();
16391 VK = ActiveExpr->getValueKind();
16392 OK = ActiveExpr->getObjectKind();
16393 }
16394
16395 return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
16396 resType, VK, OK, RPLoc, CondIsTrue);
16397}
16398
16399//===----------------------------------------------------------------------===//
16400// Clang Extensions.
16401//===----------------------------------------------------------------------===//
16402
16403/// ActOnBlockStart - This callback is invoked when a block literal is started.
16404void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
16406
16407 if (LangOpts.CPlusPlus) {
16409 Decl *ManglingContextDecl;
16410 std::tie(MCtx, ManglingContextDecl) =
16411 getCurrentMangleNumberContext(Block->getDeclContext());
16412 if (MCtx) {
16413 unsigned ManglingNumber = MCtx->getManglingNumber(Block);
16414 Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
16415 }
16416 }
16417
16418 PushBlockScope(CurScope, Block);
16420 if (CurScope)
16421 PushDeclContext(CurScope, Block);
16422 else
16423 CurContext = Block;
16424
16426
16427 // Enter a new evaluation context to insulate the block from any
16428 // cleanups from the enclosing full-expression.
16431}
16432
16434 Scope *CurScope) {
16435 assert(ParamInfo.getIdentifier() == nullptr &&
16436 "block-id should have no identifier!");
16437 assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteral);
16438 BlockScopeInfo *CurBlock = getCurBlock();
16439
16440 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo);
16441 QualType T = Sig->getType();
16442
16443 // FIXME: We should allow unexpanded parameter packs here, but that would,
16444 // in turn, make the block expression contain unexpanded parameter packs.
16445 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
16446 // Drop the parameters.
16448 EPI.HasTrailingReturn = false;
16449 EPI.TypeQuals.addConst();
16450 T = Context.getFunctionType(Context.DependentTy, std::nullopt, EPI);
16452 }
16453
16454 // GetTypeForDeclarator always produces a function type for a block
16455 // literal signature. Furthermore, it is always a FunctionProtoType
16456 // unless the function was written with a typedef.
16457 assert(T->isFunctionType() &&
16458 "GetTypeForDeclarator made a non-function block signature");
16459
16460 // Look for an explicit signature in that function type.
16461 FunctionProtoTypeLoc ExplicitSignature;
16462
16463 if ((ExplicitSignature = Sig->getTypeLoc()
16465
16466 // Check whether that explicit signature was synthesized by
16467 // GetTypeForDeclarator. If so, don't save that as part of the
16468 // written signature.
16469 if (ExplicitSignature.getLocalRangeBegin() ==
16470 ExplicitSignature.getLocalRangeEnd()) {
16471 // This would be much cheaper if we stored TypeLocs instead of
16472 // TypeSourceInfos.
16473 TypeLoc Result = ExplicitSignature.getReturnLoc();
16474 unsigned Size = Result.getFullDataSize();
16475 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
16476 Sig->getTypeLoc().initializeFullCopy(Result, Size);
16477
16478 ExplicitSignature = FunctionProtoTypeLoc();
16479 }
16480 }
16481
16482 CurBlock->TheDecl->setSignatureAsWritten(Sig);
16483 CurBlock->FunctionType = T;
16484
16485 const auto *Fn = T->castAs<FunctionType>();
16486 QualType RetTy = Fn->getReturnType();
16487 bool isVariadic =
16488 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
16489
16490 CurBlock->TheDecl->setIsVariadic(isVariadic);
16491
16492 // Context.DependentTy is used as a placeholder for a missing block
16493 // return type. TODO: what should we do with declarators like:
16494 // ^ * { ... }
16495 // If the answer is "apply template argument deduction"....
16496 if (RetTy != Context.DependentTy) {
16497 CurBlock->ReturnType = RetTy;
16498 CurBlock->TheDecl->setBlockMissingReturnType(false);
16499 CurBlock->HasImplicitReturnType = false;
16500 }
16501
16502 // Push block parameters from the declarator if we had them.
16504 if (ExplicitSignature) {
16505 for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
16506 ParmVarDecl *Param = ExplicitSignature.getParam(I);
16507 if (Param->getIdentifier() == nullptr && !Param->isImplicit() &&
16508 !Param->isInvalidDecl() && !getLangOpts().CPlusPlus) {
16509 // Diagnose this as an extension in C17 and earlier.
16510 if (!getLangOpts().C23)
16511 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
16512 }
16513 Params.push_back(Param);
16514 }
16515
16516 // Fake up parameter variables if we have a typedef, like
16517 // ^ fntype { ... }
16518 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
16519 for (const auto &I : Fn->param_types()) {
16521 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16522 Params.push_back(Param);
16523 }
16524 }
16525
16526 // Set the parameters on the block decl.
16527 if (!Params.empty()) {
16528 CurBlock->TheDecl->setParams(Params);
16530 /*CheckParameterNames=*/false);
16531 }
16532
16533 // Finally we can process decl attributes.
16534 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
16535
16536 // Put the parameter variables in scope.
16537 for (auto *AI : CurBlock->TheDecl->parameters()) {
16538 AI->setOwningFunction(CurBlock->TheDecl);
16539
16540 // If this has an identifier, add it to the scope stack.
16541 if (AI->getIdentifier()) {
16542 CheckShadow(CurBlock->TheScope, AI);
16543
16544 PushOnScopeChains(AI, CurBlock->TheScope);
16545 }
16546
16547 if (AI->isInvalidDecl())
16548 CurBlock->TheDecl->setInvalidDecl();
16549 }
16550}
16551
16552/// ActOnBlockError - If there is an error parsing a block, this callback
16553/// is invoked to pop the information about the block from the action impl.
16554void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
16555 // Leave the expression-evaluation context.
16558
16559 // Pop off CurBlock, handle nested blocks.
16562}
16563
16564/// ActOnBlockStmtExpr - This is called when the body of a block statement
16565/// literal was successfully completed. ^(int x){...}
16567 Stmt *Body, Scope *CurScope) {
16568 // If blocks are disabled, emit an error.
16569 if (!LangOpts.Blocks)
16570 Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
16571
16572 // Leave the expression-evaluation context.
16575 assert(!Cleanup.exprNeedsCleanups() &&
16576 "cleanups within block not correctly bound!");
16578
16579 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
16580 BlockDecl *BD = BSI->TheDecl;
16581
16582 if (BSI->HasImplicitReturnType)
16584
16585 QualType RetTy = Context.VoidTy;
16586 if (!BSI->ReturnType.isNull())
16587 RetTy = BSI->ReturnType;
16588
16589 bool NoReturn = BD->hasAttr<NoReturnAttr>();
16590 QualType BlockTy;
16591
16592 // If the user wrote a function type in some form, try to use that.
16593 if (!BSI->FunctionType.isNull()) {
16594 const FunctionType *FTy = BSI->FunctionType->castAs<FunctionType>();
16595
16596 FunctionType::ExtInfo Ext = FTy->getExtInfo();
16597 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
16598
16599 // Turn protoless block types into nullary block types.
16600 if (isa<FunctionNoProtoType>(FTy)) {
16602 EPI.ExtInfo = Ext;
16603 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16604
16605 // Otherwise, if we don't need to change anything about the function type,
16606 // preserve its sugar structure.
16607 } else if (FTy->getReturnType() == RetTy &&
16608 (!NoReturn || FTy->getNoReturnAttr())) {
16609 BlockTy = BSI->FunctionType;
16610
16611 // Otherwise, make the minimal modifications to the function type.
16612 } else {
16613 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
16615 EPI.TypeQuals = Qualifiers();
16616 EPI.ExtInfo = Ext;
16617 BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
16618 }
16619
16620 // If we don't have a function type, just build one from nothing.
16621 } else {
16623 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
16624 BlockTy = Context.getFunctionType(RetTy, std::nullopt, EPI);
16625 }
16626
16628 BlockTy = Context.getBlockPointerType(BlockTy);
16629
16630 // If needed, diagnose invalid gotos and switches in the block.
16631 if (getCurFunction()->NeedsScopeChecking() &&
16633 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
16634
16635 BD->setBody(cast<CompoundStmt>(Body));
16636
16637 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16639
16640 // Try to apply the named return value optimization. We have to check again
16641 // if we can do this, though, because blocks keep return statements around
16642 // to deduce an implicit return type.
16643 if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
16644 !BD->isDependentContext())
16645 computeNRVO(Body, BSI);
16646
16651
16653
16654 // Set the captured variables on the block.
16656 for (Capture &Cap : BSI->Captures) {
16657 if (Cap.isInvalid() || Cap.isThisCapture())
16658 continue;
16659 // Cap.getVariable() is always a VarDecl because
16660 // blocks cannot capture structured bindings or other ValueDecl kinds.
16661 auto *Var = cast<VarDecl>(Cap.getVariable());
16662 Expr *CopyExpr = nullptr;
16663 if (getLangOpts().CPlusPlus && Cap.isCopyCapture()) {
16664 if (const RecordType *Record =
16665 Cap.getCaptureType()->getAs<RecordType>()) {
16666 // The capture logic needs the destructor, so make sure we mark it.
16667 // Usually this is unnecessary because most local variables have
16668 // their destructors marked at declaration time, but parameters are
16669 // an exception because it's technically only the call site that
16670 // actually requires the destructor.
16671 if (isa<ParmVarDecl>(Var))
16673
16674 // Enter a separate potentially-evaluated context while building block
16675 // initializers to isolate their cleanups from those of the block
16676 // itself.
16677 // FIXME: Is this appropriate even when the block itself occurs in an
16678 // unevaluated operand?
16681
16682 SourceLocation Loc = Cap.getLocation();
16683
16685 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
16686
16687 // According to the blocks spec, the capture of a variable from
16688 // the stack requires a const copy constructor. This is not true
16689 // of the copy/move done to move a __block variable to the heap.
16690 if (!Result.isInvalid() &&
16691 !Result.get()->getType().isConstQualified()) {
16693 Result.get()->getType().withConst(),
16694 CK_NoOp, VK_LValue);
16695 }
16696
16697 if (!Result.isInvalid()) {
16699 InitializedEntity::InitializeBlock(Var->getLocation(),
16700 Cap.getCaptureType()),
16701 Loc, Result.get());
16702 }
16703
16704 // Build a full-expression copy expression if initialization
16705 // succeeded and used a non-trivial constructor. Recover from
16706 // errors by pretending that the copy isn't necessary.
16707 if (!Result.isInvalid() &&
16708 !cast<CXXConstructExpr>(Result.get())->getConstructor()
16709 ->isTrivial()) {
16711 CopyExpr = Result.get();
16712 }
16713 }
16714 }
16715
16716 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16717 CopyExpr);
16718 Captures.push_back(NewCap);
16719 }
16720 BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
16721
16722 // Pop the block scope now but keep it alive to the end of this function.
16724 PoppedFunctionScopePtr ScopeRAII = PopFunctionScopeInfo(&WP, BD, BlockTy);
16725
16726 BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
16727
16728 // If the block isn't obviously global, i.e. it captures anything at
16729 // all, then we need to do a few things in the surrounding context:
16730 if (Result->getBlockDecl()->hasCaptures()) {
16731 // First, this expression has a new cleanup object.
16732 ExprCleanupObjects.push_back(Result->getBlockDecl());
16734
16735 // It also gets a branch-protected scope if any of the captured
16736 // variables needs destruction.
16737 for (const auto &CI : Result->getBlockDecl()->captures()) {
16738 const VarDecl *var = CI.getVariable();
16739 if (var->getType().isDestructedType() != QualType::DK_none) {
16741 break;
16742 }
16743 }
16744 }
16745
16746 if (getCurFunction())
16747 getCurFunction()->addBlock(BD);
16748
16749 if (BD->isInvalidDecl())
16750 return CreateRecoveryExpr(Result->getBeginLoc(), Result->getEndLoc(),
16751 {Result}, Result->getType());
16752 return Result;
16753}
16754
16756 SourceLocation RPLoc) {
16757 TypeSourceInfo *TInfo;
16758 GetTypeFromParser(Ty, &TInfo);
16759 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16760}
16761
16763 Expr *E, TypeSourceInfo *TInfo,
16764 SourceLocation RPLoc) {
16765 Expr *OrigExpr = E;
16766 bool IsMS = false;
16767
16768 // CUDA device code does not support varargs.
16769 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
16770 if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
16774 return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
16775 }
16776 }
16777
16778 // NVPTX does not support va_arg expression.
16779 if (getLangOpts().OpenMP && getLangOpts().OpenMPIsTargetDevice &&
16780 Context.getTargetInfo().getTriple().isNVPTX())
16781 targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
16782
16783 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16784 // as Microsoft ABI on an actual Microsoft platform, where
16785 // __builtin_ms_va_list and __builtin_va_list are the same.)
16788 QualType MSVaListType = Context.getBuiltinMSVaListType();
16789 if (Context.hasSameType(MSVaListType, E->getType())) {
16790 if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
16791 return ExprError();
16792 IsMS = true;
16793 }
16794 }
16795
16796 // Get the va_list type
16797 QualType VaListType = Context.getBuiltinVaListType();
16798 if (!IsMS) {
16799 if (VaListType->isArrayType()) {
16800 // Deal with implicit array decay; for example, on x86-64,
16801 // va_list is an array, but it's supposed to decay to
16802 // a pointer for va_arg.
16803 VaListType = Context.getArrayDecayedType(VaListType);
16804 // Make sure the input expression also decays appropriately.
16806 if (Result.isInvalid())
16807 return ExprError();
16808 E = Result.get();
16809 } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
16810 // If va_list is a record type and we are compiling in C++ mode,
16811 // check the argument using reference binding.
16813 Context, Context.getLValueReferenceType(VaListType), false);
16815 if (Init.isInvalid())
16816 return ExprError();
16817 E = Init.getAs<Expr>();
16818 } else {
16819 // Otherwise, the va_list argument must be an l-value because
16820 // it is modified by va_arg.
16821 if (!E->isTypeDependent() &&
16822 CheckForModifiableLvalue(E, BuiltinLoc, *this))
16823 return ExprError();
16824 }
16825 }
16826
16827 if (!IsMS && !E->isTypeDependent() &&
16828 !Context.hasSameType(VaListType, E->getType()))
16829 return ExprError(
16830 Diag(E->getBeginLoc(),
16831 diag::err_first_argument_to_va_arg_not_of_type_va_list)
16832 << OrigExpr->getType() << E->getSourceRange());
16833
16834 if (!TInfo->getType()->isDependentType()) {
16835 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
16836 diag::err_second_parameter_to_va_arg_incomplete,
16837 TInfo->getTypeLoc()))
16838 return ExprError();
16839
16841 TInfo->getType(),
16842 diag::err_second_parameter_to_va_arg_abstract,
16843 TInfo->getTypeLoc()))
16844 return ExprError();
16845
16846 if (!TInfo->getType().isPODType(Context)) {
16847 Diag(TInfo->getTypeLoc().getBeginLoc(),
16848 TInfo->getType()->isObjCLifetimeType()
16849 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16850 : diag::warn_second_parameter_to_va_arg_not_pod)
16851 << TInfo->getType()
16852 << TInfo->getTypeLoc().getSourceRange();
16853 }
16854
16855 // Check for va_arg where arguments of the given type will be promoted
16856 // (i.e. this va_arg is guaranteed to have undefined behavior).
16857 QualType PromoteType;
16858 if (Context.isPromotableIntegerType(TInfo->getType())) {
16859 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
16860 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16861 // and C23 7.16.1.1p2 says, in part:
16862 // If type is not compatible with the type of the actual next argument
16863 // (as promoted according to the default argument promotions), the
16864 // behavior is undefined, except for the following cases:
16865 // - both types are pointers to qualified or unqualified versions of
16866 // compatible types;
16867 // - one type is compatible with a signed integer type, the other
16868 // type is compatible with the corresponding unsigned integer type,
16869 // and the value is representable in both types;
16870 // - one type is pointer to qualified or unqualified void and the
16871 // other is a pointer to a qualified or unqualified character type;
16872 // - or, the type of the next argument is nullptr_t and type is a
16873 // pointer type that has the same representation and alignment
16874 // requirements as a pointer to a character type.
16875 // Given that type compatibility is the primary requirement (ignoring
16876 // qualifications), you would think we could call typesAreCompatible()
16877 // directly to test this. However, in C++, that checks for *same type*,
16878 // which causes false positives when passing an enumeration type to
16879 // va_arg. Instead, get the underlying type of the enumeration and pass
16880 // that.
16881 QualType UnderlyingType = TInfo->getType();
16882 if (const auto *ET = UnderlyingType->getAs<EnumType>())
16883 UnderlyingType = ET->getDecl()->getIntegerType();
16884 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16885 /*CompareUnqualified*/ true))
16886 PromoteType = QualType();
16887
16888 // If the types are still not compatible, we need to test whether the
16889 // promoted type and the underlying type are the same except for
16890 // signedness. Ask the AST for the correctly corresponding type and see
16891 // if that's compatible.
16892 if (!PromoteType.isNull() && !UnderlyingType->isBooleanType() &&
16893 PromoteType->isUnsignedIntegerType() !=
16894 UnderlyingType->isUnsignedIntegerType()) {
16895 UnderlyingType =
16896 UnderlyingType->isUnsignedIntegerType()
16897 ? Context.getCorrespondingSignedType(UnderlyingType)
16898 : Context.getCorrespondingUnsignedType(UnderlyingType);
16899 if (Context.typesAreCompatible(PromoteType, UnderlyingType,
16900 /*CompareUnqualified*/ true))
16901 PromoteType = QualType();
16902 }
16903 }
16904 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
16905 PromoteType = Context.DoubleTy;
16906 if (!PromoteType.isNull())
16908 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16909 << TInfo->getType()
16910 << PromoteType
16911 << TInfo->getTypeLoc().getSourceRange());
16912 }
16913
16915 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16916}
16917
16919 // The type of __null will be int or long, depending on the size of
16920 // pointers on the target.
16921 QualType Ty;
16923 if (pw == Context.getTargetInfo().getIntWidth())
16924 Ty = Context.IntTy;
16925 else if (pw == Context.getTargetInfo().getLongWidth())
16926 Ty = Context.LongTy;
16927 else if (pw == Context.getTargetInfo().getLongLongWidth())
16928 Ty = Context.LongLongTy;
16929 else {
16930 llvm_unreachable("I don't know size of pointer!");
16931 }
16932
16933 return new (Context) GNUNullExpr(Ty, TokenLoc);
16934}
16935
16937 CXXRecordDecl *ImplDecl = nullptr;
16938
16939 // Fetch the std::source_location::__impl decl.
16940 if (NamespaceDecl *Std = S.getStdNamespace()) {
16941 LookupResult ResultSL(S, &S.PP.getIdentifierTable().get("source_location"),
16943 if (S.LookupQualifiedName(ResultSL, Std)) {
16944 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16945 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get("__impl"),
16947 if ((SLDecl->isCompleteDefinition() || SLDecl->isBeingDefined()) &&
16948 S.LookupQualifiedName(ResultImpl, SLDecl)) {
16949 ImplDecl = ResultImpl.getAsSingle<CXXRecordDecl>();
16950 }
16951 }
16952 }
16953 }
16954
16955 if (!ImplDecl || !ImplDecl->isCompleteDefinition()) {
16956 S.Diag(Loc, diag::err_std_source_location_impl_not_found);
16957 return nullptr;
16958 }
16959
16960 // Verify that __impl is a trivial struct type, with no base classes, and with
16961 // only the four expected fields.
16962 if (ImplDecl->isUnion() || !ImplDecl->isStandardLayout() ||
16963 ImplDecl->getNumBases() != 0) {
16964 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16965 return nullptr;
16966 }
16967
16968 unsigned Count = 0;
16969 for (FieldDecl *F : ImplDecl->fields()) {
16970 StringRef Name = F->getName();
16971
16972 if (Name == "_M_file_name") {
16973 if (F->getType() !=
16975 break;
16976 Count++;
16977 } else if (Name == "_M_function_name") {
16978 if (F->getType() !=
16980 break;
16981 Count++;
16982 } else if (Name == "_M_line") {
16983 if (!F->getType()->isIntegerType())
16984 break;
16985 Count++;
16986 } else if (Name == "_M_column") {
16987 if (!F->getType()->isIntegerType())
16988 break;
16989 Count++;
16990 } else {
16991 Count = 100; // invalid
16992 break;
16993 }
16994 }
16995 if (Count != 4) {
16996 S.Diag(Loc, diag::err_std_source_location_impl_malformed);
16997 return nullptr;
16998 }
16999
17000 return ImplDecl;
17001}
17002
17004 SourceLocation BuiltinLoc,
17005 SourceLocation RPLoc) {
17006 QualType ResultTy;
17007 switch (Kind) {
17013 ResultTy =
17015 break;
17016 }
17019 ResultTy = Context.UnsignedIntTy;
17020 break;
17024 LookupStdSourceLocationImpl(*this, BuiltinLoc);
17026 return ExprError();
17027 }
17028 ResultTy = Context.getPointerType(
17030 break;
17031 }
17032
17033 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, CurContext);
17034}
17035
17037 SourceLocation BuiltinLoc,
17038 SourceLocation RPLoc,
17039 DeclContext *ParentContext) {
17040 return new (Context)
17041 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17042}
17043
17045 bool Diagnose) {
17046 if (!getLangOpts().ObjC)
17047 return false;
17048
17049 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
17050 if (!PT)
17051 return false;
17052 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
17053
17054 // Ignore any parens, implicit casts (should only be
17055 // array-to-pointer decays), and not-so-opaque values. The last is
17056 // important for making this trigger for property assignments.
17057 Expr *SrcExpr = Exp->IgnoreParenImpCasts();
17058 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
17059 if (OV->getSourceExpr())
17060 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
17061
17062 if (auto *SL = dyn_cast<StringLiteral>(SrcExpr)) {
17063 if (!PT->isObjCIdType() &&
17064 !(ID && ID->getIdentifier()->isStr("NSString")))
17065 return false;
17066 if (!SL->isOrdinary())
17067 return false;
17068
17069 if (Diagnose) {
17070 Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
17071 << /*string*/0 << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
17072 Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
17073 }
17074 return true;
17075 }
17076
17077 if ((isa<IntegerLiteral>(SrcExpr) || isa<CharacterLiteral>(SrcExpr) ||
17078 isa<FloatingLiteral>(SrcExpr) || isa<ObjCBoolLiteralExpr>(SrcExpr) ||
17079 isa<CXXBoolLiteralExpr>(SrcExpr)) &&
17080 !SrcExpr->isNullPointerConstant(
17082 if (!ID || !ID->getIdentifier()->isStr("NSNumber"))
17083 return false;
17084 if (Diagnose) {
17085 Diag(SrcExpr->getBeginLoc(), diag::err_missing_atsign_prefix)
17086 << /*number*/1
17087 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "@");
17088 Expr *NumLit =
17089 BuildObjCNumericLiteral(SrcExpr->getBeginLoc(), SrcExpr).get();
17090 if (NumLit)
17091 Exp = NumLit;
17092 }
17093 return true;
17094 }
17095
17096 return false;
17097}
17098
17100 const Expr *SrcExpr) {
17101 if (!DstType->isFunctionPointerType() ||
17102 !SrcExpr->getType()->isFunctionType())
17103 return false;
17104
17105 auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
17106 if (!DRE)
17107 return false;
17108
17109 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
17110 if (!FD)
17111 return false;
17112
17114 /*Complain=*/true,
17115 SrcExpr->getBeginLoc());
17116}
17117
17119 SourceLocation Loc,
17120 QualType DstType, QualType SrcType,
17121 Expr *SrcExpr, AssignmentAction Action,
17122 bool *Complained) {
17123 if (Complained)
17124 *Complained = false;
17125
17126 // Decode the result (notice that AST's are still created for extensions).
17127 bool CheckInferredResultType = false;
17128 bool isInvalid = false;
17129 unsigned DiagKind = 0;
17130 ConversionFixItGenerator ConvHints;
17131 bool MayHaveConvFixit = false;
17132 bool MayHaveFunctionDiff = false;
17133 const ObjCInterfaceDecl *IFace = nullptr;
17134 const ObjCProtocolDecl *PDecl = nullptr;
17135
17136 switch (ConvTy) {
17137 case Compatible:
17138 DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
17139 return false;
17140
17141 case PointerToInt:
17142 if (getLangOpts().CPlusPlus) {
17143 DiagKind = diag::err_typecheck_convert_pointer_int;
17144 isInvalid = true;
17145 } else {
17146 DiagKind = diag::ext_typecheck_convert_pointer_int;
17147 }
17148 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17149 MayHaveConvFixit = true;
17150 break;
17151 case IntToPointer:
17152 if (getLangOpts().CPlusPlus) {
17153 DiagKind = diag::err_typecheck_convert_int_pointer;
17154 isInvalid = true;
17155 } else {
17156 DiagKind = diag::ext_typecheck_convert_int_pointer;
17157 }
17158 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17159 MayHaveConvFixit = true;
17160 break;
17162 DiagKind =
17163 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17164 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17165 MayHaveConvFixit = true;
17166 break;
17168 if (getLangOpts().CPlusPlus) {
17169 DiagKind = diag::err_typecheck_convert_incompatible_function_pointer;
17170 isInvalid = true;
17171 } else {
17172 DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
17173 }
17174 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17175 MayHaveConvFixit = true;
17176 break;
17178 if (Action == AA_Passing_CFAudited) {
17179 DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
17180 } else if (getLangOpts().CPlusPlus) {
17181 DiagKind = diag::err_typecheck_convert_incompatible_pointer;
17182 isInvalid = true;
17183 } else {
17184 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
17185 }
17186 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
17187 SrcType->isObjCObjectPointerType();
17188 if (!CheckInferredResultType) {
17189 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17190 } else if (CheckInferredResultType) {
17191 SrcType = SrcType.getUnqualifiedType();
17192 DstType = DstType.getUnqualifiedType();
17193 }
17194 MayHaveConvFixit = true;
17195 break;
17197 if (getLangOpts().CPlusPlus) {
17198 DiagKind = diag::err_typecheck_convert_incompatible_pointer_sign;
17199 isInvalid = true;
17200 } else {
17201 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
17202 }
17203 break;
17205 if (getLangOpts().CPlusPlus) {
17206 DiagKind = diag::err_typecheck_convert_pointer_void_func;
17207 isInvalid = true;
17208 } else {
17209 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
17210 }
17211 break;
17213 // Perform array-to-pointer decay if necessary.
17214 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
17215
17216 isInvalid = true;
17217
17218 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
17219 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
17220 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
17221 DiagKind = diag::err_typecheck_incompatible_address_space;
17222 break;
17223 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
17224 DiagKind = diag::err_typecheck_incompatible_ownership;
17225 break;
17226 }
17227
17228 llvm_unreachable("unknown error case for discarding qualifiers!");
17229 // fallthrough
17230 }
17232 // If the qualifiers lost were because we were applying the
17233 // (deprecated) C++ conversion from a string literal to a char*
17234 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17235 // Ideally, this check would be performed in
17236 // checkPointerTypesForAssignment. However, that would require a
17237 // bit of refactoring (so that the second argument is an
17238 // expression, rather than a type), which should be done as part
17239 // of a larger effort to fix checkPointerTypesForAssignment for
17240 // C++ semantics.
17241 if (getLangOpts().CPlusPlus &&
17243 return false;
17244 if (getLangOpts().CPlusPlus) {
17245 DiagKind = diag::err_typecheck_convert_discards_qualifiers;
17246 isInvalid = true;
17247 } else {
17248 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
17249 }
17250
17251 break;
17253 if (getLangOpts().CPlusPlus) {
17254 isInvalid = true;
17255 DiagKind = diag::err_nested_pointer_qualifier_mismatch;
17256 } else {
17257 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
17258 }
17259 break;
17261 DiagKind = diag::err_typecheck_incompatible_nested_address_space;
17262 isInvalid = true;
17263 break;
17264 case IntToBlockPointer:
17265 DiagKind = diag::err_int_to_block_pointer;
17266 isInvalid = true;
17267 break;
17269 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17270 isInvalid = true;
17271 break;
17273 if (SrcType->isObjCQualifiedIdType()) {
17274 const ObjCObjectPointerType *srcOPT =
17275 SrcType->castAs<ObjCObjectPointerType>();
17276 for (auto *srcProto : srcOPT->quals()) {
17277 PDecl = srcProto;
17278 break;
17279 }
17280 if (const ObjCInterfaceType *IFaceT =
17282 IFace = IFaceT->getDecl();
17283 }
17284 else if (DstType->isObjCQualifiedIdType()) {
17285 const ObjCObjectPointerType *dstOPT =
17286 DstType->castAs<ObjCObjectPointerType>();
17287 for (auto *dstProto : dstOPT->quals()) {
17288 PDecl = dstProto;
17289 break;
17290 }
17291 if (const ObjCInterfaceType *IFaceT =
17293 IFace = IFaceT->getDecl();
17294 }
17295 if (getLangOpts().CPlusPlus) {
17296 DiagKind = diag::err_incompatible_qualified_id;
17297 isInvalid = true;
17298 } else {
17299 DiagKind = diag::warn_incompatible_qualified_id;
17300 }
17301 break;
17302 }
17304 if (getLangOpts().CPlusPlus) {
17305 DiagKind = diag::err_incompatible_vectors;
17306 isInvalid = true;
17307 } else {
17308 DiagKind = diag::warn_incompatible_vectors;
17309 }
17310 break;
17312 DiagKind = diag::err_arc_weak_unavailable_assign;
17313 isInvalid = true;
17314 break;
17315 case Incompatible:
17316 if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
17317 if (Complained)
17318 *Complained = true;
17319 return true;
17320 }
17321
17322 DiagKind = diag::err_typecheck_convert_incompatible;
17323 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
17324 MayHaveConvFixit = true;
17325 isInvalid = true;
17326 MayHaveFunctionDiff = true;
17327 break;
17328 }
17329
17330 QualType FirstType, SecondType;
17331 switch (Action) {
17332 case AA_Assigning:
17333 case AA_Initializing:
17334 // The destination type comes first.
17335 FirstType = DstType;
17336 SecondType = SrcType;
17337 break;
17338
17339 case AA_Returning:
17340 case AA_Passing:
17342 case AA_Converting:
17343 case AA_Sending:
17344 case AA_Casting:
17345 // The source type comes first.
17346 FirstType = SrcType;
17347 SecondType = DstType;
17348 break;
17349 }
17350
17351 PartialDiagnostic FDiag = PDiag(DiagKind);
17352 AssignmentAction ActionForDiag = Action;
17353 if (Action == AA_Passing_CFAudited)
17354 ActionForDiag = AA_Passing;
17355
17356 FDiag << FirstType << SecondType << ActionForDiag
17357 << SrcExpr->getSourceRange();
17358
17359 if (DiagKind == diag::ext_typecheck_convert_incompatible_pointer_sign ||
17360 DiagKind == diag::err_typecheck_convert_incompatible_pointer_sign) {
17361 auto isPlainChar = [](const clang::Type *Type) {
17362 return Type->isSpecificBuiltinType(BuiltinType::Char_S) ||
17363 Type->isSpecificBuiltinType(BuiltinType::Char_U);
17364 };
17365 FDiag << (isPlainChar(FirstType->getPointeeOrArrayElementType()) ||
17366 isPlainChar(SecondType->getPointeeOrArrayElementType()));
17367 }
17368
17369 // If we can fix the conversion, suggest the FixIts.
17370 if (!ConvHints.isNull()) {
17371 for (FixItHint &H : ConvHints.Hints)
17372 FDiag << H;
17373 }
17374
17375 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
17376
17377 if (MayHaveFunctionDiff)
17378 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
17379
17380 Diag(Loc, FDiag);
17381 if ((DiagKind == diag::warn_incompatible_qualified_id ||
17382 DiagKind == diag::err_incompatible_qualified_id) &&
17383 PDecl && IFace && !IFace->hasDefinition())
17384 Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
17385 << IFace << PDecl;
17386
17387 if (SecondType == Context.OverloadTy)
17389 FirstType, /*TakingAddress=*/true);
17390
17391 if (CheckInferredResultType)
17393
17394 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17396
17397 if (Complained)
17398 *Complained = true;
17399 return isInvalid;
17400}
17401
17403 llvm::APSInt *Result,
17404 AllowFoldKind CanFold) {
17405 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
17406 public:
17407 SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
17408 QualType T) override {
17409 return S.Diag(Loc, diag::err_ice_not_integral)
17410 << T << S.LangOpts.CPlusPlus;
17411 }
17412 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17413 return S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus;
17414 }
17415 } Diagnoser;
17416
17417 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17418}
17419
17421 llvm::APSInt *Result,
17422 unsigned DiagID,
17423 AllowFoldKind CanFold) {
17424 class IDDiagnoser : public VerifyICEDiagnoser {
17425 unsigned DiagID;
17426
17427 public:
17428 IDDiagnoser(unsigned DiagID)
17429 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
17430
17431 SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) override {
17432 return S.Diag(Loc, DiagID);
17433 }
17434 } Diagnoser(DiagID);
17435
17436 return VerifyIntegerConstantExpression(E, Result, Diagnoser, CanFold);
17437}
17438
17441 QualType T) {
17442 return diagnoseNotICE(S, Loc);
17443}
17444
17447 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17448}
17449
17452 VerifyICEDiagnoser &Diagnoser,
17453 AllowFoldKind CanFold) {
17454 SourceLocation DiagLoc = E->getBeginLoc();
17455
17456 if (getLangOpts().CPlusPlus11) {
17457 // C++11 [expr.const]p5:
17458 // If an expression of literal class type is used in a context where an
17459 // integral constant expression is required, then that class type shall
17460 // have a single non-explicit conversion function to an integral or
17461 // unscoped enumeration type
17462 ExprResult Converted;
17463 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
17464 VerifyICEDiagnoser &BaseDiagnoser;
17465 public:
17466 CXX11ConvertDiagnoser(VerifyICEDiagnoser &BaseDiagnoser)
17467 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17468 BaseDiagnoser.Suppress, true),
17469 BaseDiagnoser(BaseDiagnoser) {}
17470
17471 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
17472 QualType T) override {
17473 return BaseDiagnoser.diagnoseNotICEType(S, Loc, T);
17474 }
17475
17476 SemaDiagnosticBuilder diagnoseIncomplete(
17477 Sema &S, SourceLocation Loc, QualType T) override {
17478 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
17479 }
17480
17481 SemaDiagnosticBuilder diagnoseExplicitConv(
17482 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17483 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
17484 }
17485
17486 SemaDiagnosticBuilder noteExplicitConv(
17487 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17488 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17489 << ConvTy->isEnumeralType() << ConvTy;
17490 }
17491
17492 SemaDiagnosticBuilder diagnoseAmbiguous(
17493 Sema &S, SourceLocation Loc, QualType T) override {
17494 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
17495 }
17496
17497 SemaDiagnosticBuilder noteAmbiguous(
17498 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
17499 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
17500 << ConvTy->isEnumeralType() << ConvTy;
17501 }
17502
17503 SemaDiagnosticBuilder diagnoseConversion(
17504 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
17505 llvm_unreachable("conversion functions are permitted");
17506 }
17507 } ConvertDiagnoser(Diagnoser);
17508
17509 Converted = PerformContextualImplicitConversion(DiagLoc, E,
17510 ConvertDiagnoser);
17511 if (Converted.isInvalid())
17512 return Converted;
17513 E = Converted.get();
17514 // The 'explicit' case causes us to get a RecoveryExpr. Give up here so we
17515 // don't try to evaluate it later. We also don't want to return the
17516 // RecoveryExpr here, as it results in this call succeeding, thus callers of
17517 // this function will attempt to use 'Value'.
17518 if (isa<RecoveryExpr>(E))
17519 return ExprError();
17521 return ExprError();
17522 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
17523 // An ICE must be of integral or unscoped enumeration type.
17524 if (!Diagnoser.Suppress)
17525 Diagnoser.diagnoseNotICEType(*this, DiagLoc, E->getType())
17526 << E->getSourceRange();
17527 return ExprError();
17528 }
17529
17530 ExprResult RValueExpr = DefaultLvalueConversion(E);
17531 if (RValueExpr.isInvalid())
17532 return ExprError();
17533
17534 E = RValueExpr.get();
17535
17536 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17537 // in the non-ICE case.
17539 if (Result)
17541 if (!isa<ConstantExpr>(E))
17544 return E;
17545 }
17546
17547 Expr::EvalResult EvalResult;
17549 EvalResult.Diag = &Notes;
17550
17551 // Try to evaluate the expression, and produce diagnostics explaining why it's
17552 // not a constant expression as a side-effect.
17553 bool Folded =
17554 E->EvaluateAsRValue(EvalResult, Context, /*isConstantContext*/ true) &&
17555 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
17556
17557 if (!isa<ConstantExpr>(E))
17558 E = ConstantExpr::Create(Context, E, EvalResult.Val);
17559
17560 // In C++11, we can rely on diagnostics being produced for any expression
17561 // which is not a constant expression. If no diagnostics were produced, then
17562 // this is a constant expression.
17563 if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
17564 if (Result)
17565 *Result = EvalResult.Val.getInt();
17566 return E;
17567 }
17568
17569 // If our only note is the usual "invalid subexpression" note, just point
17570 // the caret at its location rather than producing an essentially
17571 // redundant note.
17572 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
17573 diag::note_invalid_subexpr_in_const_expr) {
17574 DiagLoc = Notes[0].first;
17575 Notes.clear();
17576 }
17577
17578 if (!Folded || !CanFold) {
17579 if (!Diagnoser.Suppress) {
17580 Diagnoser.diagnoseNotICE(*this, DiagLoc) << E->getSourceRange();
17581 for (const PartialDiagnosticAt &Note : Notes)
17582 Diag(Note.first, Note.second);
17583 }
17584
17585 return ExprError();
17586 }
17587
17588 Diagnoser.diagnoseFold(*this, DiagLoc) << E->getSourceRange();
17589 for (const PartialDiagnosticAt &Note : Notes)
17590 Diag(Note.first, Note.second);
17591
17592 if (Result)
17593 *Result = EvalResult.Val.getInt();
17594 return E;
17595}
17596
17597namespace {
17598 // Handle the case where we conclude a expression which we speculatively
17599 // considered to be unevaluated is actually evaluated.
17600 class TransformToPE : public TreeTransform<TransformToPE> {
17601 typedef TreeTransform<TransformToPE> BaseTransform;
17602
17603 public:
17604 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
17605
17606 // Make sure we redo semantic analysis
17607 bool AlwaysRebuild() { return true; }
17608 bool ReplacingOriginal() { return true; }
17609
17610 // We need to special-case DeclRefExprs referring to FieldDecls which
17611 // are not part of a member pointer formation; normal TreeTransforming
17612 // doesn't catch this case because of the way we represent them in the AST.
17613 // FIXME: This is a bit ugly; is it really the best way to handle this
17614 // case?
17615 //
17616 // Error on DeclRefExprs referring to FieldDecls.
17617 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17618 if (isa<FieldDecl>(E->getDecl()) &&
17619 !SemaRef.isUnevaluatedContext())
17620 return SemaRef.Diag(E->getLocation(),
17621 diag::err_invalid_non_static_member_use)
17622 << E->getDecl() << E->getSourceRange();
17623
17624 return BaseTransform::TransformDeclRefExpr(E);
17625 }
17626
17627 // Exception: filter out member pointer formation
17628 ExprResult TransformUnaryOperator(UnaryOperator *E) {
17629 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
17630 return E;
17631
17632 return BaseTransform::TransformUnaryOperator(E);
17633 }
17634
17635 // The body of a lambda-expression is in a separate expression evaluation
17636 // context so never needs to be transformed.
17637 // FIXME: Ideally we wouldn't transform the closure type either, and would
17638 // just recreate the capture expressions and lambda expression.
17639 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
17640 return SkipLambdaBody(E, Body);
17641 }
17642 };
17643}
17644
17646 assert(isUnevaluatedContext() &&
17647 "Should only transform unevaluated expressions");
17648 ExprEvalContexts.back().Context =
17649 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17651 return E;
17652 return TransformToPE(*this).TransformExpr(E);
17653}
17654
17656 assert(isUnevaluatedContext() &&
17657 "Should only transform unevaluated expressions");
17658 ExprEvalContexts.back().Context =
17659 ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
17661 return TInfo;
17662 return TransformToPE(*this).TransformType(TInfo);
17663}
17664
17665void
17667 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17669 ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
17670 LambdaContextDecl, ExprContext);
17671
17672 // Discarded statements and immediate contexts nested in other
17673 // discarded statements or immediate context are themselves
17674 // a discarded statement or an immediate context, respectively.
17675 ExprEvalContexts.back().InDiscardedStatement =
17677 .isDiscardedStatementContext();
17678
17679 // C++23 [expr.const]/p15
17680 // An expression or conversion is in an immediate function context if [...]
17681 // it is a subexpression of a manifestly constant-evaluated expression or
17682 // conversion.
17683 const auto &Prev = ExprEvalContexts[ExprEvalContexts.size() - 2];
17684 ExprEvalContexts.back().InImmediateFunctionContext =
17685 Prev.isImmediateFunctionContext() || Prev.isConstantEvaluated();
17686
17687 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
17688 Prev.InImmediateEscalatingFunctionContext;
17689
17690 Cleanup.reset();
17691 if (!MaybeODRUseExprs.empty())
17692 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
17693}
17694
17695void
17699 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17700 PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
17701}
17702
17703namespace {
17704
17705const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
17706 PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
17707 if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
17708 if (E->getOpcode() == UO_Deref)
17709 return CheckPossibleDeref(S, E->getSubExpr());
17710 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
17711 return CheckPossibleDeref(S, E->getBase());
17712 } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
17713 return CheckPossibleDeref(S, E->getBase());
17714 } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
17715 QualType Inner;
17716 QualType Ty = E->getType();
17717 if (const auto *Ptr = Ty->getAs<PointerType>())
17718 Inner = Ptr->getPointeeType();
17719 else if (const auto *Arr = S.Context.getAsArrayType(Ty))
17720 Inner = Arr->getElementType();
17721 else
17722 return nullptr;
17723
17724 if (Inner->hasAttr(attr::NoDeref))
17725 return E;
17726 }
17727 return nullptr;
17728}
17729
17730} // namespace
17731
17733 for (const Expr *E : Rec.PossibleDerefs) {
17734 const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
17735 if (DeclRef) {
17736 const ValueDecl *Decl = DeclRef->getDecl();
17737 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
17738 << Decl->getName() << E->getSourceRange();
17739 Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
17740 } else {
17741 Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
17742 << E->getSourceRange();
17743 }
17744 }
17745 Rec.PossibleDerefs.clear();
17746}
17747
17748/// Check whether E, which is either a discarded-value expression or an
17749/// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17750/// and if so, remove it from the list of volatile-qualified assignments that
17751/// we are going to warn are deprecated.
17754 return;
17755
17756 // Note: ignoring parens here is not justified by the standard rules, but
17757 // ignoring parentheses seems like a more reasonable approach, and this only
17758 // drives a deprecation warning so doesn't affect conformance.
17759 if (auto *BO = dyn_cast<BinaryOperator>(E->IgnoreParenImpCasts())) {
17760 if (BO->getOpcode() == BO_Assign) {
17761 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17762 llvm::erase(LHSs, BO->getLHS());
17763 }
17764 }
17765}
17766
17768 assert(getLangOpts().CPlusPlus20 &&
17769 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17770 "Cannot mark an immediate escalating expression outside of an "
17771 "immediate escalating context");
17772 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreImplicit());
17773 Call && Call->getCallee()) {
17774 if (auto *DeclRef =
17775 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17776 DeclRef->setIsImmediateEscalating(true);
17777 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(E->IgnoreImplicit())) {
17778 Ctr->setIsImmediateEscalating(true);
17779 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreImplicit())) {
17780 DeclRef->setIsImmediateEscalating(true);
17781 } else {
17782 assert(false && "expected an immediately escalating expression");
17783 }
17785 FI->FoundImmediateEscalatingExpression = true;
17786}
17787
17789 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17790 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
17793 return E;
17794
17795 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17796 /// It's OK if this fails; we'll also remove this in
17797 /// HandleImmediateInvocations, but catching it here allows us to avoid
17798 /// walking the AST looking for it in simple cases.
17799 if (auto *Call = dyn_cast<CallExpr>(E.get()->IgnoreImplicit()))
17800 if (auto *DeclRef =
17801 dyn_cast<DeclRefExpr>(Call->getCallee()->IgnoreImplicit()))
17802 ExprEvalContexts.back().ReferenceToConsteval.erase(DeclRef);
17803
17804 // C++23 [expr.const]/p16
17805 // An expression or conversion is immediate-escalating if it is not initially
17806 // in an immediate function context and it is [...] an immediate invocation
17807 // that is not a constant expression and is not a subexpression of an
17808 // immediate invocation.
17809 APValue Cached;
17810 auto CheckConstantExpressionAndKeepResult = [&]() {
17812 Expr::EvalResult Eval;
17813 Eval.Diag = &Notes;
17814 bool Res = E.get()->EvaluateAsConstantExpr(
17815 Eval, getASTContext(), ConstantExprKind::ImmediateInvocation);
17816 if (Res && Notes.empty()) {
17817 Cached = std::move(Eval.Val);
17818 return true;
17819 }
17820 return false;
17821 };
17822
17823 if (!E.get()->isValueDependent() &&
17824 ExprEvalContexts.back().InImmediateEscalatingFunctionContext &&
17825 !CheckConstantExpressionAndKeepResult()) {
17827 return E;
17828 }
17829
17830 if (Cleanup.exprNeedsCleanups()) {
17831 // Since an immediate invocation is a full expression itself - it requires
17832 // an additional ExprWithCleanups node, but it can participate to a bigger
17833 // full expression which actually requires cleanups to be run after so
17834 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
17835 // may discard cleanups for outer expression too early.
17836
17837 // Note that ExprWithCleanups created here must always have empty cleanup
17838 // objects:
17839 // - compound literals do not create cleanup objects in C++ and immediate
17840 // invocations are C++-only.
17841 // - blocks are not allowed inside constant expressions and compiler will
17842 // issue an error if they appear there.
17843 //
17844 // Hence, in correct code any cleanup objects created inside current
17845 // evaluation context must be outside the immediate invocation.
17848 }
17849
17851 getASTContext(), E.get(),
17852 ConstantExpr::getStorageKind(Decl->getReturnType().getTypePtr(),
17853 getASTContext()),
17854 /*IsImmediateInvocation*/ true);
17855 if (Cached.hasValue())
17856 Res->MoveIntoResult(Cached, getASTContext());
17857 /// Value-dependent constant expressions should not be immediately
17858 /// evaluated until they are instantiated.
17859 if (!Res->isValueDependent())
17860 ExprEvalContexts.back().ImmediateInvocationCandidates.emplace_back(Res, 0);
17861 return Res;
17862}
17863
17867 Expr::EvalResult Eval;
17868 Eval.Diag = &Notes;
17869 ConstantExpr *CE = Candidate.getPointer();
17870 bool Result = CE->EvaluateAsConstantExpr(
17871 Eval, SemaRef.getASTContext(), ConstantExprKind::ImmediateInvocation);
17872 if (!Result || !Notes.empty()) {
17874 Expr *InnerExpr = CE->getSubExpr()->IgnoreImplicit();
17875 if (auto *FunctionalCast = dyn_cast<CXXFunctionalCastExpr>(InnerExpr))
17876 InnerExpr = FunctionalCast->getSubExpr()->IgnoreImplicit();
17877 FunctionDecl *FD = nullptr;
17878 if (auto *Call = dyn_cast<CallExpr>(InnerExpr))
17879 FD = cast<FunctionDecl>(Call->getCalleeDecl());
17880 else if (auto *Call = dyn_cast<CXXConstructExpr>(InnerExpr))
17881 FD = Call->getConstructor();
17882 else if (auto *Cast = dyn_cast<CastExpr>(InnerExpr))
17883 FD = dyn_cast_or_null<FunctionDecl>(Cast->getConversionFunction());
17884
17885 assert(FD && FD->isImmediateFunction() &&
17886 "could not find an immediate function in this expression");
17887 if (FD->isInvalidDecl())
17888 return;
17889 SemaRef.Diag(CE->getBeginLoc(), diag::err_invalid_consteval_call)
17890 << FD << FD->isConsteval();
17891 if (auto Context =
17893 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
17894 << Context->Decl;
17895 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
17896 }
17897 if (!FD->isConsteval())
17899 for (auto &Note : Notes)
17900 SemaRef.Diag(Note.first, Note.second);
17901 return;
17902 }
17904}
17905
17909 struct ComplexRemove : TreeTransform<ComplexRemove> {
17911 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17914 CurrentII;
17915 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17918 4>::reverse_iterator Current)
17919 : Base(SemaRef), DRSet(DR), IISet(II), CurrentII(Current) {}
17920 void RemoveImmediateInvocation(ConstantExpr* E) {
17921 auto It = std::find_if(CurrentII, IISet.rend(),
17923 return Elem.getPointer() == E;
17924 });
17925 // It is possible that some subexpression of the current immediate
17926 // invocation was handled from another expression evaluation context. Do
17927 // not handle the current immediate invocation if some of its
17928 // subexpressions failed before.
17929 if (It == IISet.rend()) {
17930 if (SemaRef.FailedImmediateInvocations.contains(E))
17931 CurrentII->setInt(1);
17932 } else {
17933 It->setInt(1); // Mark as deleted
17934 }
17935 }
17936 ExprResult TransformConstantExpr(ConstantExpr *E) {
17937 if (!E->isImmediateInvocation())
17938 return Base::TransformConstantExpr(E);
17939 RemoveImmediateInvocation(E);
17940 return Base::TransformExpr(E->getSubExpr());
17941 }
17942 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17943 /// we need to remove its DeclRefExpr from the DRSet.
17944 ExprResult TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
17945 DRSet.erase(cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit()));
17946 return Base::TransformCXXOperatorCallExpr(E);
17947 }
17948 /// Base::TransformUserDefinedLiteral doesn't preserve the
17949 /// UserDefinedLiteral node.
17950 ExprResult TransformUserDefinedLiteral(UserDefinedLiteral *E) { return E; }
17951 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
17952 /// here.
17953 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit) {
17954 if (!Init)
17955 return Init;
17956 /// ConstantExpr are the first layer of implicit node to be removed so if
17957 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17958 if (auto *CE = dyn_cast<ConstantExpr>(Init))
17959 if (CE->isImmediateInvocation())
17960 RemoveImmediateInvocation(CE);
17961 return Base::TransformInitializer(Init, NotCopyInit);
17962 }
17963 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17964 DRSet.erase(E);
17965 return E;
17966 }
17967 ExprResult TransformLambdaExpr(LambdaExpr *E) {
17968 // Do not rebuild lambdas to avoid creating a new type.
17969 // Lambdas have already been processed inside their eval context.
17970 return E;
17971 }
17972 bool AlwaysRebuild() { return false; }
17973 bool ReplacingOriginal() { return true; }
17974 bool AllowSkippingCXXConstructExpr() {
17975 bool Res = AllowSkippingFirstCXXConstructExpr;
17976 AllowSkippingFirstCXXConstructExpr = true;
17977 return Res;
17978 }
17979 bool AllowSkippingFirstCXXConstructExpr = true;
17980 } Transformer(SemaRef, Rec.ReferenceToConsteval,
17982
17983 /// CXXConstructExpr with a single argument are getting skipped by
17984 /// TreeTransform in some situtation because they could be implicit. This
17985 /// can only occur for the top-level CXXConstructExpr because it is used
17986 /// nowhere in the expression being transformed therefore will not be rebuilt.
17987 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17988 /// skipping the first CXXConstructExpr.
17989 if (isa<CXXConstructExpr>(It->getPointer()->IgnoreImplicit()))
17990 Transformer.AllowSkippingFirstCXXConstructExpr = false;
17991
17992 ExprResult Res = Transformer.TransformExpr(It->getPointer()->getSubExpr());
17993 // The result may not be usable in case of previous compilation errors.
17994 // In this case evaluation of the expression may result in crash so just
17995 // don't do anything further with the result.
17996 if (Res.isUsable()) {
17998 It->getPointer()->setSubExpr(Res.get());
17999 }
18000}
18001
18002static void
18005 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18006 Rec.ReferenceToConsteval.size() == 0) ||
18008 return;
18009
18010 /// When we have more than 1 ImmediateInvocationCandidates or previously
18011 /// failed immediate invocations, we need to check for nested
18012 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18013 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18014 /// invocation.
18015 if (Rec.ImmediateInvocationCandidates.size() > 1 ||
18017
18018 /// Prevent sema calls during the tree transform from adding pointers that
18019 /// are already in the sets.
18020 llvm::SaveAndRestore DisableIITracking(
18022
18023 /// Prevent diagnostic during tree transfrom as they are duplicates
18025
18026 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18027 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18028 if (!It->getInt())
18030 } else if (Rec.ImmediateInvocationCandidates.size() == 1 &&
18031 Rec.ReferenceToConsteval.size()) {
18032 struct SimpleRemove : RecursiveASTVisitor<SimpleRemove> {
18033 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
18034 SimpleRemove(llvm::SmallPtrSetImpl<DeclRefExpr *> &S) : DRSet(S) {}
18035 bool VisitDeclRefExpr(DeclRefExpr *E) {
18036 DRSet.erase(E);
18037 return DRSet.size();
18038 }
18039 } Visitor(Rec.ReferenceToConsteval);
18040 Visitor.TraverseStmt(
18041 Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18042 }
18043 for (auto CE : Rec.ImmediateInvocationCandidates)
18044 if (!CE.getInt())
18046 for (auto *DR : Rec.ReferenceToConsteval) {
18047 // If the expression is immediate escalating, it is not an error;
18048 // The outer context itself becomes immediate and further errors,
18049 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18050 if (DR->isImmediateEscalating())
18051 continue;
18052 auto *FD = cast<FunctionDecl>(DR->getDecl());
18053 const NamedDecl *ND = FD;
18054 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND);
18055 MD && (MD->isLambdaStaticInvoker() || isLambdaCallOperator(MD)))
18056 ND = MD->getParent();
18057
18058 // C++23 [expr.const]/p16
18059 // An expression or conversion is immediate-escalating if it is not
18060 // initially in an immediate function context and it is [...] a
18061 // potentially-evaluated id-expression that denotes an immediate function
18062 // that is not a subexpression of an immediate invocation.
18063 bool ImmediateEscalating = false;
18064 bool IsPotentiallyEvaluated =
18065 Rec.Context ==
18067 Rec.Context ==
18069 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18070 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18071
18073 (SemaRef.inTemplateInstantiation() && !ImmediateEscalating)) {
18074 SemaRef.Diag(DR->getBeginLoc(), diag::err_invalid_consteval_take_address)
18075 << ND << isa<CXXRecordDecl>(ND) << FD->isConsteval();
18076 SemaRef.Diag(ND->getLocation(), diag::note_declared_at);
18077 if (auto Context =
18079 SemaRef.Diag(Context->Loc, diag::note_invalid_consteval_initializer)
18080 << Context->Decl;
18081 SemaRef.Diag(Context->Decl->getBeginLoc(), diag::note_declared_at);
18082 }
18083 if (FD->isImmediateEscalating() && !FD->isConsteval())
18085
18086 } else {
18088 }
18089 }
18090}
18091
18094 unsigned NumTypos = Rec.NumTypos;
18095
18096 if (!Rec.Lambdas.empty()) {
18098 if (!getLangOpts().CPlusPlus20 &&
18099 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18100 Rec.isUnevaluated() ||
18102 unsigned D;
18103 if (Rec.isUnevaluated()) {
18104 // C++11 [expr.prim.lambda]p2:
18105 // A lambda-expression shall not appear in an unevaluated operand
18106 // (Clause 5).
18107 D = diag::err_lambda_unevaluated_operand;
18108 } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
18109 // C++1y [expr.const]p2:
18110 // A conditional-expression e is a core constant expression unless the
18111 // evaluation of e, following the rules of the abstract machine, would
18112 // evaluate [...] a lambda-expression.
18113 D = diag::err_lambda_in_constant_expression;
18114 } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
18115 // C++17 [expr.prim.lamda]p2:
18116 // A lambda-expression shall not appear [...] in a template-argument.
18117 D = diag::err_lambda_in_invalid_context;
18118 } else
18119 llvm_unreachable("Couldn't infer lambda error message.");
18120
18121 for (const auto *L : Rec.Lambdas)
18122 Diag(L->getBeginLoc(), D);
18123 }
18124 }
18125
18126 // Append the collected materialized temporaries into previous context before
18127 // exit if the previous also is a lifetime extending context.
18128 auto &PrevRecord = ExprEvalContexts[ExprEvalContexts.size() - 2];
18130 PrevRecord.InLifetimeExtendingContext &&
18131 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18132 PrevRecord.ForRangeLifetimeExtendTemps.append(
18134 }
18135
18137 HandleImmediateInvocations(*this, Rec);
18138
18139 // Warn on any volatile-qualified simple-assignments that are not discarded-
18140 // value expressions nor unevaluated operands (those cases get removed from
18141 // this list by CheckUnusedVolatileAssignment).
18142 for (auto *BO : Rec.VolatileAssignmentLHSs)
18143 Diag(BO->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile)
18144 << BO->getType();
18145
18146 // When are coming out of an unevaluated context, clear out any
18147 // temporaries that we may have created as part of the evaluation of
18148 // the expression in that context: they aren't relevant because they
18149 // will never be constructed.
18150 if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
18152 ExprCleanupObjects.end());
18153 Cleanup = Rec.ParentCleanup;
18156 // Otherwise, merge the contexts together.
18157 } else {
18159 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
18160 Rec.SavedMaybeODRUseExprs.end());
18161 }
18162
18163 // Pop the current expression evaluation context off the stack.
18164 ExprEvalContexts.pop_back();
18165
18166 // The global expression evaluation context record is never popped.
18167 ExprEvalContexts.back().NumTypos += NumTypos;
18168}
18169
18171 ExprCleanupObjects.erase(
18172 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18173 ExprCleanupObjects.end());
18174 Cleanup.reset();
18175 MaybeODRUseExprs.clear();
18176}
18177
18180 if (Result.isInvalid())
18181 return ExprError();
18182 E = Result.get();
18183 if (!E->getType()->isVariablyModifiedType())
18184 return E;
18186}
18187
18188/// Are we in a context that is potentially constant evaluated per C++20
18189/// [expr.const]p12?
18191 /// C++2a [expr.const]p12:
18192 // An expression or conversion is potentially constant evaluated if it is
18193 switch (SemaRef.ExprEvalContexts.back().Context) {
18196
18197 // -- a manifestly constant-evaluated expression,
18201 // -- a potentially-evaluated expression,
18203 // -- an immediate subexpression of a braced-init-list,
18204
18205 // -- [FIXME] an expression of the form & cast-expression that occurs
18206 // within a templated entity
18207 // -- a subexpression of one of the above that is not a subexpression of
18208 // a nested unevaluated operand.
18209 return true;
18210
18213 // Expressions in this context are never evaluated.
18214 return false;
18215 }
18216 llvm_unreachable("Invalid context");
18217}
18218
18219/// Return true if this function has a calling convention that requires mangling
18220/// in the size of the parameter pack.
18222 // These manglings don't do anything on non-Windows or non-x86 platforms, so
18223 // we don't need parameter type sizes.
18224 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
18225 if (!TT.isOSWindows() || !TT.isX86())
18226 return false;
18227
18228 // If this is C++ and this isn't an extern "C" function, parameters do not
18229 // need to be complete. In this case, C++ mangling will apply, which doesn't
18230 // use the size of the parameters.
18231 if (S.getLangOpts().CPlusPlus && !FD->isExternC())
18232 return false;
18233
18234 // Stdcall, fastcall, and vectorcall need this special treatment.
18235 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18236 switch (CC) {
18237 case CC_X86StdCall:
18238 case CC_X86FastCall:
18239 case CC_X86VectorCall:
18240 return true;
18241 default:
18242 break;
18243 }
18244 return false;
18245}
18246
18247/// Require that all of the parameter types of function be complete. Normally,
18248/// parameter types are only required to be complete when a function is called
18249/// or defined, but to mangle functions with certain calling conventions, the
18250/// mangler needs to know the size of the parameter list. In this situation,
18251/// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18252/// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18253/// result in a linker error. Clang doesn't implement this behavior, and instead
18254/// attempts to error at compile time.
18256 SourceLocation Loc) {
18257 class ParamIncompleteTypeDiagnoser : public Sema::TypeDiagnoser {
18258 FunctionDecl *FD;
18259 ParmVarDecl *Param;
18260
18261 public:
18262 ParamIncompleteTypeDiagnoser(FunctionDecl *FD, ParmVarDecl *Param)
18263 : FD(FD), Param(Param) {}
18264
18265 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
18266 CallingConv CC = FD->getType()->castAs<FunctionType>()->getCallConv();
18267 StringRef CCName;
18268 switch (CC) {
18269 case CC_X86StdCall:
18270 CCName = "stdcall";
18271 break;
18272 case CC_X86FastCall:
18273 CCName = "fastcall";
18274 break;
18275 case CC_X86VectorCall:
18276 CCName = "vectorcall";
18277 break;
18278 default:
18279 llvm_unreachable("CC does not need mangling");
18280 }
18281
18282 S.Diag(Loc, diag::err_cconv_incomplete_param_type)
18283 << Param->getDeclName() << FD->getDeclName() << CCName;
18284 }
18285 };
18286
18287 for (ParmVarDecl *Param : FD->parameters()) {
18288 ParamIncompleteTypeDiagnoser Diagnoser(FD, Param);
18289 S.RequireCompleteType(Loc, Param->getType(), Diagnoser);
18290 }
18291}
18292
18293namespace {
18294enum class OdrUseContext {
18295 /// Declarations in this context are not odr-used.
18296 None,
18297 /// Declarations in this context are formally odr-used, but this is a
18298 /// dependent context.
18299 Dependent,
18300 /// Declarations in this context are odr-used but not actually used (yet).
18301 FormallyOdrUsed,
18302 /// Declarations in this context are used.
18303 Used
18304};
18305}
18306
18307/// Are we within a context in which references to resolved functions or to
18308/// variables result in odr-use?
18309static OdrUseContext isOdrUseContext(Sema &SemaRef) {
18310 OdrUseContext Result;
18311
18312 switch (SemaRef.ExprEvalContexts.back().Context) {
18316 return OdrUseContext::None;
18317
18321 Result = OdrUseContext::Used;
18322 break;
18323
18325 Result = OdrUseContext::FormallyOdrUsed;
18326 break;
18327
18329 // A default argument formally results in odr-use, but doesn't actually
18330 // result in a use in any real sense until it itself is used.
18331 Result = OdrUseContext::FormallyOdrUsed;
18332 break;
18333 }
18334
18336 return OdrUseContext::Dependent;
18337
18338 return Result;
18339}
18340
18342 if (!Func->isConstexpr())
18343 return false;
18344
18345 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18346 return true;
18347 auto *CCD = dyn_cast<CXXConstructorDecl>(Func);
18348 return CCD && CCD->getInheritedConstructor();
18349}
18350
18351/// Mark a function referenced, and check whether it is odr-used
18352/// (C++ [basic.def.odr]p2, C99 6.9p3)
18354 bool MightBeOdrUse) {
18355 assert(Func && "No function?");
18356
18357 Func->setReferenced();
18358
18359 // Recursive functions aren't really used until they're used from some other
18360 // context.
18361 bool IsRecursiveCall = CurContext == Func;
18362
18363 // C++11 [basic.def.odr]p3:
18364 // A function whose name appears as a potentially-evaluated expression is
18365 // odr-used if it is the unique lookup result or the selected member of a
18366 // set of overloaded functions [...].
18367 //
18368 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18369 // can just check that here.
18370 OdrUseContext OdrUse =
18371 MightBeOdrUse ? isOdrUseContext(*this) : OdrUseContext::None;
18372 if (IsRecursiveCall && OdrUse == OdrUseContext::Used)
18373 OdrUse = OdrUseContext::FormallyOdrUsed;
18374
18375 // Trivial default constructors and destructors are never actually used.
18376 // FIXME: What about other special members?
18377 if (Func->isTrivial() && !Func->hasAttr<DLLExportAttr>() &&
18378 OdrUse == OdrUseContext::Used) {
18379 if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Func))
18380 if (Constructor->isDefaultConstructor())
18381 OdrUse = OdrUseContext::FormallyOdrUsed;
18382 if (isa<CXXDestructorDecl>(Func))
18383 OdrUse = OdrUseContext::FormallyOdrUsed;
18384 }
18385
18386 // C++20 [expr.const]p12:
18387 // A function [...] is needed for constant evaluation if it is [...] a
18388 // constexpr function that is named by an expression that is potentially
18389 // constant evaluated
18390 bool NeededForConstantEvaluation =
18393
18394 // Determine whether we require a function definition to exist, per
18395 // C++11 [temp.inst]p3:
18396 // Unless a function template specialization has been explicitly
18397 // instantiated or explicitly specialized, the function template
18398 // specialization is implicitly instantiated when the specialization is
18399 // referenced in a context that requires a function definition to exist.
18400 // C++20 [temp.inst]p7:
18401 // The existence of a definition of a [...] function is considered to
18402 // affect the semantics of the program if the [...] function is needed for
18403 // constant evaluation by an expression
18404 // C++20 [basic.def.odr]p10:
18405 // Every program shall contain exactly one definition of every non-inline
18406 // function or variable that is odr-used in that program outside of a
18407 // discarded statement
18408 // C++20 [special]p1:
18409 // The implementation will implicitly define [defaulted special members]
18410 // if they are odr-used or needed for constant evaluation.
18411 //
18412 // Note that we skip the implicit instantiation of templates that are only
18413 // used in unused default arguments or by recursive calls to themselves.
18414 // This is formally non-conforming, but seems reasonable in practice.
18415 bool NeedDefinition =
18416 !IsRecursiveCall &&
18417 (OdrUse == OdrUseContext::Used ||
18418 (NeededForConstantEvaluation && !Func->isPureVirtual()));
18419
18420 // C++14 [temp.expl.spec]p6:
18421 // If a template [...] is explicitly specialized then that specialization
18422 // shall be declared before the first use of that specialization that would
18423 // cause an implicit instantiation to take place, in every translation unit
18424 // in which such a use occurs
18425 if (NeedDefinition &&
18426 (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
18427 Func->getMemberSpecializationInfo()))
18429
18430 if (getLangOpts().CUDA)
18431 CUDA().CheckCall(Loc, Func);
18432
18433 // If we need a definition, try to create one.
18434 if (NeedDefinition && !Func->getBody()) {
18436 if (CXXConstructorDecl *Constructor =
18437 dyn_cast<CXXConstructorDecl>(Func)) {
18438 Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
18439 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
18440 if (Constructor->isDefaultConstructor()) {
18441 if (Constructor->isTrivial() &&
18442 !Constructor->hasAttr<DLLExportAttr>())
18443 return;
18444 DefineImplicitDefaultConstructor(Loc, Constructor);
18445 } else if (Constructor->isCopyConstructor()) {
18446 DefineImplicitCopyConstructor(Loc, Constructor);
18447 } else if (Constructor->isMoveConstructor()) {
18448 DefineImplicitMoveConstructor(Loc, Constructor);
18449 }
18450 } else if (Constructor->getInheritedConstructor()) {
18451 DefineInheritingConstructor(Loc, Constructor);
18452 }
18453 } else if (CXXDestructorDecl *Destructor =
18454 dyn_cast<CXXDestructorDecl>(Func)) {
18455 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18456 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18457 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18458 return;
18460 }
18461 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18462 MarkVTableUsed(Loc, Destructor->getParent());
18463 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
18464 if (MethodDecl->isOverloadedOperator() &&
18465 MethodDecl->getOverloadedOperator() == OO_Equal) {
18466 MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
18467 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
18468 if (MethodDecl->isCopyAssignmentOperator())
18469 DefineImplicitCopyAssignment(Loc, MethodDecl);
18470 else if (MethodDecl->isMoveAssignmentOperator())
18471 DefineImplicitMoveAssignment(Loc, MethodDecl);
18472 }
18473 } else if (isa<CXXConversionDecl>(MethodDecl) &&
18474 MethodDecl->getParent()->isLambda()) {
18475 CXXConversionDecl *Conversion =
18476 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18477 if (Conversion->isLambdaToBlockPointerConversion())
18479 else
18481 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18482 MarkVTableUsed(Loc, MethodDecl->getParent());
18483 }
18484
18485 if (Func->isDefaulted() && !Func->isDeleted()) {
18489 }
18490
18491 // Implicit instantiation of function templates and member functions of
18492 // class templates.
18493 if (Func->isImplicitlyInstantiable()) {
18495 Func->getTemplateSpecializationKindForInstantiation();
18496 SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
18497 bool FirstInstantiation = PointOfInstantiation.isInvalid();
18498 if (FirstInstantiation) {
18499 PointOfInstantiation = Loc;
18500 if (auto *MSI = Func->getMemberSpecializationInfo())
18501 MSI->setPointOfInstantiation(Loc);
18502 // FIXME: Notify listener.
18503 else
18504 Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
18505 } else if (TSK != TSK_ImplicitInstantiation) {
18506 // Use the point of use as the point of instantiation, instead of the
18507 // point of explicit instantiation (which we track as the actual point
18508 // of instantiation). This gives better backtraces in diagnostics.
18509 PointOfInstantiation = Loc;
18510 }
18511
18512 if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
18513 Func->isConstexpr()) {
18514 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
18515 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
18516 CodeSynthesisContexts.size())
18518 std::make_pair(Func, PointOfInstantiation));
18519 else if (Func->isConstexpr())
18520 // Do not defer instantiations of constexpr functions, to avoid the
18521 // expression evaluator needing to call back into Sema if it sees a
18522 // call to such a function.
18523 InstantiateFunctionDefinition(PointOfInstantiation, Func);
18524 else {
18525 Func->setInstantiationIsPending(true);
18526 PendingInstantiations.push_back(
18527 std::make_pair(Func, PointOfInstantiation));
18528 // Notify the consumer that a function was implicitly instantiated.
18530 }
18531 }
18532 } else {
18533 // Walk redefinitions, as some of them may be instantiable.
18534 for (auto *i : Func->redecls()) {
18535 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
18536 MarkFunctionReferenced(Loc, i, MightBeOdrUse);
18537 }
18538 }
18539 });
18540 }
18541
18542 // If a constructor was defined in the context of a default parameter
18543 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18544 // context), its initializers may not be referenced yet.
18545 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
18547 *this,
18548 Constructor->isImmediateFunction()
18551 Constructor);
18552 for (CXXCtorInitializer *Init : Constructor->inits()) {
18553 if (Init->isInClassMemberInitializer())
18554 runWithSufficientStackSpace(Init->getSourceLocation(), [&]() {
18555 MarkDeclarationsReferencedInExpr(Init->getInit());
18556 });
18557 }
18558 }
18559
18560 // C++14 [except.spec]p17:
18561 // An exception-specification is considered to be needed when:
18562 // - the function is odr-used or, if it appears in an unevaluated operand,
18563 // would be odr-used if the expression were potentially-evaluated;
18564 //
18565 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18566 // function is a pure virtual function we're calling, and in that case the
18567 // function was selected by overload resolution and we need to resolve its
18568 // exception specification for a different reason.
18569 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
18571 ResolveExceptionSpec(Loc, FPT);
18572
18573 // A callee could be called by a host function then by a device function.
18574 // If we only try recording once, we will miss recording the use on device
18575 // side. Therefore keep trying until it is recorded.
18576 if (LangOpts.OffloadImplicitHostDeviceTemplates && LangOpts.CUDAIsDevice &&
18579
18580 // If this is the first "real" use, act on that.
18581 if (OdrUse == OdrUseContext::Used && !Func->isUsed(/*CheckUsedAttr=*/false)) {
18582 // Keep track of used but undefined functions.
18583 if (!Func->isDefined()) {
18584 if (mightHaveNonExternalLinkage(Func))
18585 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18586 else if (Func->getMostRecentDecl()->isInlined() &&
18587 !LangOpts.GNUInline &&
18588 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18589 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18591 UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
18592 }
18593
18594 // Some x86 Windows calling conventions mangle the size of the parameter
18595 // pack into the name. Computing the size of the parameters requires the
18596 // parameter types to be complete. Check that now.
18599
18600 // In the MS C++ ABI, the compiler emits destructor variants where they are
18601 // used. If the destructor is used here but defined elsewhere, mark the
18602 // virtual base destructors referenced. If those virtual base destructors
18603 // are inline, this will ensure they are defined when emitting the complete
18604 // destructor variant. This checking may be redundant if the destructor is
18605 // provided later in this TU.
18607 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Func)) {
18608 CXXRecordDecl *Parent = Dtor->getParent();
18609 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18611 }
18612 }
18613
18614 Func->markUsed(Context);
18615 }
18616}
18617
18618/// Directly mark a variable odr-used. Given a choice, prefer to use
18619/// MarkVariableReferenced since it does additional checks and then
18620/// calls MarkVarDeclODRUsed.
18621/// If the variable must be captured:
18622/// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18623/// - else capture it in the DeclContext that maps to the
18624/// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18625static void
18627 const unsigned *const FunctionScopeIndexToStopAt = nullptr) {
18628 // Keep track of used but undefined variables.
18629 // FIXME: We shouldn't suppress this warning for static data members.
18630 VarDecl *Var = V->getPotentiallyDecomposedVarDecl();
18631 assert(Var && "expected a capturable variable");
18632
18634 (!Var->isExternallyVisible() || Var->isInline() ||
18636 !(Var->isStaticDataMember() && Var->hasInit())) {
18638 if (old.isInvalid())
18639 old = Loc;
18640 }
18641 QualType CaptureType, DeclRefType;
18642 if (SemaRef.LangOpts.OpenMP)
18645 /*EllipsisLoc*/ SourceLocation(),
18646 /*BuildAndDiagnose*/ true, CaptureType,
18647 DeclRefType, FunctionScopeIndexToStopAt);
18648
18649 if (SemaRef.LangOpts.CUDA && Var->hasGlobalStorage()) {
18650 auto *FD = dyn_cast_or_null<FunctionDecl>(SemaRef.CurContext);
18651 auto VarTarget = SemaRef.CUDA().IdentifyTarget(Var);
18652 auto UserTarget = SemaRef.CUDA().IdentifyTarget(FD);
18653 if (VarTarget == SemaCUDA::CVT_Host &&
18654 (UserTarget == CUDAFunctionTarget::Device ||
18655 UserTarget == CUDAFunctionTarget::HostDevice ||
18656 UserTarget == CUDAFunctionTarget::Global)) {
18657 // Diagnose ODR-use of host global variables in device functions.
18658 // Reference of device global variables in host functions is allowed
18659 // through shadow variables therefore it is not diagnosed.
18660 if (SemaRef.LangOpts.CUDAIsDevice && !SemaRef.LangOpts.HIPStdPar) {
18661 SemaRef.targetDiag(Loc, diag::err_ref_bad_target)
18662 << /*host*/ 2 << /*variable*/ 1 << Var
18663 << llvm::to_underlying(UserTarget);
18665 Var->getType().isConstQualified()
18666 ? diag::note_cuda_const_var_unpromoted
18667 : diag::note_cuda_host_var);
18668 }
18669 } else if (VarTarget == SemaCUDA::CVT_Device &&
18670 !Var->hasAttr<CUDASharedAttr>() &&
18671 (UserTarget == CUDAFunctionTarget::Host ||
18672 UserTarget == CUDAFunctionTarget::HostDevice)) {
18673 // Record a CUDA/HIP device side variable if it is ODR-used
18674 // by host code. This is done conservatively, when the variable is
18675 // referenced in any of the following contexts:
18676 // - a non-function context
18677 // - a host function
18678 // - a host device function
18679 // This makes the ODR-use of the device side variable by host code to
18680 // be visible in the device compilation for the compiler to be able to
18681 // emit template variables instantiated by host code only and to
18682 // externalize the static device side variable ODR-used by host code.
18683 if (!Var->hasExternalStorage())
18685 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18686 (!FD || (!FD->getDescribedFunctionTemplate() &&
18690 }
18691 }
18692
18693 V->markUsed(SemaRef.Context);
18694}
18695
18697 SourceLocation Loc,
18698 unsigned CapturingScopeIndex) {
18699 MarkVarDeclODRUsed(Capture, Loc, *this, &CapturingScopeIndex);
18700}
18701
18703 ValueDecl *var) {
18704 DeclContext *VarDC = var->getDeclContext();
18705
18706 // If the parameter still belongs to the translation unit, then
18707 // we're actually just using one parameter in the declaration of
18708 // the next.
18709 if (isa<ParmVarDecl>(var) &&
18710 isa<TranslationUnitDecl>(VarDC))
18711 return;
18712
18713 // For C code, don't diagnose about capture if we're not actually in code
18714 // right now; it's impossible to write a non-constant expression outside of
18715 // function context, so we'll get other (more useful) diagnostics later.
18716 //
18717 // For C++, things get a bit more nasty... it would be nice to suppress this
18718 // diagnostic for certain cases like using a local variable in an array bound
18719 // for a member of a local class, but the correct predicate is not obvious.
18720 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
18721 return;
18722
18723 unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
18724 unsigned ContextKind = 3; // unknown
18725 if (isa<CXXMethodDecl>(VarDC) &&
18726 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
18727 ContextKind = 2;
18728 } else if (isa<FunctionDecl>(VarDC)) {
18729 ContextKind = 0;
18730 } else if (isa<BlockDecl>(VarDC)) {
18731 ContextKind = 1;
18732 }
18733
18734 S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
18735 << var << ValueKind << ContextKind << VarDC;
18736 S.Diag(var->getLocation(), diag::note_entity_declared_at)
18737 << var;
18738
18739 // FIXME: Add additional diagnostic info about class etc. which prevents
18740 // capture.
18741}
18742
18744 ValueDecl *Var,
18745 bool &SubCapturesAreNested,
18746 QualType &CaptureType,
18747 QualType &DeclRefType) {
18748 // Check whether we've already captured it.
18749 if (CSI->CaptureMap.count(Var)) {
18750 // If we found a capture, any subcaptures are nested.
18751 SubCapturesAreNested = true;
18752
18753 // Retrieve the capture type for this variable.
18754 CaptureType = CSI->getCapture(Var).getCaptureType();
18755
18756 // Compute the type of an expression that refers to this variable.
18757 DeclRefType = CaptureType.getNonReferenceType();
18758
18759 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18760 // are mutable in the sense that user can change their value - they are
18761 // private instances of the captured declarations.
18762 const Capture &Cap = CSI->getCapture(Var);
18763 if (Cap.isCopyCapture() &&
18764 !(isa<LambdaScopeInfo>(CSI) &&
18765 !cast<LambdaScopeInfo>(CSI)->lambdaCaptureShouldBeConst()) &&
18766 !(isa<CapturedRegionScopeInfo>(CSI) &&
18767 cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
18768 DeclRefType.addConst();
18769 return true;
18770 }
18771 return false;
18772}
18773
18774// Only block literals, captured statements, and lambda expressions can
18775// capture; other scopes don't work.
18777 ValueDecl *Var,
18778 SourceLocation Loc,
18779 const bool Diagnose,
18780 Sema &S) {
18781 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
18783
18784 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18785 if (Underlying) {
18786 if (Underlying->hasLocalStorage() && Diagnose)
18788 }
18789 return nullptr;
18790}
18791
18792// Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18793// certain types of variables (unnamed, variably modified types etc.)
18794// so check for eligibility.
18796 SourceLocation Loc, const bool Diagnose,
18797 Sema &S) {
18798
18799 assert((isa<VarDecl, BindingDecl>(Var)) &&
18800 "Only variables and structured bindings can be captured");
18801
18802 bool IsBlock = isa<BlockScopeInfo>(CSI);
18803 bool IsLambda = isa<LambdaScopeInfo>(CSI);
18804
18805 // Lambdas are not allowed to capture unnamed variables
18806 // (e.g. anonymous unions).
18807 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18808 // assuming that's the intent.
18809 if (IsLambda && !Var->getDeclName()) {
18810 if (Diagnose) {
18811 S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
18812 S.Diag(Var->getLocation(), diag::note_declared_at);
18813 }
18814 return false;
18815 }
18816
18817 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18818 if (Var->getType()->isVariablyModifiedType() && IsBlock) {
18819 if (Diagnose) {
18820 S.Diag(Loc, diag::err_ref_vm_type);
18821 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18822 }
18823 return false;
18824 }
18825 // Prohibit structs with flexible array members too.
18826 // We cannot capture what is in the tail end of the struct.
18827 if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
18828 if (VTTy->getDecl()->hasFlexibleArrayMember()) {
18829 if (Diagnose) {
18830 if (IsBlock)
18831 S.Diag(Loc, diag::err_ref_flexarray_type);
18832 else
18833 S.Diag(Loc, diag::err_lambda_capture_flexarray_type) << Var;
18834 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18835 }
18836 return false;
18837 }
18838 }
18839 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18840 // Lambdas and captured statements are not allowed to capture __block
18841 // variables; they don't support the expected semantics.
18842 if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
18843 if (Diagnose) {
18844 S.Diag(Loc, diag::err_capture_block_variable) << Var << !IsLambda;
18845 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18846 }
18847 return false;
18848 }
18849 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18850 if (S.getLangOpts().OpenCL && IsBlock &&
18851 Var->getType()->isBlockPointerType()) {
18852 if (Diagnose)
18853 S.Diag(Loc, diag::err_opencl_block_ref_block);
18854 return false;
18855 }
18856
18857 if (isa<BindingDecl>(Var)) {
18858 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18859 if (Diagnose)
18861 return false;
18862 } else if (Diagnose && S.getLangOpts().CPlusPlus) {
18863 S.Diag(Loc, S.LangOpts.CPlusPlus20
18864 ? diag::warn_cxx17_compat_capture_binding
18865 : diag::ext_capture_binding)
18866 << Var;
18867 S.Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
18868 }
18869 }
18870
18871 return true;
18872}
18873
18874// Returns true if the capture by block was successful.
18876 SourceLocation Loc, const bool BuildAndDiagnose,
18877 QualType &CaptureType, QualType &DeclRefType,
18878 const bool Nested, Sema &S, bool Invalid) {
18879 bool ByRef = false;
18880
18881 // Blocks are not allowed to capture arrays, excepting OpenCL.
18882 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18883 // (decayed to pointers).
18884 if (!Invalid && !S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
18885 if (BuildAndDiagnose) {
18886 S.Diag(Loc, diag::err_ref_array_type);
18887 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18888 Invalid = true;
18889 } else {
18890 return false;
18891 }
18892 }
18893
18894 // Forbid the block-capture of autoreleasing variables.
18895 if (!Invalid &&
18897 if (BuildAndDiagnose) {
18898 S.Diag(Loc, diag::err_arc_autoreleasing_capture)
18899 << /*block*/ 0;
18900 S.Diag(Var->getLocation(), diag::note_previous_decl) << Var;
18901 Invalid = true;
18902 } else {
18903 return false;
18904 }
18905 }
18906
18907 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18908 if (const auto *PT = CaptureType->getAs<PointerType>()) {
18909 QualType PointeeTy = PT->getPointeeType();
18910
18911 if (!Invalid && PointeeTy->getAs<ObjCObjectPointerType>() &&
18913 !S.Context.hasDirectOwnershipQualifier(PointeeTy)) {
18914 if (BuildAndDiagnose) {
18915 SourceLocation VarLoc = Var->getLocation();
18916 S.Diag(Loc, diag::warn_block_capture_autoreleasing);
18917 S.Diag(VarLoc, diag::note_declare_parameter_strong);
18918 }
18919 }
18920 }
18921
18922 const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
18923 if (HasBlocksAttr || CaptureType->isReferenceType() ||
18924 (S.getLangOpts().OpenMP && S.OpenMP().isOpenMPCapturedDecl(Var))) {
18925 // Block capture by reference does not change the capture or
18926 // declaration reference types.
18927 ByRef = true;
18928 } else {
18929 // Block capture by copy introduces 'const'.
18930 CaptureType = CaptureType.getNonReferenceType().withConst();
18931 DeclRefType = CaptureType;
18932 }
18933
18934 // Actually capture the variable.
18935 if (BuildAndDiagnose)
18936 BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, SourceLocation(),
18937 CaptureType, Invalid);
18938
18939 return !Invalid;
18940}
18941
18942/// Capture the given variable in the captured region.
18945 const bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType,
18946 const bool RefersToCapturedVariable, Sema::TryCaptureKind Kind,
18947 bool IsTopScope, Sema &S, bool Invalid) {
18948 // By default, capture variables by reference.
18949 bool ByRef = true;
18950 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18951 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18952 } else if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
18953 // Using an LValue reference type is consistent with Lambdas (see below).
18954 if (S.OpenMP().isOpenMPCapturedDecl(Var)) {
18955 bool HasConst = DeclRefType.isConstQualified();
18956 DeclRefType = DeclRefType.getUnqualifiedType();
18957 // Don't lose diagnostics about assignments to const.
18958 if (HasConst)
18959 DeclRefType.addConst();
18960 }
18961 // Do not capture firstprivates in tasks.
18962 if (S.OpenMP().isOpenMPPrivateDecl(Var, RSI->OpenMPLevel,
18963 RSI->OpenMPCaptureLevel) != OMPC_unknown)
18964 return true;
18965 ByRef = S.OpenMP().isOpenMPCapturedByRef(Var, RSI->OpenMPLevel,
18966 RSI->OpenMPCaptureLevel);
18967 }
18968
18969 if (ByRef)
18970 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
18971 else
18972 CaptureType = DeclRefType;
18973
18974 // Actually capture the variable.
18975 if (BuildAndDiagnose)
18976 RSI->addCapture(Var, /*isBlock*/ false, ByRef, RefersToCapturedVariable,
18977 Loc, SourceLocation(), CaptureType, Invalid);
18978
18979 return !Invalid;
18980}
18981
18982/// Capture the given variable in the lambda.
18984 SourceLocation Loc, const bool BuildAndDiagnose,
18985 QualType &CaptureType, QualType &DeclRefType,
18986 const bool RefersToCapturedVariable,
18987 const Sema::TryCaptureKind Kind,
18988 SourceLocation EllipsisLoc, const bool IsTopScope,
18989 Sema &S, bool Invalid) {
18990 // Determine whether we are capturing by reference or by value.
18991 bool ByRef = false;
18992 if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
18993 ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
18994 } else {
18995 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
18996 }
18997
18998 if (BuildAndDiagnose && S.Context.getTargetInfo().getTriple().isWasm() &&
19000 S.Diag(Loc, diag::err_wasm_ca_reference) << 0;
19001 Invalid = true;
19002 }
19003
19004 // Compute the type of the field that will capture this variable.
19005 if (ByRef) {
19006 // C++11 [expr.prim.lambda]p15:
19007 // An entity is captured by reference if it is implicitly or
19008 // explicitly captured but not captured by copy. It is
19009 // unspecified whether additional unnamed non-static data
19010 // members are declared in the closure type for entities
19011 // captured by reference.
19012 //
19013 // FIXME: It is not clear whether we want to build an lvalue reference
19014 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19015 // to do the former, while EDG does the latter. Core issue 1249 will
19016 // clarify, but for now we follow GCC because it's a more permissive and
19017 // easily defensible position.
19018 CaptureType = S.Context.getLValueReferenceType(DeclRefType);
19019 } else {
19020 // C++11 [expr.prim.lambda]p14:
19021 // For each entity captured by copy, an unnamed non-static
19022 // data member is declared in the closure type. The
19023 // declaration order of these members is unspecified. The type
19024 // of such a data member is the type of the corresponding
19025 // captured entity if the entity is not a reference to an
19026 // object, or the referenced type otherwise. [Note: If the
19027 // captured entity is a reference to a function, the
19028 // corresponding data member is also a reference to a
19029 // function. - end note ]
19030 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
19031 if (!RefType->getPointeeType()->isFunctionType())
19032 CaptureType = RefType->getPointeeType();
19033 }
19034
19035 // Forbid the lambda copy-capture of autoreleasing variables.
19036 if (!Invalid &&
19038 if (BuildAndDiagnose) {
19039 S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
19040 S.Diag(Var->getLocation(), diag::note_previous_decl)
19041 << Var->getDeclName();
19042 Invalid = true;
19043 } else {
19044 return false;
19045 }
19046 }
19047
19048 // Make sure that by-copy captures are of a complete and non-abstract type.
19049 if (!Invalid && BuildAndDiagnose) {
19050 if (!CaptureType->isDependentType() &&
19052 Loc, CaptureType,
19053 diag::err_capture_of_incomplete_or_sizeless_type,
19054 Var->getDeclName()))
19055 Invalid = true;
19056 else if (S.RequireNonAbstractType(Loc, CaptureType,
19057 diag::err_capture_of_abstract_type))
19058 Invalid = true;
19059 }
19060 }
19061
19062 // Compute the type of a reference to this captured variable.
19063 if (ByRef)
19064 DeclRefType = CaptureType.getNonReferenceType();
19065 else {
19066 // C++ [expr.prim.lambda]p5:
19067 // The closure type for a lambda-expression has a public inline
19068 // function call operator [...]. This function call operator is
19069 // declared const (9.3.1) if and only if the lambda-expression's
19070 // parameter-declaration-clause is not followed by mutable.
19071 DeclRefType = CaptureType.getNonReferenceType();
19072 bool Const = LSI->lambdaCaptureShouldBeConst();
19073 if (Const && !CaptureType->isReferenceType())
19074 DeclRefType.addConst();
19075 }
19076
19077 // Add the capture.
19078 if (BuildAndDiagnose)
19079 LSI->addCapture(Var, /*isBlock=*/false, ByRef, RefersToCapturedVariable,
19080 Loc, EllipsisLoc, CaptureType, Invalid);
19081
19082 return !Invalid;
19083}
19084
19086 const ASTContext &Context) {
19087 // Offer a Copy fix even if the type is dependent.
19088 if (Var->getType()->isDependentType())
19089 return true;
19091 if (T.isTriviallyCopyableType(Context))
19092 return true;
19093 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
19094
19095 if (!(RD = RD->getDefinition()))
19096 return false;
19097 if (RD->hasSimpleCopyConstructor())
19098 return true;
19099 if (RD->hasUserDeclaredCopyConstructor())
19100 for (CXXConstructorDecl *Ctor : RD->ctors())
19101 if (Ctor->isCopyConstructor())
19102 return !Ctor->isDeleted();
19103 }
19104 return false;
19105}
19106
19107/// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19108/// default capture. Fixes may be omitted if they aren't allowed by the
19109/// standard, for example we can't emit a default copy capture fix-it if we
19110/// already explicitly copy capture capture another variable.
19112 ValueDecl *Var) {
19114 // Don't offer Capture by copy of default capture by copy fixes if Var is
19115 // known not to be copy constructible.
19116 bool ShouldOfferCopyFix = canCaptureVariableByCopy(Var, Sema.getASTContext());
19117
19118 SmallString<32> FixBuffer;
19119 StringRef Separator = LSI->NumExplicitCaptures > 0 ? ", " : "";
19120 if (Var->getDeclName().isIdentifier() && !Var->getName().empty()) {
19121 SourceLocation VarInsertLoc = LSI->IntroducerRange.getEnd();
19122 if (ShouldOfferCopyFix) {
19123 // Offer fixes to insert an explicit capture for the variable.
19124 // [] -> [VarName]
19125 // [OtherCapture] -> [OtherCapture, VarName]
19126 FixBuffer.assign({Separator, Var->getName()});
19127 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19128 << Var << /*value*/ 0
19129 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19130 }
19131 // As above but capture by reference.
19132 FixBuffer.assign({Separator, "&", Var->getName()});
19133 Sema.Diag(VarInsertLoc, diag::note_lambda_variable_capture_fixit)
19134 << Var << /*reference*/ 1
19135 << FixItHint::CreateInsertion(VarInsertLoc, FixBuffer);
19136 }
19137
19138 // Only try to offer default capture if there are no captures excluding this
19139 // and init captures.
19140 // [this]: OK.
19141 // [X = Y]: OK.
19142 // [&A, &B]: Don't offer.
19143 // [A, B]: Don't offer.
19144 if (llvm::any_of(LSI->Captures, [](Capture &C) {
19145 return !C.isThisCapture() && !C.isInitCapture();
19146 }))
19147 return;
19148
19149 // The default capture specifiers, '=' or '&', must appear first in the
19150 // capture body.
19151 SourceLocation DefaultInsertLoc =
19153
19154 if (ShouldOfferCopyFix) {
19155 bool CanDefaultCopyCapture = true;
19156 // [=, *this] OK since c++17
19157 // [=, this] OK since c++20
19158 if (LSI->isCXXThisCaptured() && !Sema.getLangOpts().CPlusPlus20)
19159 CanDefaultCopyCapture = Sema.getLangOpts().CPlusPlus17
19161 : false;
19162 // We can't use default capture by copy if any captures already specified
19163 // capture by copy.
19164 if (CanDefaultCopyCapture && llvm::none_of(LSI->Captures, [](Capture &C) {
19165 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19166 })) {
19167 FixBuffer.assign({"=", Separator});
19168 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19169 << /*value*/ 0
19170 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19171 }
19172 }
19173
19174 // We can't use default capture by reference if any captures already specified
19175 // capture by reference.
19176 if (llvm::none_of(LSI->Captures, [](Capture &C) {
19177 return !C.isInitCapture() && C.isReferenceCapture() &&
19178 !C.isThisCapture();
19179 })) {
19180 FixBuffer.assign({"&", Separator});
19181 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19182 << /*reference*/ 1
19183 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19184 }
19185}
19186
19188 ValueDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
19189 SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
19190 QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
19191 // An init-capture is notionally from the context surrounding its
19192 // declaration, but its parent DC is the lambda class.
19193 DeclContext *VarDC = Var->getDeclContext();
19194 DeclContext *DC = CurContext;
19195
19196 // tryCaptureVariable is called every time a DeclRef is formed,
19197 // it can therefore have non-negigible impact on performances.
19198 // For local variables and when there is no capturing scope,
19199 // we can bailout early.
19200 if (CapturingFunctionScopes == 0 && (!BuildAndDiagnose || VarDC == DC))
19201 return true;
19202
19203 const auto *VD = dyn_cast<VarDecl>(Var);
19204 if (VD) {
19205 if (VD->isInitCapture())
19206 VarDC = VarDC->getParent();
19207 } else {
19209 }
19210 assert(VD && "Cannot capture a null variable");
19211
19212 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
19213 ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
19214 // We need to sync up the Declaration Context with the
19215 // FunctionScopeIndexToStopAt
19216 if (FunctionScopeIndexToStopAt) {
19217 unsigned FSIndex = FunctionScopes.size() - 1;
19218 while (FSIndex != MaxFunctionScopesIndex) {
19220 --FSIndex;
19221 }
19222 }
19223
19224 // Capture global variables if it is required to use private copy of this
19225 // variable.
19226 bool IsGlobal = !VD->hasLocalStorage();
19227 if (IsGlobal && !(LangOpts.OpenMP &&
19228 OpenMP().isOpenMPCapturedDecl(Var, /*CheckScopeInfo=*/true,
19229 MaxFunctionScopesIndex)))
19230 return true;
19231
19232 if (isa<VarDecl>(Var))
19233 Var = cast<VarDecl>(Var->getCanonicalDecl());
19234
19235 // Walk up the stack to determine whether we can capture the variable,
19236 // performing the "simple" checks that don't depend on type. We stop when
19237 // we've either hit the declared scope of the variable or find an existing
19238 // capture of that variable. We start from the innermost capturing-entity
19239 // (the DC) and ensure that all intervening capturing-entities
19240 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19241 // declcontext can either capture the variable or have already captured
19242 // the variable.
19243 CaptureType = Var->getType();
19244 DeclRefType = CaptureType.getNonReferenceType();
19245 bool Nested = false;
19246 bool Explicit = (Kind != TryCapture_Implicit);
19247 unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
19248 do {
19249
19250 LambdaScopeInfo *LSI = nullptr;
19251 if (!FunctionScopes.empty())
19252 LSI = dyn_cast_or_null<LambdaScopeInfo>(
19253 FunctionScopes[FunctionScopesIndex]);
19254
19255 bool IsInScopeDeclarationContext =
19256 !LSI || LSI->AfterParameterList || CurContext == LSI->CallOperator;
19257
19258 if (LSI && !LSI->AfterParameterList) {
19259 // This allows capturing parameters from a default value which does not
19260 // seems correct
19261 if (isa<ParmVarDecl>(Var) && !Var->getDeclContext()->isFunctionOrMethod())
19262 return true;
19263 }
19264 // If the variable is declared in the current context, there is no need to
19265 // capture it.
19266 if (IsInScopeDeclarationContext &&
19267 FunctionScopesIndex == MaxFunctionScopesIndex && VarDC == DC)
19268 return true;
19269
19270 // Only block literals, captured statements, and lambda expressions can
19271 // capture; other scopes don't work.
19272 DeclContext *ParentDC =
19273 !IsInScopeDeclarationContext
19274 ? DC->getParent()
19275 : getParentOfCapturingContextOrNull(DC, Var, ExprLoc,
19276 BuildAndDiagnose, *this);
19277 // We need to check for the parent *first* because, if we *have*
19278 // private-captured a global variable, we need to recursively capture it in
19279 // intermediate blocks, lambdas, etc.
19280 if (!ParentDC) {
19281 if (IsGlobal) {
19282 FunctionScopesIndex = MaxFunctionScopesIndex - 1;
19283 break;
19284 }
19285 return true;
19286 }
19287
19288 FunctionScopeInfo *FSI = FunctionScopes[FunctionScopesIndex];
19289 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
19290
19291 // Check whether we've already captured it.
19292 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
19293 DeclRefType)) {
19294 CSI->getCapture(Var).markUsed(BuildAndDiagnose);
19295 break;
19296 }
19297
19298 // When evaluating some attributes (like enable_if) we might refer to a
19299 // function parameter appertaining to the same declaration as that
19300 // attribute.
19301 if (const auto *Parm = dyn_cast<ParmVarDecl>(Var);
19302 Parm && Parm->getDeclContext() == DC)
19303 return true;
19304
19305 // If we are instantiating a generic lambda call operator body,
19306 // we do not want to capture new variables. What was captured
19307 // during either a lambdas transformation or initial parsing
19308 // should be used.
19310 if (BuildAndDiagnose) {
19311 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19313 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19314 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19315 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19316 buildLambdaCaptureFixit(*this, LSI, Var);
19317 } else
19319 }
19320 return true;
19321 }
19322
19323 // Try to capture variable-length arrays types.
19324 if (Var->getType()->isVariablyModifiedType()) {
19325 // We're going to walk down into the type and look for VLA
19326 // expressions.
19327 QualType QTy = Var->getType();
19328 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19329 QTy = PVD->getOriginalType();
19331 }
19332
19333 if (getLangOpts().OpenMP) {
19334 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19335 // OpenMP private variables should not be captured in outer scope, so
19336 // just break here. Similarly, global variables that are captured in a
19337 // target region should not be captured outside the scope of the region.
19338 if (RSI->CapRegionKind == CR_OpenMP) {
19339 // FIXME: We should support capturing structured bindings in OpenMP.
19340 if (isa<BindingDecl>(Var)) {
19341 if (BuildAndDiagnose) {
19342 Diag(ExprLoc, diag::err_capture_binding_openmp) << Var;
19343 Diag(Var->getLocation(), diag::note_entity_declared_at) << Var;
19344 }
19345 return true;
19346 }
19347 OpenMPClauseKind IsOpenMPPrivateDecl = OpenMP().isOpenMPPrivateDecl(
19348 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19349 // If the variable is private (i.e. not captured) and has variably
19350 // modified type, we still need to capture the type for correct
19351 // codegen in all regions, associated with the construct. Currently,
19352 // it is captured in the innermost captured region only.
19353 if (IsOpenMPPrivateDecl != OMPC_unknown &&
19354 Var->getType()->isVariablyModifiedType()) {
19355 QualType QTy = Var->getType();
19356 if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
19357 QTy = PVD->getOriginalType();
19358 for (int I = 1,
19359 E = OpenMP().getNumberOfConstructScopes(RSI->OpenMPLevel);
19360 I < E; ++I) {
19361 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19362 FunctionScopes[FunctionScopesIndex - I]);
19363 assert(RSI->OpenMPLevel == OuterRSI->OpenMPLevel &&
19364 "Wrong number of captured regions associated with the "
19365 "OpenMP construct.");
19366 captureVariablyModifiedType(Context, QTy, OuterRSI);
19367 }
19368 }
19369 bool IsTargetCap =
19370 IsOpenMPPrivateDecl != OMPC_private &&
19371 OpenMP().isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel,
19372 RSI->OpenMPCaptureLevel);
19373 // Do not capture global if it is not privatized in outer regions.
19374 bool IsGlobalCap =
19375 IsGlobal && OpenMP().isOpenMPGlobalCapturedDecl(
19376 Var, RSI->OpenMPLevel, RSI->OpenMPCaptureLevel);
19377
19378 // When we detect target captures we are looking from inside the
19379 // target region, therefore we need to propagate the capture from the
19380 // enclosing region. Therefore, the capture is not initially nested.
19381 if (IsTargetCap)
19382 OpenMP().adjustOpenMPTargetScopeIndex(FunctionScopesIndex,
19383 RSI->OpenMPLevel);
19384
19385 if (IsTargetCap || IsOpenMPPrivateDecl == OMPC_private ||
19386 (IsGlobal && !IsGlobalCap)) {
19387 Nested = !IsTargetCap;
19388 bool HasConst = DeclRefType.isConstQualified();
19389 DeclRefType = DeclRefType.getUnqualifiedType();
19390 // Don't lose diagnostics about assignments to const.
19391 if (HasConst)
19392 DeclRefType.addConst();
19393 CaptureType = Context.getLValueReferenceType(DeclRefType);
19394 break;
19395 }
19396 }
19397 }
19398 }
19399 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
19400 // No capture-default, and this is not an explicit capture
19401 // so cannot capture this variable.
19402 if (BuildAndDiagnose) {
19403 Diag(ExprLoc, diag::err_lambda_impcap) << Var;
19404 Diag(Var->getLocation(), diag::note_previous_decl) << Var;
19405 auto *LSI = cast<LambdaScopeInfo>(CSI);
19406 if (LSI->Lambda) {
19407 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19408 buildLambdaCaptureFixit(*this, LSI, Var);
19409 }
19410 // FIXME: If we error out because an outer lambda can not implicitly
19411 // capture a variable that an inner lambda explicitly captures, we
19412 // should have the inner lambda do the explicit capture - because
19413 // it makes for cleaner diagnostics later. This would purely be done
19414 // so that the diagnostic does not misleadingly claim that a variable
19415 // can not be captured by a lambda implicitly even though it is captured
19416 // explicitly. Suggestion:
19417 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19418 // at the function head
19419 // - cache the StartingDeclContext - this must be a lambda
19420 // - captureInLambda in the innermost lambda the variable.
19421 }
19422 return true;
19423 }
19424 Explicit = false;
19425 FunctionScopesIndex--;
19426 if (IsInScopeDeclarationContext)
19427 DC = ParentDC;
19428 } while (!VarDC->Equals(DC));
19429
19430 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19431 // computing the type of the capture at each step, checking type-specific
19432 // requirements, and adding captures if requested.
19433 // If the variable had already been captured previously, we start capturing
19434 // at the lambda nested within that one.
19435 bool Invalid = false;
19436 for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
19437 ++I) {
19438 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
19439
19440 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19441 // certain types of variables (unnamed, variably modified types etc.)
19442 // so check for eligibility.
19443 if (!Invalid)
19444 Invalid =
19445 !isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this);
19446
19447 // After encountering an error, if we're actually supposed to capture, keep
19448 // capturing in nested contexts to suppress any follow-on diagnostics.
19449 if (Invalid && !BuildAndDiagnose)
19450 return true;
19451
19452 if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
19453 Invalid = !captureInBlock(BSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19454 DeclRefType, Nested, *this, Invalid);
19455 Nested = true;
19456 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
19458 RSI, Var, ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, Nested,
19459 Kind, /*IsTopScope*/ I == N - 1, *this, Invalid);
19460 Nested = true;
19461 } else {
19462 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
19463 Invalid =
19464 !captureInLambda(LSI, Var, ExprLoc, BuildAndDiagnose, CaptureType,
19465 DeclRefType, Nested, Kind, EllipsisLoc,
19466 /*IsTopScope*/ I == N - 1, *this, Invalid);
19467 Nested = true;
19468 }
19469
19470 if (Invalid && !BuildAndDiagnose)
19471 return true;
19472 }
19473 return Invalid;
19474}
19475
19477 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19478 QualType CaptureType;
19479 QualType DeclRefType;
19480 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
19481 /*BuildAndDiagnose=*/true, CaptureType,
19482 DeclRefType, nullptr);
19483}
19484
19486 QualType CaptureType;
19487 QualType DeclRefType;
19489 /*BuildAndDiagnose=*/false, CaptureType,
19490 DeclRefType, nullptr);
19491}
19492
19494 QualType CaptureType;
19495 QualType DeclRefType;
19496
19497 // Determine whether we can capture this variable.
19499 /*BuildAndDiagnose=*/false, CaptureType,
19500 DeclRefType, nullptr))
19501 return QualType();
19502
19503 return DeclRefType;
19504}
19505
19506namespace {
19507// Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19508// The produced TemplateArgumentListInfo* points to data stored within this
19509// object, so should only be used in contexts where the pointer will not be
19510// used after the CopiedTemplateArgs object is destroyed.
19511class CopiedTemplateArgs {
19512 bool HasArgs;
19513 TemplateArgumentListInfo TemplateArgStorage;
19514public:
19515 template<typename RefExpr>
19516 CopiedTemplateArgs(RefExpr *E) : HasArgs(E->hasExplicitTemplateArgs()) {
19517 if (HasArgs)
19518 E->copyTemplateArgumentsInto(TemplateArgStorage);
19519 }
19520 operator TemplateArgumentListInfo*()
19521#ifdef __has_cpp_attribute
19522#if __has_cpp_attribute(clang::lifetimebound)
19523 [[clang::lifetimebound]]
19524#endif
19525#endif
19526 {
19527 return HasArgs ? &TemplateArgStorage : nullptr;
19528 }
19529};
19530}
19531
19532/// Walk the set of potential results of an expression and mark them all as
19533/// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19534///
19535/// \return A new expression if we found any potential results, ExprEmpty() if
19536/// not, and ExprError() if we diagnosed an error.
19538 NonOdrUseReason NOUR) {
19539 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19540 // an object that satisfies the requirements for appearing in a
19541 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19542 // is immediately applied." This function handles the lvalue-to-rvalue
19543 // conversion part.
19544 //
19545 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19546 // transform it into the relevant kind of non-odr-use node and rebuild the
19547 // tree of nodes leading to it.
19548 //
19549 // This is a mini-TreeTransform that only transforms a restricted subset of
19550 // nodes (and only certain operands of them).
19551
19552 // Rebuild a subexpression.
19553 auto Rebuild = [&](Expr *Sub) {
19554 return rebuildPotentialResultsAsNonOdrUsed(S, Sub, NOUR);
19555 };
19556
19557 // Check whether a potential result satisfies the requirements of NOUR.
19558 auto IsPotentialResultOdrUsed = [&](NamedDecl *D) {
19559 // Any entity other than a VarDecl is always odr-used whenever it's named
19560 // in a potentially-evaluated expression.
19561 auto *VD = dyn_cast<VarDecl>(D);
19562 if (!VD)
19563 return true;
19564
19565 // C++2a [basic.def.odr]p4:
19566 // A variable x whose name appears as a potentially-evalauted expression
19567 // e is odr-used by e unless
19568 // -- x is a reference that is usable in constant expressions, or
19569 // -- x is a variable of non-reference type that is usable in constant
19570 // expressions and has no mutable subobjects, and e is an element of
19571 // the set of potential results of an expression of
19572 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19573 // conversion is applied, or
19574 // -- x is a variable of non-reference type, and e is an element of the
19575 // set of potential results of a discarded-value expression to which
19576 // the lvalue-to-rvalue conversion is not applied
19577 //
19578 // We check the first bullet and the "potentially-evaluated" condition in
19579 // BuildDeclRefExpr. We check the type requirements in the second bullet
19580 // in CheckLValueToRValueConversionOperand below.
19581 switch (NOUR) {
19582 case NOUR_None:
19583 case NOUR_Unevaluated:
19584 llvm_unreachable("unexpected non-odr-use-reason");
19585
19586 case NOUR_Constant:
19587 // Constant references were handled when they were built.
19588 if (VD->getType()->isReferenceType())
19589 return true;
19590 if (auto *RD = VD->getType()->getAsCXXRecordDecl())
19591 if (RD->hasMutableFields())
19592 return true;
19593 if (!VD->isUsableInConstantExpressions(S.Context))
19594 return true;
19595 break;
19596
19597 case NOUR_Discarded:
19598 if (VD->getType()->isReferenceType())
19599 return true;
19600 break;
19601 }
19602 return false;
19603 };
19604
19605 // Mark that this expression does not constitute an odr-use.
19606 auto MarkNotOdrUsed = [&] {
19607 S.MaybeODRUseExprs.remove(E);
19608 if (LambdaScopeInfo *LSI = S.getCurLambda())
19609 LSI->markVariableExprAsNonODRUsed(E);
19610 };
19611
19612 // C++2a [basic.def.odr]p2:
19613 // The set of potential results of an expression e is defined as follows:
19614 switch (E->getStmtClass()) {
19615 // -- If e is an id-expression, ...
19616 case Expr::DeclRefExprClass: {
19617 auto *DRE = cast<DeclRefExpr>(E);
19618 if (DRE->isNonOdrUse() || IsPotentialResultOdrUsed(DRE->getDecl()))
19619 break;
19620
19621 // Rebuild as a non-odr-use DeclRefExpr.
19622 MarkNotOdrUsed();
19623 return DeclRefExpr::Create(
19624 S.Context, DRE->getQualifierLoc(), DRE->getTemplateKeywordLoc(),
19625 DRE->getDecl(), DRE->refersToEnclosingVariableOrCapture(),
19626 DRE->getNameInfo(), DRE->getType(), DRE->getValueKind(),
19627 DRE->getFoundDecl(), CopiedTemplateArgs(DRE), NOUR);
19628 }
19629
19630 case Expr::FunctionParmPackExprClass: {
19631 auto *FPPE = cast<FunctionParmPackExpr>(E);
19632 // If any of the declarations in the pack is odr-used, then the expression
19633 // as a whole constitutes an odr-use.
19634 for (VarDecl *D : *FPPE)
19635 if (IsPotentialResultOdrUsed(D))
19636 return ExprEmpty();
19637
19638 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19639 // nothing cares about whether we marked this as an odr-use, but it might
19640 // be useful for non-compiler tools.
19641 MarkNotOdrUsed();
19642 break;
19643 }
19644
19645 // -- If e is a subscripting operation with an array operand...
19646 case Expr::ArraySubscriptExprClass: {
19647 auto *ASE = cast<ArraySubscriptExpr>(E);
19648 Expr *OldBase = ASE->getBase()->IgnoreImplicit();
19649 if (!OldBase->getType()->isArrayType())
19650 break;
19651 ExprResult Base = Rebuild(OldBase);
19652 if (!Base.isUsable())
19653 return Base;
19654 Expr *LHS = ASE->getBase() == ASE->getLHS() ? Base.get() : ASE->getLHS();
19655 Expr *RHS = ASE->getBase() == ASE->getRHS() ? Base.get() : ASE->getRHS();
19656 SourceLocation LBracketLoc = ASE->getBeginLoc(); // FIXME: Not stored.
19657 return S.ActOnArraySubscriptExpr(nullptr, LHS, LBracketLoc, RHS,
19658 ASE->getRBracketLoc());
19659 }
19660
19661 case Expr::MemberExprClass: {
19662 auto *ME = cast<MemberExpr>(E);
19663 // -- If e is a class member access expression [...] naming a non-static
19664 // data member...
19665 if (isa<FieldDecl>(ME->getMemberDecl())) {
19666 ExprResult Base = Rebuild(ME->getBase());
19667 if (!Base.isUsable())
19668 return Base;
19669 return MemberExpr::Create(
19670 S.Context, Base.get(), ME->isArrow(), ME->getOperatorLoc(),
19671 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(),
19672 ME->getMemberDecl(), ME->getFoundDecl(), ME->getMemberNameInfo(),
19673 CopiedTemplateArgs(ME), ME->getType(), ME->getValueKind(),
19674 ME->getObjectKind(), ME->isNonOdrUse());
19675 }
19676
19677 if (ME->getMemberDecl()->isCXXInstanceMember())
19678 break;
19679
19680 // -- If e is a class member access expression naming a static data member,
19681 // ...
19682 if (ME->isNonOdrUse() || IsPotentialResultOdrUsed(ME->getMemberDecl()))
19683 break;
19684
19685 // Rebuild as a non-odr-use MemberExpr.
19686 MarkNotOdrUsed();
19687 return MemberExpr::Create(
19688 S.Context, ME->getBase(), ME->isArrow(), ME->getOperatorLoc(),
19689 ME->getQualifierLoc(), ME->getTemplateKeywordLoc(), ME->getMemberDecl(),
19690 ME->getFoundDecl(), ME->getMemberNameInfo(), CopiedTemplateArgs(ME),
19691 ME->getType(), ME->getValueKind(), ME->getObjectKind(), NOUR);
19692 }
19693
19694 case Expr::BinaryOperatorClass: {
19695 auto *BO = cast<BinaryOperator>(E);
19696 Expr *LHS = BO->getLHS();
19697 Expr *RHS = BO->getRHS();
19698 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19699 if (BO->getOpcode() == BO_PtrMemD) {
19700 ExprResult Sub = Rebuild(LHS);
19701 if (!Sub.isUsable())
19702 return Sub;
19703 LHS = Sub.get();
19704 // -- If e is a comma expression, ...
19705 } else if (BO->getOpcode() == BO_Comma) {
19706 ExprResult Sub = Rebuild(RHS);
19707 if (!Sub.isUsable())
19708 return Sub;
19709 RHS = Sub.get();
19710 } else {
19711 break;
19712 }
19713 return S.BuildBinOp(nullptr, BO->getOperatorLoc(), BO->getOpcode(),
19714 LHS, RHS);
19715 }
19716
19717 // -- If e has the form (e1)...
19718 case Expr::ParenExprClass: {
19719 auto *PE = cast<ParenExpr>(E);
19720 ExprResult Sub = Rebuild(PE->getSubExpr());
19721 if (!Sub.isUsable())
19722 return Sub;
19723 return S.ActOnParenExpr(PE->getLParen(), PE->getRParen(), Sub.get());
19724 }
19725
19726 // -- If e is a glvalue conditional expression, ...
19727 // We don't apply this to a binary conditional operator. FIXME: Should we?
19728 case Expr::ConditionalOperatorClass: {
19729 auto *CO = cast<ConditionalOperator>(E);
19730 ExprResult LHS = Rebuild(CO->getLHS());
19731 if (LHS.isInvalid())
19732 return ExprError();
19733 ExprResult RHS = Rebuild(CO->getRHS());
19734 if (RHS.isInvalid())
19735 return ExprError();
19736 if (!LHS.isUsable() && !RHS.isUsable())
19737 return ExprEmpty();
19738 if (!LHS.isUsable())
19739 LHS = CO->getLHS();
19740 if (!RHS.isUsable())
19741 RHS = CO->getRHS();
19742 return S.ActOnConditionalOp(CO->getQuestionLoc(), CO->getColonLoc(),
19743 CO->getCond(), LHS.get(), RHS.get());
19744 }
19745
19746 // [Clang extension]
19747 // -- If e has the form __extension__ e1...
19748 case Expr::UnaryOperatorClass: {
19749 auto *UO = cast<UnaryOperator>(E);
19750 if (UO->getOpcode() != UO_Extension)
19751 break;
19752 ExprResult Sub = Rebuild(UO->getSubExpr());
19753 if (!Sub.isUsable())
19754 return Sub;
19755 return S.BuildUnaryOp(nullptr, UO->getOperatorLoc(), UO_Extension,
19756 Sub.get());
19757 }
19758
19759 // [Clang extension]
19760 // -- If e has the form _Generic(...), the set of potential results is the
19761 // union of the sets of potential results of the associated expressions.
19762 case Expr::GenericSelectionExprClass: {
19763 auto *GSE = cast<GenericSelectionExpr>(E);
19764
19765 SmallVector<Expr *, 4> AssocExprs;
19766 bool AnyChanged = false;
19767 for (Expr *OrigAssocExpr : GSE->getAssocExprs()) {
19768 ExprResult AssocExpr = Rebuild(OrigAssocExpr);
19769 if (AssocExpr.isInvalid())
19770 return ExprError();
19771 if (AssocExpr.isUsable()) {
19772 AssocExprs.push_back(AssocExpr.get());
19773 AnyChanged = true;
19774 } else {
19775 AssocExprs.push_back(OrigAssocExpr);
19776 }
19777 }
19778
19779 void *ExOrTy = nullptr;
19780 bool IsExpr = GSE->isExprPredicate();
19781 if (IsExpr)
19782 ExOrTy = GSE->getControllingExpr();
19783 else
19784 ExOrTy = GSE->getControllingType();
19785 return AnyChanged ? S.CreateGenericSelectionExpr(
19786 GSE->getGenericLoc(), GSE->getDefaultLoc(),
19787 GSE->getRParenLoc(), IsExpr, ExOrTy,
19788 GSE->getAssocTypeSourceInfos(), AssocExprs)
19789 : ExprEmpty();
19790 }
19791
19792 // [Clang extension]
19793 // -- If e has the form __builtin_choose_expr(...), the set of potential
19794 // results is the union of the sets of potential results of the
19795 // second and third subexpressions.
19796 case Expr::ChooseExprClass: {
19797 auto *CE = cast<ChooseExpr>(E);
19798
19799 ExprResult LHS = Rebuild(CE->getLHS());
19800 if (LHS.isInvalid())
19801 return ExprError();
19802
19803 ExprResult RHS = Rebuild(CE->getLHS());
19804 if (RHS.isInvalid())
19805 return ExprError();
19806
19807 if (!LHS.get() && !RHS.get())
19808 return ExprEmpty();
19809 if (!LHS.isUsable())
19810 LHS = CE->getLHS();
19811 if (!RHS.isUsable())
19812 RHS = CE->getRHS();
19813
19814 return S.ActOnChooseExpr(CE->getBuiltinLoc(), CE->getCond(), LHS.get(),
19815 RHS.get(), CE->getRParenLoc());
19816 }
19817
19818 // Step through non-syntactic nodes.
19819 case Expr::ConstantExprClass: {
19820 auto *CE = cast<ConstantExpr>(E);
19821 ExprResult Sub = Rebuild(CE->getSubExpr());
19822 if (!Sub.isUsable())
19823 return Sub;
19824 return ConstantExpr::Create(S.Context, Sub.get());
19825 }
19826
19827 // We could mostly rely on the recursive rebuilding to rebuild implicit
19828 // casts, but not at the top level, so rebuild them here.
19829 case Expr::ImplicitCastExprClass: {
19830 auto *ICE = cast<ImplicitCastExpr>(E);
19831 // Only step through the narrow set of cast kinds we expect to encounter.
19832 // Anything else suggests we've left the region in which potential results
19833 // can be found.
19834 switch (ICE->getCastKind()) {
19835 case CK_NoOp:
19836 case CK_DerivedToBase:
19837 case CK_UncheckedDerivedToBase: {
19838 ExprResult Sub = Rebuild(ICE->getSubExpr());
19839 if (!Sub.isUsable())
19840 return Sub;
19841 CXXCastPath Path(ICE->path());
19842 return S.ImpCastExprToType(Sub.get(), ICE->getType(), ICE->getCastKind(),
19843 ICE->getValueKind(), &Path);
19844 }
19845
19846 default:
19847 break;
19848 }
19849 break;
19850 }
19851
19852 default:
19853 break;
19854 }
19855
19856 // Can't traverse through this node. Nothing to do.
19857 return ExprEmpty();
19858}
19859
19861 // Check whether the operand is or contains an object of non-trivial C union
19862 // type.
19863 if (E->getType().isVolatileQualified() &&
19869
19870 // C++2a [basic.def.odr]p4:
19871 // [...] an expression of non-volatile-qualified non-class type to which
19872 // the lvalue-to-rvalue conversion is applied [...]
19873 if (E->getType().isVolatileQualified() || E->getType()->getAs<RecordType>())
19874 return E;
19875
19878 if (Result.isInvalid())
19879 return ExprError();
19880 return Result.get() ? Result : E;
19881}
19882
19884 Res = CorrectDelayedTyposInExpr(Res);
19885
19886 if (!Res.isUsable())
19887 return Res;
19888
19889 // If a constant-expression is a reference to a variable where we delay
19890 // deciding whether it is an odr-use, just assume we will apply the
19891 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19892 // (a non-type template argument), we have special handling anyway.
19894}
19895
19897 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19898 // call.
19899 MaybeODRUseExprSet LocalMaybeODRUseExprs;
19900 std::swap(LocalMaybeODRUseExprs, MaybeODRUseExprs);
19901
19902 for (Expr *E : LocalMaybeODRUseExprs) {
19903 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
19904 MarkVarDeclODRUsed(cast<VarDecl>(DRE->getDecl()),
19905 DRE->getLocation(), *this);
19906 } else if (auto *ME = dyn_cast<MemberExpr>(E)) {
19907 MarkVarDeclODRUsed(cast<VarDecl>(ME->getMemberDecl()), ME->getMemberLoc(),
19908 *this);
19909 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(E)) {
19910 for (VarDecl *VD : *FP)
19911 MarkVarDeclODRUsed(VD, FP->getParameterPackLocation(), *this);
19912 } else {
19913 llvm_unreachable("Unexpected expression");
19914 }
19915 }
19916
19917 assert(MaybeODRUseExprs.empty() &&
19918 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19919}
19920
19922 ValueDecl *Var, Expr *E) {
19924 if (!VD)
19925 return;
19926
19927 const bool RefersToEnclosingScope =
19928 (SemaRef.CurContext != VD->getDeclContext() &&
19930 if (RefersToEnclosingScope) {
19931 LambdaScopeInfo *const LSI =
19932 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19933 if (LSI && (!LSI->CallOperator ||
19934 !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
19935 // If a variable could potentially be odr-used, defer marking it so
19936 // until we finish analyzing the full expression for any
19937 // lvalue-to-rvalue
19938 // or discarded value conversions that would obviate odr-use.
19939 // Add it to the list of potential captures that will be analyzed
19940 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19941 // unless the variable is a reference that was initialized by a constant
19942 // expression (this will never need to be captured or odr-used).
19943 //
19944 // FIXME: We can simplify this a lot after implementing P0588R1.
19945 assert(E && "Capture variable should be used in an expression.");
19946 if (!Var->getType()->isReferenceType() ||
19949 }
19950 }
19951}
19952
19954 Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E,
19955 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
19956 assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E) ||
19957 isa<FunctionParmPackExpr>(E)) &&
19958 "Invalid Expr argument to DoMarkVarDeclReferenced");
19959 Var->setReferenced();
19960
19961 if (Var->isInvalidDecl())
19962 return;
19963
19964 auto *MSI = Var->getMemberSpecializationInfo();
19967
19968 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19969 bool UsableInConstantExpr =
19971
19972 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19973 RefsMinusAssignments.insert({Var, 0}).first->getSecond()++;
19974 }
19975
19976 // C++20 [expr.const]p12:
19977 // A variable [...] is needed for constant evaluation if it is [...] a
19978 // variable whose name appears as a potentially constant evaluated
19979 // expression that is either a contexpr variable or is of non-volatile
19980 // const-qualified integral type or of reference type
19981 bool NeededForConstantEvaluation =
19982 isPotentiallyConstantEvaluatedContext(SemaRef) && UsableInConstantExpr;
19983
19984 bool NeedDefinition =
19985 OdrUse == OdrUseContext::Used || NeededForConstantEvaluation;
19986
19987 assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
19988 "Can't instantiate a partial template specialization.");
19989
19990 // If this might be a member specialization of a static data member, check
19991 // the specialization is visible. We already did the checks for variable
19992 // template specializations when we created them.
19993 if (NeedDefinition && TSK != TSK_Undeclared &&
19994 !isa<VarTemplateSpecializationDecl>(Var))
19996
19997 // Perform implicit instantiation of static data members, static data member
19998 // templates of class templates, and variable template specializations. Delay
19999 // instantiations of variable templates, except for those that could be used
20000 // in a constant expression.
20001 if (NeedDefinition && isTemplateInstantiation(TSK)) {
20002 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20003 // instantiation declaration if a variable is usable in a constant
20004 // expression (among other cases).
20005 bool TryInstantiating =
20007 (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
20008
20009 if (TryInstantiating) {
20010 SourceLocation PointOfInstantiation =
20011 MSI ? MSI->getPointOfInstantiation() : Var->getPointOfInstantiation();
20012 bool FirstInstantiation = PointOfInstantiation.isInvalid();
20013 if (FirstInstantiation) {
20014 PointOfInstantiation = Loc;
20015 if (MSI)
20016 MSI->setPointOfInstantiation(PointOfInstantiation);
20017 // FIXME: Notify listener.
20018 else
20019 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
20020 }
20021
20022 if (UsableInConstantExpr) {
20023 // Do not defer instantiations of variables that could be used in a
20024 // constant expression.
20025 SemaRef.runWithSufficientStackSpace(PointOfInstantiation, [&] {
20026 SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
20027 });
20028
20029 // Re-set the member to trigger a recomputation of the dependence bits
20030 // for the expression.
20031 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20032 DRE->setDecl(DRE->getDecl());
20033 else if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
20034 ME->setMemberDecl(ME->getMemberDecl());
20035 } else if (FirstInstantiation) {
20037 .push_back(std::make_pair(Var, PointOfInstantiation));
20038 } else {
20039 bool Inserted = false;
20040 for (auto &I : SemaRef.SavedPendingInstantiations) {
20041 auto Iter = llvm::find_if(
20042 I, [Var](const Sema::PendingImplicitInstantiation &P) {
20043 return P.first == Var;
20044 });
20045 if (Iter != I.end()) {
20047 I.erase(Iter);
20048 Inserted = true;
20049 break;
20050 }
20051 }
20052
20053 // FIXME: For a specialization of a variable template, we don't
20054 // distinguish between "declaration and type implicitly instantiated"
20055 // and "implicit instantiation of definition requested", so we have
20056 // no direct way to avoid enqueueing the pending instantiation
20057 // multiple times.
20058 if (isa<VarTemplateSpecializationDecl>(Var) && !Inserted)
20060 .push_back(std::make_pair(Var, PointOfInstantiation));
20061 }
20062 }
20063 }
20064
20065 // C++2a [basic.def.odr]p4:
20066 // A variable x whose name appears as a potentially-evaluated expression e
20067 // is odr-used by e unless
20068 // -- x is a reference that is usable in constant expressions
20069 // -- x is a variable of non-reference type that is usable in constant
20070 // expressions and has no mutable subobjects [FIXME], and e is an
20071 // element of the set of potential results of an expression of
20072 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20073 // conversion is applied
20074 // -- x is a variable of non-reference type, and e is an element of the set
20075 // of potential results of a discarded-value expression to which the
20076 // lvalue-to-rvalue conversion is not applied [FIXME]
20077 //
20078 // We check the first part of the second bullet here, and
20079 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20080 // FIXME: To get the third bullet right, we need to delay this even for
20081 // variables that are not usable in constant expressions.
20082
20083 // If we already know this isn't an odr-use, there's nothing more to do.
20084 if (DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(E))
20085 if (DRE->isNonOdrUse())
20086 return;
20087 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(E))
20088 if (ME->isNonOdrUse())
20089 return;
20090
20091 switch (OdrUse) {
20092 case OdrUseContext::None:
20093 // In some cases, a variable may not have been marked unevaluated, if it
20094 // appears in a defaukt initializer.
20095 assert((!E || isa<FunctionParmPackExpr>(E) ||
20097 "missing non-odr-use marking for unevaluated decl ref");
20098 break;
20099
20100 case OdrUseContext::FormallyOdrUsed:
20101 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20102 // behavior.
20103 break;
20104
20105 case OdrUseContext::Used:
20106 // If we might later find that this expression isn't actually an odr-use,
20107 // delay the marking.
20109 SemaRef.MaybeODRUseExprs.insert(E);
20110 else
20111 MarkVarDeclODRUsed(Var, Loc, SemaRef);
20112 break;
20113
20114 case OdrUseContext::Dependent:
20115 // If this is a dependent context, we don't need to mark variables as
20116 // odr-used, but we may still need to track them for lambda capture.
20117 // FIXME: Do we also need to do this inside dependent typeid expressions
20118 // (which are modeled as unevaluated at this point)?
20119 DoMarkPotentialCapture(SemaRef, Loc, Var, E);
20120 break;
20121 }
20122}
20123
20125 BindingDecl *BD, Expr *E) {
20126 BD->setReferenced();
20127
20128 if (BD->isInvalidDecl())
20129 return;
20130
20131 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
20132 if (OdrUse == OdrUseContext::Used) {
20133 QualType CaptureType, DeclRefType;
20135 /*EllipsisLoc*/ SourceLocation(),
20136 /*BuildAndDiagnose*/ true, CaptureType,
20137 DeclRefType,
20138 /*FunctionScopeIndexToStopAt*/ nullptr);
20139 } else if (OdrUse == OdrUseContext::Dependent) {
20140 DoMarkPotentialCapture(SemaRef, Loc, BD, E);
20141 }
20142}
20143
20144/// Mark a variable referenced, and check whether it is odr-used
20145/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
20146/// used directly for normal expressions referring to VarDecl.
20148 DoMarkVarDeclReferenced(*this, Loc, Var, nullptr, RefsMinusAssignments);
20149}
20150
20151// C++ [temp.dep.expr]p3:
20152// An id-expression is type-dependent if it contains:
20153// - an identifier associated by name lookup with an entity captured by copy
20154// in a lambda-expression that has an explicit object parameter whose type
20155// is dependent ([dcl.fct]),
20157 Sema &SemaRef, ValueDecl *D, Expr *E) {
20158 auto *ID = dyn_cast<DeclRefExpr>(E);
20159 if (!ID || ID->isTypeDependent() || !ID->refersToEnclosingVariableOrCapture())
20160 return;
20161
20162 // If any enclosing lambda with a dependent explicit object parameter either
20163 // explicitly captures the variable by value, or has a capture default of '='
20164 // and does not capture the variable by reference, then the type of the DRE
20165 // is dependent on the type of that lambda's explicit object parameter.
20166 auto IsDependent = [&]() {
20167 for (auto *Scope : llvm::reverse(SemaRef.FunctionScopes)) {
20168 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope);
20169 if (!LSI)
20170 continue;
20171
20172 if (LSI->Lambda && !LSI->Lambda->Encloses(SemaRef.CurContext) &&
20173 LSI->AfterParameterList)
20174 return false;
20175
20176 const auto *MD = LSI->CallOperator;
20177 if (MD->getType().isNull())
20178 continue;
20179
20180 const auto *Ty = MD->getType()->getAs<FunctionProtoType>();
20181 if (!Ty || !MD->isExplicitObjectMemberFunction() ||
20182 !Ty->getParamType(0)->isDependentType())
20183 continue;
20184
20185 if (auto *C = LSI->CaptureMap.count(D) ? &LSI->getCapture(D) : nullptr) {
20186 if (C->isCopyCapture())
20187 return true;
20188 continue;
20189 }
20190
20191 if (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByval)
20192 return true;
20193 }
20194 return false;
20195 }();
20196
20197 ID->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20198 IsDependent, SemaRef.getASTContext());
20199}
20200
20201static void
20203 bool MightBeOdrUse,
20204 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20207
20208 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
20210 if (SemaRef.getLangOpts().CPlusPlus)
20212 Var, E);
20213 return;
20214 }
20215
20216 if (BindingDecl *Decl = dyn_cast<BindingDecl>(D)) {
20218 if (SemaRef.getLangOpts().CPlusPlus)
20220 Decl, E);
20221 return;
20222 }
20223 SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
20224
20225 // If this is a call to a method via a cast, also mark the method in the
20226 // derived class used in case codegen can devirtualize the call.
20227 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
20228 if (!ME)
20229 return;
20230 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
20231 if (!MD)
20232 return;
20233 // Only attempt to devirtualize if this is truly a virtual call.
20234 bool IsVirtualCall = MD->isVirtual() &&
20236 if (!IsVirtualCall)
20237 return;
20238
20239 // If it's possible to devirtualize the call, mark the called function
20240 // referenced.
20242 ME->getBase(), SemaRef.getLangOpts().AppleKext);
20243 if (DM)
20244 SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
20245}
20246
20247/// Perform reference-marking and odr-use handling for a DeclRefExpr.
20248///
20249/// Note, this may change the dependence of the DeclRefExpr, and so needs to be
20250/// handled with care if the DeclRefExpr is not newly-created.
20252 // TODO: update this with DR# once a defect report is filed.
20253 // C++11 defect. The address of a pure member should not be an ODR use, even
20254 // if it's a qualified reference.
20255 bool OdrUse = true;
20256 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
20257 if (Method->isVirtual() &&
20258 !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
20259 OdrUse = false;
20260
20261 if (auto *FD = dyn_cast<FunctionDecl>(E->getDecl())) {
20265 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20266 !FD->isDependentContext())
20267 ExprEvalContexts.back().ReferenceToConsteval.insert(E);
20268 }
20269 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20271}
20272
20273/// Perform reference-marking and odr-use handling for a MemberExpr.
20275 // C++11 [basic.def.odr]p2:
20276 // A non-overloaded function whose name appears as a potentially-evaluated
20277 // expression or a member of a set of candidate functions, if selected by
20278 // overload resolution when referred to from a potentially-evaluated
20279 // expression, is odr-used, unless it is a pure virtual function and its
20280 // name is not explicitly qualified.
20281 bool MightBeOdrUse = true;
20283 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
20284 if (Method->isPureVirtual())
20285 MightBeOdrUse = false;
20286 }
20287 SourceLocation Loc =
20288 E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
20289 MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse,
20291}
20292
20293/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
20295 for (VarDecl *VD : *E)
20296 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20298}
20299
20300/// Perform marking for a reference to an arbitrary declaration. It
20301/// marks the declaration referenced, and performs odr-use checking for
20302/// functions and variables. This method should not be used when building a
20303/// normal expression which refers to a variable.
20305 bool MightBeOdrUse) {
20306 if (MightBeOdrUse) {
20307 if (auto *VD = dyn_cast<VarDecl>(D)) {
20308 MarkVariableReferenced(Loc, VD);
20309 return;
20310 }
20311 }
20312 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
20313 MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
20314 return;
20315 }
20316 D->setReferenced();
20317}
20318
20319namespace {
20320 // Mark all of the declarations used by a type as referenced.
20321 // FIXME: Not fully implemented yet! We need to have a better understanding
20322 // of when we're entering a context we should not recurse into.
20323 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20324 // TreeTransforms rebuilding the type in a new context. Rather than
20325 // duplicating the TreeTransform logic, we should consider reusing it here.
20326 // Currently that causes problems when rebuilding LambdaExprs.
20327 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
20328 Sema &S;
20329 SourceLocation Loc;
20330
20331 public:
20333
20334 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
20335
20336 bool TraverseTemplateArgument(const TemplateArgument &Arg);
20337 };
20338}
20339
20340bool MarkReferencedDecls::TraverseTemplateArgument(
20341 const TemplateArgument &Arg) {
20342 {
20343 // A non-type template argument is a constant-evaluated context.
20347 if (Decl *D = Arg.getAsDecl())
20348 S.MarkAnyDeclReferenced(Loc, D, true);
20349 } else if (Arg.getKind() == TemplateArgument::Expression) {
20351 }
20352 }
20353
20354 return Inherited::TraverseTemplateArgument(Arg);
20355}
20356
20358 MarkReferencedDecls Marker(*this, Loc);
20359 Marker.TraverseType(T);
20360}
20361
20362namespace {
20363/// Helper class that marks all of the declarations referenced by
20364/// potentially-evaluated subexpressions as "referenced".
20365class EvaluatedExprMarker : public UsedDeclVisitor<EvaluatedExprMarker> {
20366public:
20367 typedef UsedDeclVisitor<EvaluatedExprMarker> Inherited;
20368 bool SkipLocalVariables;
20370
20371 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20373 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20374
20375 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20376 S.MarkFunctionReferenced(Loc, cast<FunctionDecl>(D));
20377 }
20378
20379 void Visit(Expr *E) {
20380 if (llvm::is_contained(StopAt, E))
20381 return;
20382 Inherited::Visit(E);
20383 }
20384
20385 void VisitConstantExpr(ConstantExpr *E) {
20386 // Don't mark declarations within a ConstantExpression, as this expression
20387 // will be evaluated and folded to a value.
20388 }
20389
20390 void VisitDeclRefExpr(DeclRefExpr *E) {
20391 // If we were asked not to visit local variables, don't.
20392 if (SkipLocalVariables) {
20393 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
20394 if (VD->hasLocalStorage())
20395 return;
20396 }
20397
20398 // FIXME: This can trigger the instantiation of the initializer of a
20399 // variable, which can cause the expression to become value-dependent
20400 // or error-dependent. Do we need to propagate the new dependence bits?
20402 }
20403
20404 void VisitMemberExpr(MemberExpr *E) {
20406 Visit(E->getBase());
20407 }
20408};
20409} // namespace
20410
20411/// Mark any declarations that appear within this expression or any
20412/// potentially-evaluated subexpressions as "referenced".
20413///
20414/// \param SkipLocalVariables If true, don't mark local variables as
20415/// 'referenced'.
20416/// \param StopAt Subexpressions that we shouldn't recurse into.
20418 bool SkipLocalVariables,
20419 ArrayRef<const Expr*> StopAt) {
20420 EvaluatedExprMarker(*this, SkipLocalVariables, StopAt).Visit(E);
20421}
20422
20423/// Emit a diagnostic when statements are reachable.
20424/// FIXME: check for reachability even in expressions for which we don't build a
20425/// CFG (eg, in the initializer of a global or in a constant expression).
20426/// For example,
20427/// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20429 const PartialDiagnostic &PD) {
20430 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20431 if (!FunctionScopes.empty())
20432 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20433 sema::PossiblyUnreachableDiag(PD, Loc, Stmts));
20434 return true;
20435 }
20436
20437 // The initializer of a constexpr variable or of the first declaration of a
20438 // static data member is not syntactically a constant evaluated constant,
20439 // but nonetheless is always required to be a constant expression, so we
20440 // can skip diagnosing.
20441 // FIXME: Using the mangling context here is a hack.
20442 if (auto *VD = dyn_cast_or_null<VarDecl>(
20443 ExprEvalContexts.back().ManglingContextDecl)) {
20444 if (VD->isConstexpr() ||
20445 (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
20446 return false;
20447 // FIXME: For any other kind of variable, we should build a CFG for its
20448 // initializer and check whether the context in question is reachable.
20449 }
20450
20451 Diag(Loc, PD);
20452 return true;
20453}
20454
20455/// Emit a diagnostic that describes an effect on the run-time behavior
20456/// of the program being compiled.
20457///
20458/// This routine emits the given diagnostic when the code currently being
20459/// type-checked is "potentially evaluated", meaning that there is a
20460/// possibility that the code will actually be executable. Code in sizeof()
20461/// expressions, code used only during overload resolution, etc., are not
20462/// potentially evaluated. This routine will suppress such diagnostics or,
20463/// in the absolutely nutty case of potentially potentially evaluated
20464/// expressions (C++ typeid), queue the diagnostic to potentially emit it
20465/// later.
20466///
20467/// This routine should be used for all diagnostics that describe the run-time
20468/// behavior of a program, such as passing a non-POD value through an ellipsis.
20469/// Failure to do so will likely result in spurious diagnostics or failures
20470/// during overload resolution or within sizeof/alignof/typeof/typeid.
20472 const PartialDiagnostic &PD) {
20473
20474 if (ExprEvalContexts.back().isDiscardedStatementContext())
20475 return false;
20476
20477 switch (ExprEvalContexts.back().Context) {
20482 // The argument will never be evaluated, so don't complain.
20483 break;
20484
20487 // Relevant diagnostics should be produced by constant evaluation.
20488 break;
20489
20492 return DiagIfReachable(Loc, Stmts, PD);
20493 }
20494
20495 return false;
20496}
20497
20499 const PartialDiagnostic &PD) {
20500 return DiagRuntimeBehavior(
20501 Loc, Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
20502}
20503
20505 CallExpr *CE, FunctionDecl *FD) {
20506 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
20507 return false;
20508
20509 // If we're inside a decltype's expression, don't check for a valid return
20510 // type or construct temporaries until we know whether this is the last call.
20511 if (ExprEvalContexts.back().ExprContext ==
20513 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
20514 return false;
20515 }
20516
20517 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
20518 FunctionDecl *FD;
20519 CallExpr *CE;
20520
20521 public:
20522 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
20523 : FD(FD), CE(CE) { }
20524
20525 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
20526 if (!FD) {
20527 S.Diag(Loc, diag::err_call_incomplete_return)
20528 << T << CE->getSourceRange();
20529 return;
20530 }
20531
20532 S.Diag(Loc, diag::err_call_function_incomplete_return)
20533 << CE->getSourceRange() << FD << T;
20534 S.Diag(FD->getLocation(), diag::note_entity_declared_at)
20535 << FD->getDeclName();
20536 }
20537 } Diagnoser(FD, CE);
20538
20539 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
20540 return true;
20541
20542 return false;
20543}
20544
20545// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20546// will prevent this condition from triggering, which is what we want.
20548 SourceLocation Loc;
20549
20550 unsigned diagnostic = diag::warn_condition_is_assignment;
20551 bool IsOrAssign = false;
20552
20553 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
20554 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
20555 return;
20556
20557 IsOrAssign = Op->getOpcode() == BO_OrAssign;
20558
20559 // Greylist some idioms by putting them into a warning subcategory.
20560 if (ObjCMessageExpr *ME
20561 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
20562 Selector Sel = ME->getSelector();
20563
20564 // self = [<foo> init...]
20565 if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
20566 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20567
20568 // <foo> = [<bar> nextObject]
20569 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
20570 diagnostic = diag::warn_condition_is_idiomatic_assignment;
20571 }
20572
20573 Loc = Op->getOperatorLoc();
20574 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
20575 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
20576 return;
20577
20578 IsOrAssign = Op->getOperator() == OO_PipeEqual;
20579 Loc = Op->getOperatorLoc();
20580 } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
20581 return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
20582 else {
20583 // Not an assignment.
20584 return;
20585 }
20586
20587 Diag(Loc, diagnostic) << E->getSourceRange();
20588
20591 Diag(Loc, diag::note_condition_assign_silence)
20593 << FixItHint::CreateInsertion(Close, ")");
20594
20595 if (IsOrAssign)
20596 Diag(Loc, diag::note_condition_or_assign_to_comparison)
20597 << FixItHint::CreateReplacement(Loc, "!=");
20598 else
20599 Diag(Loc, diag::note_condition_assign_to_comparison)
20600 << FixItHint::CreateReplacement(Loc, "==");
20601}
20602
20603/// Redundant parentheses over an equality comparison can indicate
20604/// that the user intended an assignment used as condition.
20606 // Don't warn if the parens came from a macro.
20607 SourceLocation parenLoc = ParenE->getBeginLoc();
20608 if (parenLoc.isInvalid() || parenLoc.isMacroID())
20609 return;
20610 // Don't warn for dependent expressions.
20611 if (ParenE->isTypeDependent())
20612 return;
20613
20614 Expr *E = ParenE->IgnoreParens();
20615
20616 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
20617 if (opE->getOpcode() == BO_EQ &&
20618 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
20619 == Expr::MLV_Valid) {
20620 SourceLocation Loc = opE->getOperatorLoc();
20621
20622 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
20623 SourceRange ParenERange = ParenE->getSourceRange();
20624 Diag(Loc, diag::note_equality_comparison_silence)
20625 << FixItHint::CreateRemoval(ParenERange.getBegin())
20626 << FixItHint::CreateRemoval(ParenERange.getEnd());
20627 Diag(Loc, diag::note_equality_comparison_to_assign)
20628 << FixItHint::CreateReplacement(Loc, "=");
20629 }
20630}
20631
20633 bool IsConstexpr) {
20635 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
20637
20638 ExprResult result = CheckPlaceholderExpr(E);
20639 if (result.isInvalid()) return ExprError();
20640 E = result.get();
20641
20642 if (!E->isTypeDependent()) {
20643 if (getLangOpts().CPlusPlus)
20644 return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
20645
20647 if (ERes.isInvalid())
20648 return ExprError();
20649 E = ERes.get();
20650
20651 QualType T = E->getType();
20652 if (!T->isScalarType()) { // C99 6.8.4.1p1
20653 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
20654 << T << E->getSourceRange();
20655 return ExprError();
20656 }
20657 CheckBoolLikeConversion(E, Loc);
20658 }
20659
20660 return E;
20661}
20662
20664 Expr *SubExpr, ConditionKind CK,
20665 bool MissingOK) {
20666 // MissingOK indicates whether having no condition expression is valid
20667 // (for loop) or invalid (e.g. while loop).
20668 if (!SubExpr)
20669 return MissingOK ? ConditionResult() : ConditionError();
20670
20671 ExprResult Cond;
20672 switch (CK) {
20674 Cond = CheckBooleanCondition(Loc, SubExpr);
20675 break;
20676
20678 Cond = CheckBooleanCondition(Loc, SubExpr, true);
20679 break;
20680
20682 Cond = CheckSwitchCondition(Loc, SubExpr);
20683 break;
20684 }
20685 if (Cond.isInvalid()) {
20686 Cond = CreateRecoveryExpr(SubExpr->getBeginLoc(), SubExpr->getEndLoc(),
20687 {SubExpr}, PreferredConditionType(CK));
20688 if (!Cond.get())
20689 return ConditionError();
20690 }
20691 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20692 FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
20693 if (!FullExpr.get())
20694 return ConditionError();
20695
20696 return ConditionResult(*this, nullptr, FullExpr,
20698}
20699
20700namespace {
20701 /// A visitor for rebuilding a call to an __unknown_any expression
20702 /// to have an appropriate type.
20703 struct RebuildUnknownAnyFunction
20704 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
20705
20706 Sema &S;
20707
20708 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
20709
20710 ExprResult VisitStmt(Stmt *S) {
20711 llvm_unreachable("unexpected statement!");
20712 }
20713
20714 ExprResult VisitExpr(Expr *E) {
20715 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
20716 << E->getSourceRange();
20717 return ExprError();
20718 }
20719
20720 /// Rebuild an expression which simply semantically wraps another
20721 /// expression which it shares the type and value kind of.
20722 template <class T> ExprResult rebuildSugarExpr(T *E) {
20723 ExprResult SubResult = Visit(E->getSubExpr());
20724 if (SubResult.isInvalid()) return ExprError();
20725
20726 Expr *SubExpr = SubResult.get();
20727 E->setSubExpr(SubExpr);
20728 E->setType(SubExpr->getType());
20729 E->setValueKind(SubExpr->getValueKind());
20730 assert(E->getObjectKind() == OK_Ordinary);
20731 return E;
20732 }
20733
20734 ExprResult VisitParenExpr(ParenExpr *E) {
20735 return rebuildSugarExpr(E);
20736 }
20737
20738 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20739 return rebuildSugarExpr(E);
20740 }
20741
20742 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20743 ExprResult SubResult = Visit(E->getSubExpr());
20744 if (SubResult.isInvalid()) return ExprError();
20745
20746 Expr *SubExpr = SubResult.get();
20747 E->setSubExpr(SubExpr);
20748 E->setType(S.Context.getPointerType(SubExpr->getType()));
20749 assert(E->isPRValue());
20750 assert(E->getObjectKind() == OK_Ordinary);
20751 return E;
20752 }
20753
20754 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
20755 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
20756
20757 E->setType(VD->getType());
20758
20759 assert(E->isPRValue());
20760 if (S.getLangOpts().CPlusPlus &&
20761 !(isa<CXXMethodDecl>(VD) &&
20762 cast<CXXMethodDecl>(VD)->isInstance()))
20764
20765 return E;
20766 }
20767
20768 ExprResult VisitMemberExpr(MemberExpr *E) {
20769 return resolveDecl(E, E->getMemberDecl());
20770 }
20771
20772 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20773 return resolveDecl(E, E->getDecl());
20774 }
20775 };
20776}
20777
20778/// Given a function expression of unknown-any type, try to rebuild it
20779/// to have a function type.
20781 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20782 if (Result.isInvalid()) return ExprError();
20783 return S.DefaultFunctionArrayConversion(Result.get());
20784}
20785
20786namespace {
20787 /// A visitor for rebuilding an expression of type __unknown_anytype
20788 /// into one which resolves the type directly on the referring
20789 /// expression. Strict preservation of the original source
20790 /// structure is not a goal.
20791 struct RebuildUnknownAnyExpr
20792 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
20793
20794 Sema &S;
20795
20796 /// The current destination type.
20797 QualType DestType;
20798
20799 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
20800 : S(S), DestType(CastType) {}
20801
20802 ExprResult VisitStmt(Stmt *S) {
20803 llvm_unreachable("unexpected statement!");
20804 }
20805
20806 ExprResult VisitExpr(Expr *E) {
20807 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
20808 << E->getSourceRange();
20809 return ExprError();
20810 }
20811
20812 ExprResult VisitCallExpr(CallExpr *E);
20813 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
20814
20815 /// Rebuild an expression which simply semantically wraps another
20816 /// expression which it shares the type and value kind of.
20817 template <class T> ExprResult rebuildSugarExpr(T *E) {
20818 ExprResult SubResult = Visit(E->getSubExpr());
20819 if (SubResult.isInvalid()) return ExprError();
20820 Expr *SubExpr = SubResult.get();
20821 E->setSubExpr(SubExpr);
20822 E->setType(SubExpr->getType());
20823 E->setValueKind(SubExpr->getValueKind());
20824 assert(E->getObjectKind() == OK_Ordinary);
20825 return E;
20826 }
20827
20828 ExprResult VisitParenExpr(ParenExpr *E) {
20829 return rebuildSugarExpr(E);
20830 }
20831
20832 ExprResult VisitUnaryExtension(UnaryOperator *E) {
20833 return rebuildSugarExpr(E);
20834 }
20835
20836 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
20837 const PointerType *Ptr = DestType->getAs<PointerType>();
20838 if (!Ptr) {
20839 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
20840 << E->getSourceRange();
20841 return ExprError();
20842 }
20843
20844 if (isa<CallExpr>(E->getSubExpr())) {
20845 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
20846 << E->getSourceRange();
20847 return ExprError();
20848 }
20849
20850 assert(E->isPRValue());
20851 assert(E->getObjectKind() == OK_Ordinary);
20852 E->setType(DestType);
20853
20854 // Build the sub-expression as if it were an object of the pointee type.
20855 DestType = Ptr->getPointeeType();
20856 ExprResult SubResult = Visit(E->getSubExpr());
20857 if (SubResult.isInvalid()) return ExprError();
20858 E->setSubExpr(SubResult.get());
20859 return E;
20860 }
20861
20862 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
20863
20864 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
20865
20866 ExprResult VisitMemberExpr(MemberExpr *E) {
20867 return resolveDecl(E, E->getMemberDecl());
20868 }
20869
20870 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
20871 return resolveDecl(E, E->getDecl());
20872 }
20873 };
20874}
20875
20876/// Rebuilds a call expression which yielded __unknown_anytype.
20877ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
20878 Expr *CalleeExpr = E->getCallee();
20879
20880 enum FnKind {
20881 FK_MemberFunction,
20882 FK_FunctionPointer,
20883 FK_BlockPointer
20884 };
20885
20886 FnKind Kind;
20887 QualType CalleeType = CalleeExpr->getType();
20888 if (CalleeType == S.Context.BoundMemberTy) {
20889 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
20890 Kind = FK_MemberFunction;
20891 CalleeType = Expr::findBoundMemberType(CalleeExpr);
20892 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
20893 CalleeType = Ptr->getPointeeType();
20894 Kind = FK_FunctionPointer;
20895 } else {
20896 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
20897 Kind = FK_BlockPointer;
20898 }
20899 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
20900
20901 // Verify that this is a legal result type of a function.
20902 if (DestType->isArrayType() || DestType->isFunctionType()) {
20903 unsigned diagID = diag::err_func_returning_array_function;
20904 if (Kind == FK_BlockPointer)
20905 diagID = diag::err_block_returning_array_function;
20906
20907 S.Diag(E->getExprLoc(), diagID)
20908 << DestType->isFunctionType() << DestType;
20909 return ExprError();
20910 }
20911
20912 // Otherwise, go ahead and set DestType as the call's result.
20913 E->setType(DestType.getNonLValueExprType(S.Context));
20915 assert(E->getObjectKind() == OK_Ordinary);
20916
20917 // Rebuild the function type, replacing the result type with DestType.
20918 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
20919 if (Proto) {
20920 // __unknown_anytype(...) is a special case used by the debugger when
20921 // it has no idea what a function's signature is.
20922 //
20923 // We want to build this call essentially under the K&R
20924 // unprototyped rules, but making a FunctionNoProtoType in C++
20925 // would foul up all sorts of assumptions. However, we cannot
20926 // simply pass all arguments as variadic arguments, nor can we
20927 // portably just call the function under a non-variadic type; see
20928 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20929 // However, it turns out that in practice it is generally safe to
20930 // call a function declared as "A foo(B,C,D);" under the prototype
20931 // "A foo(B,C,D,...);". The only known exception is with the
20932 // Windows ABI, where any variadic function is implicitly cdecl
20933 // regardless of its normal CC. Therefore we change the parameter
20934 // types to match the types of the arguments.
20935 //
20936 // This is a hack, but it is far superior to moving the
20937 // corresponding target-specific code from IR-gen to Sema/AST.
20938
20939 ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
20940 SmallVector<QualType, 8> ArgTypes;
20941 if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
20942 ArgTypes.reserve(E->getNumArgs());
20943 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20944 ArgTypes.push_back(S.Context.getReferenceQualifiedType(E->getArg(i)));
20945 }
20946 ParamTypes = ArgTypes;
20947 }
20948 DestType = S.Context.getFunctionType(DestType, ParamTypes,
20949 Proto->getExtProtoInfo());
20950 } else {
20951 DestType = S.Context.getFunctionNoProtoType(DestType,
20952 FnType->getExtInfo());
20953 }
20954
20955 // Rebuild the appropriate pointer-to-function type.
20956 switch (Kind) {
20957 case FK_MemberFunction:
20958 // Nothing to do.
20959 break;
20960
20961 case FK_FunctionPointer:
20962 DestType = S.Context.getPointerType(DestType);
20963 break;
20964
20965 case FK_BlockPointer:
20966 DestType = S.Context.getBlockPointerType(DestType);
20967 break;
20968 }
20969
20970 // Finally, we can recurse.
20971 ExprResult CalleeResult = Visit(CalleeExpr);
20972 if (!CalleeResult.isUsable()) return ExprError();
20973 E->setCallee(CalleeResult.get());
20974
20975 // Bind a temporary if necessary.
20976 return S.MaybeBindToTemporary(E);
20977}
20978
20979ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
20980 // Verify that this is a legal result type of a call.
20981 if (DestType->isArrayType() || DestType->isFunctionType()) {
20982 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
20983 << DestType->isFunctionType() << DestType;
20984 return ExprError();
20985 }
20986
20987 // Rewrite the method result type if available.
20988 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
20989 assert(Method->getReturnType() == S.Context.UnknownAnyTy);
20990 Method->setReturnType(DestType);
20991 }
20992
20993 // Change the type of the message.
20994 E->setType(DestType.getNonReferenceType());
20996
20997 return S.MaybeBindToTemporary(E);
20998}
20999
21000ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
21001 // The only case we should ever see here is a function-to-pointer decay.
21002 if (E->getCastKind() == CK_FunctionToPointerDecay) {
21003 assert(E->isPRValue());
21004 assert(E->getObjectKind() == OK_Ordinary);
21005
21006 E->setType(DestType);
21007
21008 // Rebuild the sub-expression as the pointee (function) type.
21009 DestType = DestType->castAs<PointerType>()->getPointeeType();
21010
21011 ExprResult Result = Visit(E->getSubExpr());
21012 if (!Result.isUsable()) return ExprError();
21013
21014 E->setSubExpr(Result.get());
21015 return E;
21016 } else if (E->getCastKind() == CK_LValueToRValue) {
21017 assert(E->isPRValue());
21018 assert(E->getObjectKind() == OK_Ordinary);
21019
21020 assert(isa<BlockPointerType>(E->getType()));
21021
21022 E->setType(DestType);
21023
21024 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21025 DestType = S.Context.getLValueReferenceType(DestType);
21026
21027 ExprResult Result = Visit(E->getSubExpr());
21028 if (!Result.isUsable()) return ExprError();
21029
21030 E->setSubExpr(Result.get());
21031 return E;
21032 } else {
21033 llvm_unreachable("Unhandled cast type!");
21034 }
21035}
21036
21037ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
21038 ExprValueKind ValueKind = VK_LValue;
21039 QualType Type = DestType;
21040
21041 // We know how to make this work for certain kinds of decls:
21042
21043 // - functions
21044 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
21045 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
21046 DestType = Ptr->getPointeeType();
21047 ExprResult Result = resolveDecl(E, VD);
21048 if (Result.isInvalid()) return ExprError();
21049 return S.ImpCastExprToType(Result.get(), Type, CK_FunctionToPointerDecay,
21050 VK_PRValue);
21051 }
21052
21053 if (!Type->isFunctionType()) {
21054 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
21055 << VD << E->getSourceRange();
21056 return ExprError();
21057 }
21058 if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
21059 // We must match the FunctionDecl's type to the hack introduced in
21060 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21061 // type. See the lengthy commentary in that routine.
21062 QualType FDT = FD->getType();
21063 const FunctionType *FnType = FDT->castAs<FunctionType>();
21064 const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
21065 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
21066 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21067 SourceLocation Loc = FD->getLocation();
21069 S.Context, FD->getDeclContext(), Loc, Loc,
21070 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21072 false /*isInlineSpecified*/, FD->hasPrototype(),
21073 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21074
21075 if (FD->getQualifier())
21076 NewFD->setQualifierInfo(FD->getQualifierLoc());
21077
21079 for (const auto &AI : FT->param_types()) {
21080 ParmVarDecl *Param =
21081 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21082 Param->setScopeInfo(0, Params.size());
21083 Params.push_back(Param);
21084 }
21085 NewFD->setParams(Params);
21086 DRE->setDecl(NewFD);
21087 VD = DRE->getDecl();
21088 }
21089 }
21090
21091 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
21092 if (MD->isInstance()) {
21093 ValueKind = VK_PRValue;
21095 }
21096
21097 // Function references aren't l-values in C.
21098 if (!S.getLangOpts().CPlusPlus)
21099 ValueKind = VK_PRValue;
21100
21101 // - variables
21102 } else if (isa<VarDecl>(VD)) {
21103 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
21104 Type = RefTy->getPointeeType();
21105 } else if (Type->isFunctionType()) {
21106 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
21107 << VD << E->getSourceRange();
21108 return ExprError();
21109 }
21110
21111 // - nothing else
21112 } else {
21113 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
21114 << VD << E->getSourceRange();
21115 return ExprError();
21116 }
21117
21118 // Modifying the declaration like this is friendly to IR-gen but
21119 // also really dangerous.
21120 VD->setType(DestType);
21121 E->setType(Type);
21122 E->setValueKind(ValueKind);
21123 return E;
21124}
21125
21126/// Check a cast of an unknown-any type. We intentionally only
21127/// trigger this for C-style casts.
21130 ExprValueKind &VK, CXXCastPath &Path) {
21131 // The type we're casting to must be either void or complete.
21132 if (!CastType->isVoidType() &&
21134 diag::err_typecheck_cast_to_incomplete))
21135 return ExprError();
21136
21137 // Rewrite the casted expression from scratch.
21138 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
21139 if (!result.isUsable()) return ExprError();
21140
21141 CastExpr = result.get();
21142 VK = CastExpr->getValueKind();
21143 CastKind = CK_NoOp;
21144
21145 return CastExpr;
21146}
21147
21149 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21150}
21151
21153 Expr *arg, QualType &paramType) {
21154 // If the syntactic form of the argument is not an explicit cast of
21155 // any sort, just do default argument promotion.
21156 ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
21157 if (!castArg) {
21159 if (result.isInvalid()) return ExprError();
21160 paramType = result.get()->getType();
21161 return result;
21162 }
21163
21164 // Otherwise, use the type that was written in the explicit cast.
21165 assert(!arg->hasPlaceholderType());
21166 paramType = castArg->getTypeAsWritten();
21167
21168 // Copy-initialize a parameter of that type.
21169 InitializedEntity entity =
21171 /*consumed*/ false);
21172 return PerformCopyInitialization(entity, callLoc, arg);
21173}
21174
21176 Expr *orig = E;
21177 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
21178 while (true) {
21179 E = E->IgnoreParenImpCasts();
21180 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
21181 E = call->getCallee();
21182 diagID = diag::err_uncasted_call_of_unknown_any;
21183 } else {
21184 break;
21185 }
21186 }
21187
21188 SourceLocation loc;
21189 NamedDecl *d;
21190 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
21191 loc = ref->getLocation();
21192 d = ref->getDecl();
21193 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
21194 loc = mem->getMemberLoc();
21195 d = mem->getMemberDecl();
21196 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
21197 diagID = diag::err_uncasted_call_of_unknown_any;
21198 loc = msg->getSelectorStartLoc();
21199 d = msg->getMethodDecl();
21200 if (!d) {
21201 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
21202 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
21203 << orig->getSourceRange();
21204 return ExprError();
21205 }
21206 } else {
21207 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
21208 << E->getSourceRange();
21209 return ExprError();
21210 }
21211
21212 S.Diag(loc, diagID) << d << orig->getSourceRange();
21213
21214 // Never recoverable.
21215 return ExprError();
21216}
21217
21218/// Check for operands with placeholder types and complain if found.
21219/// Returns ExprError() if there was an error and no recovery was possible.
21222 // C cannot handle TypoExpr nodes on either side of a binop because it
21223 // doesn't handle dependent types properly, so make sure any TypoExprs have
21224 // been dealt with before checking the operands.
21226 if (!Result.isUsable()) return ExprError();
21227 E = Result.get();
21228 }
21229
21230 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
21231 if (!placeholderType) return E;
21232
21233 switch (placeholderType->getKind()) {
21234
21235 // Overloaded expressions.
21236 case BuiltinType::Overload: {
21237 // Try to resolve a single function template specialization.
21238 // This is obligatory.
21239 ExprResult Result = E;
21241 return Result;
21242
21243 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21244 // leaves Result unchanged on failure.
21245 Result = E;
21247 return Result;
21248
21249 // If that failed, try to recover with a call.
21250 tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
21251 /*complain*/ true);
21252 return Result;
21253 }
21254
21255 // Bound member functions.
21256 case BuiltinType::BoundMember: {
21257 ExprResult result = E;
21258 const Expr *BME = E->IgnoreParens();
21259 PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
21260 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21261 if (isa<CXXPseudoDestructorExpr>(BME)) {
21262 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21263 } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
21264 if (ME->getMemberNameInfo().getName().getNameKind() ==
21266 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21267 }
21268 tryToRecoverWithCall(result, PD,
21269 /*complain*/ true);
21270 return result;
21271 }
21272
21273 // ARC unbridged casts.
21274 case BuiltinType::ARCUnbridgedCast: {
21275 Expr *realCast = stripARCUnbridgedCast(E);
21276 diagnoseARCUnbridgedCast(realCast);
21277 return realCast;
21278 }
21279
21280 // Expressions of unknown type.
21281 case BuiltinType::UnknownAny:
21282 return diagnoseUnknownAnyExpr(*this, E);
21283
21284 // Pseudo-objects.
21285 case BuiltinType::PseudoObject:
21286 return checkPseudoObjectRValue(E);
21287
21288 case BuiltinType::BuiltinFn: {
21289 // Accept __noop without parens by implicitly converting it to a call expr.
21290 auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
21291 if (DRE) {
21292 auto *FD = cast<FunctionDecl>(DRE->getDecl());
21293 unsigned BuiltinID = FD->getBuiltinID();
21294 if (BuiltinID == Builtin::BI__noop) {
21295 E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
21296 CK_BuiltinFnToFnPtr)
21297 .get();
21298 return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
21301 }
21302
21303 if (Context.BuiltinInfo.isInStdNamespace(BuiltinID)) {
21304 // Any use of these other than a direct call is ill-formed as of C++20,
21305 // because they are not addressable functions. In earlier language
21306 // modes, warn and force an instantiation of the real body.
21307 Diag(E->getBeginLoc(),
21309 ? diag::err_use_of_unaddressable_function
21310 : diag::warn_cxx20_compat_use_of_unaddressable_function);
21311 if (FD->isImplicitlyInstantiable()) {
21312 // Require a definition here because a normal attempt at
21313 // instantiation for a builtin will be ignored, and we won't try
21314 // again later. We assume that the definition of the template
21315 // precedes this use.
21317 /*Recursive=*/false,
21318 /*DefinitionRequired=*/true,
21319 /*AtEndOfTU=*/false);
21320 }
21321 // Produce a properly-typed reference to the function.
21322 CXXScopeSpec SS;
21323 SS.Adopt(DRE->getQualifierLoc());
21324 TemplateArgumentListInfo TemplateArgs;
21325 DRE->copyTemplateArgumentsInto(TemplateArgs);
21326 return BuildDeclRefExpr(
21327 FD, FD->getType(), VK_LValue, DRE->getNameInfo(),
21328 DRE->hasQualifier() ? &SS : nullptr, DRE->getFoundDecl(),
21329 DRE->getTemplateKeywordLoc(),
21330 DRE->hasExplicitTemplateArgs() ? &TemplateArgs : nullptr);
21331 }
21332 }
21333
21334 Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
21335 return ExprError();
21336 }
21337
21338 case BuiltinType::IncompleteMatrixIdx:
21339 Diag(cast<MatrixSubscriptExpr>(E->IgnoreParens())
21340 ->getRowIdx()
21341 ->getBeginLoc(),
21342 diag::err_matrix_incomplete_index);
21343 return ExprError();
21344
21345 // Expressions of unknown type.
21346 case BuiltinType::OMPArraySection:
21347 Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
21348 return ExprError();
21349
21350 // Expressions of unknown type.
21351 case BuiltinType::OMPArrayShaping:
21352 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_array_shaping_use));
21353
21354 case BuiltinType::OMPIterator:
21355 return ExprError(Diag(E->getBeginLoc(), diag::err_omp_iterator_use));
21356
21357 // Everything else should be impossible.
21358#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21359 case BuiltinType::Id:
21360#include "clang/Basic/OpenCLImageTypes.def"
21361#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21362 case BuiltinType::Id:
21363#include "clang/Basic/OpenCLExtensionTypes.def"
21364#define SVE_TYPE(Name, Id, SingletonId) \
21365 case BuiltinType::Id:
21366#include "clang/Basic/AArch64SVEACLETypes.def"
21367#define PPC_VECTOR_TYPE(Name, Id, Size) \
21368 case BuiltinType::Id:
21369#include "clang/Basic/PPCTypes.def"
21370#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21371#include "clang/Basic/RISCVVTypes.def"
21372#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21373#include "clang/Basic/WebAssemblyReferenceTypes.def"
21374#define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21375#define PLACEHOLDER_TYPE(Id, SingletonId)
21376#include "clang/AST/BuiltinTypes.def"
21377 break;
21378 }
21379
21380 llvm_unreachable("invalid placeholder type!");
21381}
21382
21384 if (E->isTypeDependent())
21385 return true;
21387 return E->getType()->isIntegralOrEnumerationType();
21388 return false;
21389}
21390
21391/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
21394 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
21395 "Unknown Objective-C Boolean value!");
21397 if (!Context.getBOOLDecl()) {
21398 LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
21400 if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
21401 NamedDecl *ND = Result.getFoundDecl();
21402 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
21403 Context.setBOOLDecl(TD);
21404 }
21405 }
21406 if (Context.getBOOLDecl())
21407 BoolT = Context.getBOOLType();
21408 return new (Context)
21409 ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
21410}
21411
21414 SourceLocation RParen) {
21415 auto FindSpecVersion =
21416 [&](StringRef Platform) -> std::optional<VersionTuple> {
21417 auto Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21418 return Spec.getPlatform() == Platform;
21419 });
21420 // Transcribe the "ios" availability check to "maccatalyst" when compiling
21421 // for "maccatalyst" if "maccatalyst" is not specified.
21422 if (Spec == AvailSpecs.end() && Platform == "maccatalyst") {
21423 Spec = llvm::find_if(AvailSpecs, [&](const AvailabilitySpec &Spec) {
21424 return Spec.getPlatform() == "ios";
21425 });
21426 }
21427 if (Spec == AvailSpecs.end())
21428 return std::nullopt;
21429 return Spec->getVersion();
21430 };
21431
21432 VersionTuple Version;
21433 if (auto MaybeVersion =
21434 FindSpecVersion(Context.getTargetInfo().getPlatformName()))
21435 Version = *MaybeVersion;
21436
21437 // The use of `@available` in the enclosing context should be analyzed to
21438 // warn when it's used inappropriately (i.e. not if(@available)).
21440 Context->HasPotentialAvailabilityViolations = true;
21441
21442 return new (Context)
21443 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
21444}
21445
21447 ArrayRef<Expr *> SubExprs, QualType T) {
21448 if (!Context.getLangOpts().RecoveryAST)
21449 return ExprError();
21450
21451 if (isSFINAEContext())
21452 return ExprError();
21453
21454 if (T.isNull() || T->isUndeducedType() ||
21455 !Context.getLangOpts().RecoveryASTType)
21456 // We don't know the concrete type, fallback to dependent type.
21458
21459 return RecoveryExpr::Create(Context, T, Begin, End, SubExprs);
21460}
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3273
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
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.
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:154
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:48
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.
This file declares semantic analysis for CUDA constructs.
CastType
Definition: SemaCast.cpp:47
static Sema::AssignConvertType checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkObjCPointerTypesForAssignment - Compares two objective-c pointer types for assignment compatibil...
Definition: SemaExpr.cpp:9504
static void HandleImmediateInvocations(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec)
Definition: SemaExpr.cpp:18003
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:1944
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:15553
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:10386
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:18943
static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc, Expr *Operand)
Check the validity of an arithmetic pointer operand.
Definition: SemaExpr.cpp:11128
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:15343
static bool isPlaceholderToRemoveAsArg(QualType type)
Is the given type a placeholder that we need to lower out immediately during argument processing?
Definition: SemaExpr.cpp:6311
static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool IsGNUIdiom)
Diagnose invalid arithmetic on a null pointer.
Definition: SemaExpr.cpp:11047
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:9071
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:3400
static QualType checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Return the resulting type when the operands are both pointers.
Definition: SemaExpr.cpp:8383
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:8589
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:12117
static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a function pointer.
Definition: SemaExpr.cpp:11092
static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, BinaryOperator::Opcode Opc)
Definition: SemaExpr.cpp:12067
static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S, VarDecl *VD)
Definition: SemaExpr.cpp:2227
static UnaryOperatorKind ConvertTokenKindToUnaryOpcode(tok::TokenKind Kind)
Definition: SemaExpr.cpp:14821
static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func)
Definition: SemaExpr.cpp:18341
NonConstCaptureKind
Is the given expression (which must be 'const') a reference to a variable which was originally non-co...
Definition: SemaExpr.cpp:13611
@ NCCK_Block
Definition: SemaExpr.cpp:13611
@ NCCK_None
Definition: SemaExpr.cpp:13611
@ NCCK_Lambda
Definition: SemaExpr.cpp:13611
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:10280
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:9553
static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD)
Definition: SemaExpr.cpp:6235
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:2651
static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(Sema &SemaRef, ValueDecl *D, Expr *E)
Definition: SemaExpr.cpp:20156
static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18795
static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType, const Expr *SrcExpr)
Definition: SemaExpr.cpp:17099
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:8975
static Decl * getPredefinedExprDecl(DeclContext *DC)
getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used to determine the value o...
Definition: SemaExpr.cpp:1928
static CXXRecordDecl * LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:16936
static bool IgnoreCommaOperand(const Expr *E, const ASTContext &Context)
Definition: SemaExpr.cpp:14170
static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc, bool IsReal)
Definition: SemaExpr.cpp:4956
static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:12469
static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK, SourceLocation OpLoc, bool IsAfterAmp=false)
CheckIndirectionOperand - Type check unary indirection (prefix '*').
Definition: SemaExpr.cpp:14718
static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind)
Definition: SemaExpr.cpp:4556
static bool ExprLooksBoolean(const Expr *E)
ExprLooksBoolean - Returns true if E looks boolean, i.e.
Definition: SemaExpr.cpp:9050
static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef)
Are we in a context that is potentially constant evaluated per C++20 [expr.const]p12?
Definition: SemaExpr.cpp:18190
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:14877
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:11213
static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Checks compatibility between two pointers and return the resulting type.
Definition: SemaExpr.cpp:8226
static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc, VarDecl *Var, Expr *E, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:19953
static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R)
Definition: SemaExpr.cpp:3425
static bool checkCondition(Sema &S, const Expr *Cond, SourceLocation QuestionLoc)
Return false if the condition expression is valid, true otherwise.
Definition: SemaExpr.cpp:8192
static bool checkForArray(const Expr *E)
Definition: SemaExpr.cpp:12159
static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S, const CallExpr *Call)
Definition: SemaExpr.cpp:6581
static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD, const RecordType *Ty, SourceLocation Loc, SourceRange Range, OriginalExprKind OEK, bool &DiagnosticEmitted)
Definition: SemaExpr.cpp:13795
static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E, bool MightBeOdrUse, llvm::DenseMap< const VarDecl *, int > &RefsMinusAssignments)
Definition: SemaExpr.cpp:20202
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:10327
static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc, ValueDecl *Var, Expr *E)
Definition: SemaExpr.cpp:19921
static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp)
Definition: SemaExpr.cpp:14700
static void EvaluateAndDiagnoseImmediateInvocation(Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate)
Definition: SemaExpr.cpp:17864
static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E, QualType FromType, SourceLocation Loc)
Definition: SemaExpr.cpp:12344
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:9005
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:14975
static QualType handleIntegerConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle integer arithmetic conversions.
Definition: SemaExpr.cpp:1314
static void checkDirectCallValidity(Sema &S, const Expr *Fn, FunctionDecl *Callee, MultiExprArg ArgExprs)
Definition: SemaExpr.cpp:6471
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:9941
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:8507
static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr, QualType PointerTy)
Return false if the NullExpr can be promoted to PointerTy, true otherwise.
Definition: SemaExpr.cpp:8213
static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc, Expr *Pointer, bool BothNull)
Diagnose invalid subraction on a null pointer.
Definition: SemaExpr.cpp:11059
static NamedDecl * getDeclFromExpr(Expr *E)
Definition: SemaExpr.cpp:14960
static bool checkArithmeticOnObjCPointer(Sema &S, SourceLocation opLoc, Expr *op)
Diagnose if arithmetic on the given ObjC pointer is illegal.
Definition: SemaExpr.cpp:5013
static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:9280
static void RemoveNestedImmediateInvocation(Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec, SmallVector< Sema::ImmediateInvocationCandidate, 4 >::reverse_iterator It)
Definition: SemaExpr.cpp:17906
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:15434
static void emitEmptyLookupTypoDiagnostic(const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS, DeclarationName Typo, SourceLocation TypoLoc, ArrayRef< Expr * > Args, unsigned DiagnosticID, unsigned DiagnosticSuggestID)
Definition: SemaExpr.cpp:2373
static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation OpLoc, bool IsInc, bool IsPrefix)
CheckIncrementDecrementOperand - unlike most "Check" methods, this routine doesn't need to call Usual...
Definition: SemaExpr.cpp:14278
static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
Simple conversion between integer and floating point types.
Definition: SemaExpr.cpp:8452
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:8561
static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:10886
static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS, BinaryOperatorKind Opc)
Diagnose some forms of syntactically-obvious tautological comparison.
Definition: SemaExpr.cpp:12173
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:4426
static void DiagnoseBadDivideOrRemainderValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsDiv)
Definition: SemaExpr.cpp:10934
static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source, SmallString< 32 > &Target)
Definition: SemaExpr.cpp:3724
static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn, FunctionDecl *FDecl, ArrayRef< Expr * > Args)
Definition: SemaExpr.cpp:5948
static bool hasAnyExplicitStorageClass(const FunctionDecl *D)
Determine whether a FunctionDecl was ever declared with an explicit storage class.
Definition: SemaExpr.cpp:144
static void DiagnoseBadShiftValues(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType LHSType)
Definition: SemaExpr.cpp:11565
static bool CheckVecStepTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4348
static Sema::AssignConvertType checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType)
checkBlockPointerTypesForAssignment - This routine determines whether two block pointer types are com...
Definition: SemaExpr.cpp:9453
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:1271
static void MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef, const unsigned *const FunctionScopeIndexToStopAt=nullptr)
Directly mark a variable odr-used.
Definition: SemaExpr.cpp:18626
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:11243
static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S)
CheckForModifiableLvalue - Verify that E is a modifiable lvalue.
Definition: SemaExpr.cpp:13859
static ValueDecl * getPrimaryDecl(Expr *E)
getPrimaryDecl - Helper function for CheckAddressOfOperand().
Definition: SemaExpr.cpp:14383
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:160
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:18221
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:11927
static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky precedence.
Definition: SemaExpr.cpp:15491
static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc, Expr *E, unsigned Type)
Diagnose invalid operand for address of operations.
Definition: SemaExpr.cpp:14443
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:1364
static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base)
Definition: SemaExpr.cpp:5027
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:10430
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:18983
static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the left hand of a '||' expr.
Definition: SemaExpr.cpp:15398
static void CheckForNullPointerDereference(Sema &S, Expr *E)
Definition: SemaExpr.cpp:569
static QualType computeConditionalNullability(QualType ResTy, bool IsBin, QualType LHSTy, QualType RHSTy, ASTContext &Ctx)
Compute the nullability of a conditional expression.
Definition: SemaExpr.cpp:9105
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:18309
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:13670
static Expr * BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal, QualType Ty, SourceLocation Loc)
Definition: SemaExpr.cpp:3854
static bool IsTypeModifiable(QualType Ty, bool IsDereference)
Definition: SemaExpr.cpp:13648
static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, ValueDecl *Var, bool &SubCapturesAreNested, QualType &CaptureType, QualType &DeclRefType)
Definition: SemaExpr.cpp:18743
static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc, Expr *Operand)
Emit error if Operand is incomplete pointer type.
Definition: SemaExpr.cpp:11106
static bool CheckExtensionTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4378
static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Definition: SemaExpr.cpp:11760
static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:12387
static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E)
Definition: SemaExpr.cpp:21175
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:1936
static bool checkBlockType(Sema &S, const Expr *E)
Return true if the Expr is block type.
Definition: SemaExpr.cpp:8627
OriginalExprKind
Definition: SemaExpr.cpp:13789
@ OEK_Variable
Definition: SemaExpr.cpp:13790
@ OEK_LValue
Definition: SemaExpr.cpp:13792
@ OEK_Member
Definition: SemaExpr.cpp:13791
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:18875
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:1221
static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc, Expr *Pointer)
Diagnose invalid arithmetic on a void pointer.
Definition: SemaExpr.cpp:11034
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:11666
static void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc, ValueDecl *var)
Definition: SemaExpr.cpp:18702
ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType)
Definition: SemaExpr.cpp:1296
static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompare)
Definition: SemaExpr.cpp:10850
static bool IsReadonlyMessage(Expr *E, Sema &S)
Definition: SemaExpr.cpp:13598
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:19111
static void tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc)
Definition: SemaExpr.cpp:6540
static Sema::AssignConvertType checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType, SourceLocation Loc)
Definition: SemaExpr.cpp:9301
static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange)
Definition: SemaExpr.cpp:4366
static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Look for '&&' in the right hand of a '||' expr.
Definition: SemaExpr.cpp:15419
static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS, const ASTContext &Ctx)
Definition: SemaExpr.cpp:5046
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:1496
static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Emit error when two pointers are incompatible.
Definition: SemaExpr.cpp:11294
static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(const UnresolvedMemberExpr *const UME, Sema &S)
Definition: SemaExpr.cpp:6498
static unsigned GetFixedPointRank(QualType Ty)
Return the rank of a given fixed point or integer type.
Definition: SemaExpr.cpp:1410
static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T, SourceLocation Loc, SourceRange ArgRange, UnaryExprOrTypeTrait TraitKind)
Definition: SemaExpr.cpp:4408
static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc, Expr *LHS, Expr *RHS)
Diagnose invalid arithmetic on two function pointers.
Definition: SemaExpr.cpp:11076
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:8422
static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK)
Definition: SemaExpr.cpp:12305
static void diagnoseXorMisusedAsPow(Sema &S, const ExprResult &XorLHS, const ExprResult &XorRHS, const SourceLocation Loc)
Definition: SemaExpr.cpp:13177
static bool checkOpenCLConditionVector(Sema &S, Expr *Cond, SourceLocation QuestionLoc)
Return false if this is a valid OpenCL condition vector.
Definition: SemaExpr.cpp:8541
static bool IsArithmeticOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:8990
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:1115
static std::pair< ExprResult, ExprResult > CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15008
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:14919
static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE, SourceLocation AssignLoc, const Expr *RHS)
Definition: SemaExpr.cpp:594
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:20780
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:1190
static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS)
Definition: SemaExpr.cpp:11979
static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter, QualType ShorterType, QualType LongerType, bool PromotePrecision)
Definition: SemaExpr.cpp:1143
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:6398
static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc, BindingDecl *BD, Expr *E)
Definition: SemaExpr.cpp:20124
static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind)
Definition: SemaExpr.cpp:1904
static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc)
Definition: SemaExpr.cpp:105
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:1457
static QualType handleComplexConversion(Sema &S, ExprResult &LHS, ExprResult &RHS, QualType LHSType, QualType RHSType, bool IsCompAssign)
Handle arithmetic conversion with complex types.
Definition: SemaExpr.cpp:1166
static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:14242
static bool canCaptureVariableByCopy(ValueDecl *Var, const ASTContext &Context)
Definition: SemaExpr.cpp:19085
static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc, Expr *LHSExpr, Expr *RHSExpr)
Diagnose invalid arithmetic on two void pointers.
Definition: SemaExpr.cpp:11024
static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Diagnose bad pointer comparisons.
Definition: SemaExpr.cpp:11916
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:15031
@ ConstMethod
Definition: SemaExpr.cpp:13661
@ ConstUnknown
Definition: SemaExpr.cpp:13663
@ ConstVariable
Definition: SemaExpr.cpp:13659
@ NestedConstMember
Definition: SemaExpr.cpp:13662
@ ConstMember
Definition: SemaExpr.cpp:13660
@ ConstFunction
Definition: SemaExpr.cpp:13658
static bool isObjCObjectLiteral(ExprResult &E)
Definition: SemaExpr.cpp:11966
static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E)
Definition: SemaExpr.cpp:13612
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:8357
static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15463
static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc, Expr *SubExpr, StringRef Shift)
Definition: SemaExpr.cpp:15449
static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc, ExprResult &LHS, ExprResult &RHS, bool IsError)
Definition: SemaExpr.cpp:11956
static void EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc, BinaryOperator *Bop)
It accepts a '&&' expr that is inside a '||' one.
Definition: SemaExpr.cpp:15386
static void captureVariablyModifiedType(ASTContext &Context, QualType T, CapturingScopeInfo *CSI)
Definition: SemaExpr.cpp:4622
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:10348
static DeclContext * getParentOfCapturingContextOrNull(DeclContext *DC, ValueDecl *Var, SourceLocation Loc, const bool Diagnose, Sema &S)
Definition: SemaExpr.cpp:18776
static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T)
Definition: SemaExpr.cpp:15736
static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr, SourceLocation Loc, Sema &Sema)
Definition: SemaExpr.cpp:13987
static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13407
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:19537
static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD, SourceLocation Loc)
Require that all of the parameter types of function be complete.
Definition: SemaExpr.cpp:18255
static bool isScopedEnumerationType(QualType T)
Definition: SemaExpr.cpp:11559
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:11160
static bool breakDownVectorType(QualType type, uint64_t &len, QualType &eltType)
Definition: SemaExpr.cpp:7693
This file declares semantic analysis for OpenMP constructs and clauses.
static bool isInvalid(LocType Loc, bool *Invalid)
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
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
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
APSInt & getInt()
Definition: APValue.h:423
bool hasValue() const
Definition: APValue.h:399
bool isInt() const
Definition: APValue.h:401
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition: APValue.cpp:946
virtual void HandleCXXImplicitFunctionInstantiation(FunctionDecl *D)
Invoked when a function is implicitly instantiated.
Definition: ASTConsumer.h:82
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
CanQualType AccumTy
Definition: ASTContext.h:1104
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:1073
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2756
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:1121
CanQualType LongTy
Definition: ASTContext.h:1100
unsigned getIntWidth(QualType T) const
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
CanQualType Int128Ty
Definition: ASTContext.h:1100
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 areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS, const ObjCObjectPointerType *RHS, bool ForCompare)
ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an ObjCQualifiedIDType.
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:2117
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:648
int getIntegerTypeOrder(QualType LHS, QualType RHS) const
Return the highest ranked integer type, see C99 6.3.1.8p1.
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:2131
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
CanQualType ShortAccumTy
Definition: ASTContext.h:1104
QualType getCorrespondingSignedFixedPointType(QualType Ty) const
CanQualType FloatTy
Definition: ASTContext.h:1103
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2563
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2579
CanQualType DoubleTy
Definition: ASTContext.h:1103
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:1103
CanQualType Char16Ty
Definition: ASTContext.h:1098
QualType getObjCSelRedefinitionType() const
Retrieve the type that 'SEL' has been defined to, which may be different from the built-in 'SEL' if '...
Definition: ASTContext.h:1889
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
CanQualType VoidPtrTy
Definition: ASTContext.h:1118
QualType getReferenceQualifiedType(const Expr *e) const
getReferenceQualifiedType - Given an expr, will return the type for that expression,...
bool isObjCSelType(QualType T) const
Definition: ASTContext.h:2900
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:1119
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:1589
CanQualType WideCharTy
Definition: ASTContext.h:1095
IdentifierTable & Idents
Definition: ASTContext.h:644
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:646
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:775
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...
TypedefDecl * getBOOLDecl() const
Retrieve declaration of 'BOOL' typedef.
Definition: ASTContext.h:2093
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>.
void setBOOLDecl(TypedefDecl *TD)
Save declaration of 'BOOL' typedef.
Definition: ASTContext.h:2098
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:1092
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:1103
CanQualType UnsignedLongTy
Definition: ASTContext.h:1101
llvm::DenseSet< const FunctionDecl * > CUDAImplicitHostDeviceFunUsedByDevice
Keep track of CUDA/HIP implicit host device functions used on device side in device compilation.
Definition: ASTContext.h:1169
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:1107
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
QualType getBOOLType() const
type of 'BOOL' type.
Definition: ASTContext.h:2103
CanQualType BoundMemberTy
Definition: ASTContext.h:1119
CanQualType CharTy
Definition: ASTContext.h:1093
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:1100
llvm::DenseSet< const VarDecl * > CUDADeviceVarODRUsedByHost
Keep track of CUDA/HIP device-side variables ODR-used by host code.
Definition: ASTContext.h:1161
CanQualType PseudoObjectTy
Definition: ASTContext.h:1121
CanQualType Float16Ty
Definition: ASTContext.h:1117
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2155
bool areComparableObjCPointerTypes(QualType LHS, QualType RHS)
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType ObjCBuiltinBoolTy
Definition: ASTContext.h:1123
CanQualType OverloadTy
Definition: ASTContext.h:1119
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:2309
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2062
llvm::DenseSet< const ValueDecl * > CUDAExternalDeviceDeclODRUsedByHost
Keep track of CUDA/HIP external kernels or device variables ODR-used by host code.
Definition: ASTContext.h:1165
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2606
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:2329
CanQualType BuiltinFnTy
Definition: ASTContext.h:1120
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType VoidTy
Definition: ASTContext.h:1091
CanQualType UnsignedCharTy
Definition: ASTContext.h:1101
CanQualType UnsignedIntTy
Definition: ASTContext.h:1101
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:1876
CanQualType UnknownAnyTy
Definition: ASTContext.h:1119
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1102
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:1567
QualType getObjCIdRedefinitionType() const
Retrieve the type that id has been defined to, which may be different from the built-in id if id has ...
Definition: ASTContext.h:1863
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:1100
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:1107
CanQualType LongAccumTy
Definition: ASTContext.h:1105
CanQualType Char32Ty
Definition: ASTContext.h:1099
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:757
CanQualType LongFractTy
Definition: ASTContext.h:1107
CanQualType IncompleteMatrixIdxTy
Definition: ASTContext.h:1129
std::optional< CharUnits > getTypeSizeInCharsIfKnown(QualType Ty) const
Definition: ASTContext.h:2348
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:1100
QualType getCorrespondingSignedType(QualType T) const
unsigned getTargetAddressSpace(LangAS AS) const
QualType getWideCharType() const
Return the type of wide characters.
Definition: ASTContext.h:1792
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:1998
unsigned char getFixedPointScale(QualType Ty) const
QualType adjustStringLiteralBaseType(QualType StrLTy) const
CanQualType Char8Ty
Definition: ASTContext.h:1097
bool hasCvrSimilarType(QualType T1, QualType T2)
Determine if two types are similar, ignoring only CVR qualifiers.
CanQualType HalfTy
Definition: ASTContext.h:1115
bool isDependenceAllowed() const
Definition: ASTContext.h:781
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:2333
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:4338
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2664
SourceLocation getExprLoc() const LLVM_READONLY
Definition: Expr.h:2719
Wrapper for source info for arrays.
Definition: TypeLoc.h:1561
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3308
ArraySizeModifier getSizeModifier() const
Definition: Type.h:3322
QualType getElementType() const
Definition: Type.h:3320
AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2] This AST node provides support ...
Definition: Expr.h:6234
Attr - This represents one attribute.
Definition: Attr.h:42
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:5449
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5771
One specifier in an @available expression.
Definition: Availability.h:31
StringRef getPlatform() const
Definition: Availability.h:53
VersionTuple getVersion() const
Definition: Availability.h:52
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4241
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3840
Expr * getLHS() const
Definition: Expr.h:3889
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition: Expr.cpp:2181
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3939
bool isComparisonOp() const
Definition: Expr.h:3940
StringRef getOpcodeStr() const
Definition: Expr.h:3905
bool isRelationalOp() const
Definition: Expr.h:3934
SourceLocation getOperatorLoc() const
Definition: Expr.h:3881
bool isCompoundAssignmentOp() const
Definition: Expr.h:3983
bool isMultiplicativeOp() const
Definition: Expr.h:3924
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition: Expr.cpp:2134
bool isShiftOp() const
Definition: Expr.h:3928
Expr * getRHS() const
Definition: Expr.h:3891
bool isEqualityOp() const
Definition: Expr.h:3937
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:4781
bool isBitwiseOp() const
Definition: Expr.h:3931
bool isAdditiveOp() const
Definition: Expr.h:3926
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:2206
Opcode getOpcode() const
Definition: Expr.h:3884
bool isAssignmentOp() const
Definition: Expr.h:3978
static Opcode getOverloadedOpcode(OverloadedOperatorKind OO)
Retrieve the binary opcode that corresponds to the given overloaded operator.
Definition: Expr.cpp:2143
static bool isBitwiseOp(Opcode Opc)
Definition: Expr.h:3930
A binding in a decomposition declaration.
Definition: DeclCXX.h:4104
A class which contains all the information about a particular captured value.
Definition: Decl.h:4501
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4495
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.cpp:5230
void setSignatureAsWritten(TypeSourceInfo *Sig)
Definition: Decl.h:4577
void setBlockMissingReturnType(bool val=true)
Definition: Decl.h:4634
void setIsVariadic(bool value)
Definition: Decl.h:4571
SourceLocation getCaretLocation() const
Definition: Decl.h:4568
void setBody(CompoundStmt *B)
Definition: Decl.h:4575
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:4581
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
Definition: Decl.cpp:5241
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5417
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6173
Pointer to a block type.
Definition: Type.h:3139
This class is used for builtin types like 'int'.
Definition: Type.h:2771
bool isSVEBool() const
Definition: Type.h:2842
Kind getKind() const
Definition: Type.h:2813
bool hasPtrArgsOrResult(unsigned ID) const
Determines whether this builtin has a result or any arguments which are pointer types.
Definition: Builtins.h:209
llvm::StringRef getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:103
bool hasCustomTypechecking(unsigned ID) const
Determines whether this builtin has custom typechecking.
Definition: Builtins.h:196
bool isInStdNamespace(unsigned ID) const
Determines whether this builtin is a C++ standard library function that lives in (possibly-versioned)...
Definition: Builtins.h:182
bool isDirectlyAddressable(unsigned ID) const
Determines whether this builtin can have its address taken with no special action required.
Definition: Builtins.h:188
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:1858
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:1540
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1603
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2532
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2859
bool isLambdaToBlockPointerConversion() const
Determine whether this conversion function is a conversion from a lambda closure type to a block poin...
Definition: DeclCXX.cpp:2902
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2297
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1264
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition: ExprCXX.cpp:969
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1371
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:1023
Expr * getExpr()
Get the initialization expression that will be used.
Definition: ExprCXX.cpp:1035
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:1484
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2796
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2057
bool isVirtual() const
Definition: DeclCXX.h:2112
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2183
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:2291
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:1225
bool hasAnyDependentBases() const
Determine whether this class has any dependent base classes which are not the current instantiation.
Definition: DeclCXX.cpp:568
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:612
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1929
bool hasDefinition() const
Definition: DeclCXX.h:571
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:523
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:73
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:214
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:126
SourceRange getRange() const
Definition: DeclSpec.h:79
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:83
bool isSet() const
Deprecated.
Definition: DeclSpec.h:227
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:152
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:94
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:212
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:207
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
Represents the this expression in C++.
Definition: ExprCXX.h:1148
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2820
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3011
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
Definition: Expr.h:3024
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:1494
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2990
Expr * getCallee()
Definition: Expr.h:2970
void computeDependence()
Compute and set dependence bits.
Definition: Expr.h:3030
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition: Expr.h:2998
Expr ** getArgs()
Retrieve the call arguments.
Definition: Expr.h:3001
void setNumArgsUnsafe(unsigned NewNumArgs)
Bluntly set a new number of arguments without doing any checks whatsoever.
Definition: Expr.h:3052
void setCallee(Expr *F)
Definition: Expr.h:2972
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
Definition: Expr.h:3043
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:3483
CastKind getCastKind() const
Definition: Expr.h:3527
const char * getCastKindName() const
Definition: Expr.h:3531
void setSubExpr(Expr *E)
Definition: Expr.h:3535
Expr * getSubExpr()
Definition: Expr.h:3533
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:1610
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4558
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:2876
QualType getElementType() const
Definition: Type.h:2886
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:4803
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3413
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
bool body_empty() const
Definition: Stmt.h:1650
Stmt * getStmtExprResult()
Definition: Stmt.h:1723
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4179
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3346
llvm::APInt getSize() const
Return the constant array size as an APInt.
Definition: Type.h:3402
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3422
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1072
static ConstantResultStorageKind getStorageKind(const APValue &Value)
Definition: Expr.cpp:302
void MoveIntoResult(APValue &Value, const ASTContext &Context)
Definition: Expr.cpp:378
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:1122
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:350
bool isImmediateInvocation() const
Definition: Expr.h:1144
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:3957
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition: Type.h:3978
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition: Type.h:3975
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:4499
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:1262
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:1371
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1438
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2068
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2193
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1264
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1784
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1231
bool isRecord() const
Definition: DeclBase.h:2148
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1920
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1698
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1567
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1946
bool isFunctionOrMethod() const
Definition: DeclBase.h:2120
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1215
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1334
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
NamedDecl * getFoundDecl()
Get the NamedDecl through which this reference occurred.
Definition: Expr.h:1365
bool hasExplicitTemplateArgs() const
Determines whether this declaration reference was followed by an explicit template argument list.
Definition: Expr.h:1409
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition: Expr.h:1458
void setDecl(ValueDecl *NewD)
Definition: Expr.cpp:544
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments (if present) into the given structure.
Definition: Expr.h:1413
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:551
DeclarationNameInfo getNameInfo() const
Definition: Expr.h:1332
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition: Expr.h:1381
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:488
bool hasQualifier() const
Determine whether this declaration reference was preceded by a C++ nested-name-specifier,...
Definition: Expr.h:1343
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
Definition: Expr.h:1347
ValueDecl * getDecl()
Definition: Expr.h:1328
SourceLocation getLocation() const
Definition: Expr.h:1336
NestedNameSpecifier * getQualifier() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name.
Definition: Expr.h:1355
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
T * getAttr() const
Definition: DeclBase.h:581
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:601
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:709
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:545
bool isInvalidDecl() const
Definition: DeclBase.h:596
SourceLocation getLocation() const
Definition: DeclBase.h:447
void setReferenced(bool R=true)
Definition: DeclBase.h:631
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:941
DeclContext * getDeclContext()
Definition: DeclBase.h:456
bool hasAttr() const
Definition: DeclBase.h:585
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:970
Kind getKind() const
Definition: DeclBase.h:450
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
bool isDependentName() const
Determines whether the name itself is dependent, e.g., because it involves a C++ type that is itself ...
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:822
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1997
NestedNameSpecifierLoc getQualifierLoc() const
Retrieve the nested-name-specifier (with source-location information) that qualifies the name of this...
Definition: Decl.h:836
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1898
DeclaratorContext getContext() const
Definition: DeclSpec.h:2070
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:2081
bool isInvalidType() const
Definition: DeclSpec.h:2712
const IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2328
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:482
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:690
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2323
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
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:5365
EnumDecl * getDecl() const
Definition: Type.h:5372
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3730
QualType getTypeAsWritten() const
getTypeAsWritten - Returns the type that this expression is casting to, as written in the source code...
Definition: Expr.h:3757
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1397
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:3086
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:3015
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:3064
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:3059
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3047
Expr * IgnoreConversionOperatorSingleStep() LLVM_READONLY
Skip conversion operators.
Definition: Expr.cpp:3068
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:3055
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:3279
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition: Expr.h:821
@ NPC_NeverValueDependent
Specifies that the expression should never be value-dependent.
Definition: Expr.h:817
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition: Expr.h:825
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:3556
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:3039
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
Definition: Expr.h:792
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition: Expr.h:801
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
Definition: Expr.h:804
@ NPCK_CXX11_nullptr
Expression is a C++11 nullptr.
Definition: Expr.h:807
@ NPCK_NotNull
Expression is not a Null pointer constant.
Definition: Expr.h:794
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:3918
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
Definition: Expr.cpp:266
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
Definition: Expr.h:454
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
static bool isSameComparisonOperand(const Expr *E1, const Expr *E2)
Checks that the two Expr's will refer to the same value as a comparison operand.
Definition: Expr.cpp:4170
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:6113
ExtVectorType - Extended vector type.
Definition: Type.h:3851
Represents difference between two FPOptions values.
Definition: LangOptions.h:908
bool isFPConstrained() const
Definition: LangOptions.h:836
Represents a member of a struct/union/class.
Definition: Decl.h:3058
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3149
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3219
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3271
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
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:134
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
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:97
static FixedPointLiteral * CreateFromRawInt(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l, unsigned Scale)
Definition: Expr.cpp:999
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1078
FullExpr - Represents a "full-expression" node.
Definition: Expr.h:1039
const Expr * getSubExpr() const
Definition: Expr.h:1052
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:1971
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2707
unsigned getMinRequiredArguments() const
Returns the minimum number of arguments needed to call this function.
Definition: Decl.cpp:3713
bool isImmediateFunction() const
Definition: Decl.cpp:3288
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3873
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3632
bool hasCXXExplicitFunctionObjectParameter() const
Definition: Decl.cpp:3731
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2831
QualType getReturnType() const
Definition: Decl.h:2755
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2684
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2406
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3492
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:2161
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2843
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3979
bool isConsteval() const
Definition: Decl.h:2445
size_t param_size() const
Definition: Decl.h:2700
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3156
SourceRange getParametersSourceRange() const
Attempt to compute an informative source range covering the function parameters, including the ellips...
Definition: Decl.cpp:3889
QualType getCallResultType() const
Determine the type of an expression that calls this function.
Definition: Decl.h:2791
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4606
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition: ExprCXX.h:4636
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4446
QualType desugar() const
Definition: Type.h:4913
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition: Type.h:4891
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
Definition: Type.h:4705
bool isParamConsumed(unsigned I) const
Definition: Type.h:4905
unsigned getNumParams() const
Definition: Type.h:4679
QualType getParamType(unsigned i) const
Definition: Type.h:4681
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4802
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4690
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4686
ArrayRef< QualType > param_types() const
Definition: Type.h:4834
Declaration of a template function.
Definition: DeclTemplate.h:958
unsigned getNumParams() const
Definition: TypeLoc.h:1500
ParmVarDecl * getParam(unsigned i) const
Definition: TypeLoc.h:1506
SourceLocation getLocalRangeEnd() const
Definition: TypeLoc.h:1452
TypeLoc getReturnLoc() const
Definition: TypeLoc.h:1509
SourceLocation getLocalRangeBegin() const
Definition: TypeLoc.h:1444
A class which abstracts out some details necessary for making a call.
Definition: Type.h:4157
bool getCmseNSCall() const
Definition: Type.h:4207
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:4231
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4046
ExtInfo getExtInfo() const
Definition: Type.h:4375
bool getNoReturnAttr() const
Determine whether this function type includes the GNU noreturn attribute.
Definition: Type.h:4371
QualType getReturnType() const
Definition: Type.h:4363
bool getCmseNSCallAttr() const
Definition: Type.h:4373
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition: Type.h:4387
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4633
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:4470
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:1712
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3655
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition: Overload.h:543
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3342
Describes an C or C++ initializer list.
Definition: Expr.h:4847
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:8591
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:977
Represents the declaration of a label.
Definition: Decl.h:499
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1948
CXXMethodDecl * getCallOperator() const
Retrieve the function call operator associated with this lambda expression.
Definition: ExprCXX.cpp:1336
FPEvalMethodKind
Possible float expression evaluation method choices.
Definition: LangOptions.h:281
@ FEM_Extended
Use extended type for fp arithmetic.
Definition: LangOptions.h:290
@ FEM_Double
Use the type double for fp arithmetic.
Definition: LangOptions.h:288
@ 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:295
@ FEM_Source
Use the declared type for fp arithmetic.
Definition: LangOptions.h:286
@ 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:454
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:489
bool isSubscriptPointerArithmetic() const
Definition: LangOptions.h:613
bool isSignedOverflowDefined() const
Definition: LangOptions.h:609
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:1024
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:310
Represents the results of name lookup.
Definition: Lookup.h:46
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition: Lookup.h:603
DeclClass * getAsSingle() const
Definition: Lookup.h:556
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:662
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:566
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:573
LookupResultKind getResultKind() const
Definition: Lookup.h:344
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:632
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:4286
MS property subscript expression.
Definition: ExprCXX.h:1000
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:2742
Represents a matrix type, as defined in the Matrix Types clang extensions.
Definition: Type.h:3921
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition: Type.h:3935
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3172
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition: Expr.h:3361
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3255
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:1754
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition: Expr.h:3390
Expr * getBase() const
Definition: Expr.h:3249
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:1798
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:638
This represents a decl that may have a name.
Definition: Decl.h:249
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:462
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
std::string getQualifiedNameAsString() const
Definition: Decl.cpp:1683
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.cpp:1200
bool isExternallyVisible() const
Definition: Decl.h:408
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:372
Represent a C++ namespace.
Definition: Decl.h:547
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,...
A runtime availability query.
Definition: ExprObjC.h:1696
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:87
Represents an ObjC class declaration.
Definition: DeclObjC.h:1152
ObjCIvarDecl * lookupInstanceVariable(IdentifierInfo *IVarName, ObjCInterfaceDecl *&ClassDeclared)
Definition: DeclObjC.cpp:637
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1525
ivar_iterator ivar_begin() const
Definition: DeclObjC.h:1450
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:352
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6742
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition: ExprObjC.h:1491
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1948
AccessControl getAccessControl() const
Definition: DeclObjC.h:1996
QualType getUsageType(QualType objectType) const
Retrieve the type of this instance variable when viewed as a member of a specific object type.
Definition: DeclObjC.cpp:1898
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:945
const ObjCMethodDecl * getMethodDecl() const
Definition: ExprObjC.h:1356
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
bool isInstanceMethod() const
Definition: DeclObjC.h:426
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
Definition: DeclObjC.cpp:1052
QualType getReturnType() const
Definition: DeclObjC.h:329
bool isClassMethod() const
Definition: DeclObjC.h:434
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1210
Represents a pointer to an Objective C object.
Definition: Type.h:6798
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition: Type.h:6873
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:6856
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition: Type.h:6850
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1787
qual_range quals() const
Definition: Type.h:6917
Represents a class type in Objective C.
Definition: Type.h:6544
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:729
static ObjCPropertyDecl * findPropertyDecl(const DeclContext *DC, const IdentifierInfo *propertyID, ObjCPropertyQueryKind queryKind)
Lookup a property by name in the specified DeclContext.
Definition: DeclObjC.cpp:179
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2079
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:1657
Helper class for OffsetOfExpr.
Definition: Expr.h:2359
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:1168
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:980
@ CSK_Normal
Normal lookup.
Definition: Overload.h:984
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition: Overload.h:1153
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:2976
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition: ExprCXX.h:3036
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:2130
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2149
const Expr * getSubExpr() const
Definition: Expr.h:2145
Expr * getExpr(unsigned Init)
Definition: Expr.h:5655
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4723
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5653
SourceLocation getLParenLoc() const
Definition: Expr.h:5670
SourceLocation getRParenLoc() const
Definition: Expr.h:5671
Represents a parameter to a function.
Definition: Decl.h:1761
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1890
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1794
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1894
QualType getOriginalType() const
Definition: Decl.cpp:2924
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:2915
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3016
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2929
QualType getPointeeType() const
Definition: Type.h:2939
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition: Expr.cpp:638
static std::string ComputeName(PredefinedIdentKind IK, const Decl *CurrentDecl, bool ForceElaboratedPrinting=false)
Definition: Expr.cpp:678
SourceLocation getLastFPEvalPragmaLocation() const
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token's location and length to ...
LangOptions::FPEvalMethodKind getCurrentFPEvalMethod() const
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
SourceManager & getSourceManager() const
bool isMacroDefined(StringRef Id)
const TargetInfo & getTargetInfo() const
char getSpellingOfSingleCharacterNumericConstant(const Token &Tok, bool *Invalid=nullptr) const
Given a Token Tok that is a numeric constant with length 1, return the character.
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:6305
A (possibly-)qualified type.
Definition: Type.h:738
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:7233
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:7238
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:7296
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3454
@ DK_nontrivial_c_struct
Definition: Type.h:1317
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2810
QualType withConst() const
Definition: Type.h:952
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:949
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition: Type.h:7331
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:805
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7149
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7275
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:7290
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:7189
bool isAddressSpaceOverlapping(QualType T) const
Returns true if address space qualifiers overlap with T address space qualifiers.
Definition: Type.h:1209
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:2569
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1230
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:7350
QualType getCanonicalType() const
Definition: Type.h:7201
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7243
bool isWebAssemblyReferenceType() const
Returns true if it is a WebAssembly Reference Type.
Definition: Type.cpp:2828
QualType withCVRQualifiers(unsigned CVR) const
Definition: Type.h:972
bool isCForbiddenLValueType() const
Determine whether expressions of the given type are forbidden from being lvalues in C.
Definition: Type.h:7357
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7222
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:7270
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition: Type.cpp:1618
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1324
bool isCanonical() const
Definition: Type.h:7206
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:1102
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1125
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2561
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7181
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:7284
The collection of all-type qualifiers we support.
Definition: Type.h:148
unsigned getCVRQualifiers() const
Definition: Type.h:296
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:303
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:176
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:179
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:182
void removeObjCLifetime()
Definition: Type.h:359
void removeAddressSpace()
Definition: Type.h:404
void addConst()
Definition: Type.h:268
void setAddressSpace(LangAS space)
Definition: Type.h:399
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B)
Returns true if address space A is equal to or a superset of B.
Definition: Type.h:496
ObjCLifetime getObjCLifetime() const
Definition: Type.h:353
Qualifiers withoutObjCLifetime() const
Definition: Type.h:341
Qualifiers withoutObjCGCAttr() const
Definition: Type.h:336
bool compatiblyIncludes(Qualifiers other) const
Determines if these qualifiers compatibly include another set.
Definition: Type.h:533
LangAS getAddressSpace() const
Definition: Type.h:379
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition: Type.h:554
Represents a struct/union/class.
Definition: Decl.h:4169
field_range fields() const
Definition: Decl.h:4375
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5339
RecordDecl * getDecl() const
Definition: Type.h:5349
static RecoveryExpr * Create(ASTContext &Ctx, QualType T, SourceLocation BeginLoc, SourceLocation EndLoc, ArrayRef< Expr * > SubExprs)
Definition: Expr.cpp:5104
A class that does preorder or postorder depth-first traversal on the entire Clang AST and visits each...
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3170
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:259
@ 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:56
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:706
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition: SemaCUDA.cpp:136
bool CheckCall(SourceLocation Loc, FunctionDecl *Callee)
Check whether we're allowed to call Callee from the current context.
Definition: SemaCUDA.cpp:882
@ CVT_Host
Emitted on device side with a shadow variable on host side.
Definition: SemaCUDA.h:110
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:369
void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc=SourceLocation())
Check declaration inside target region.
const ValueDecl * getOpenMPDeclareMapperVarName() const
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:6552
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
Definition: Sema.h:9547
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:5776
virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc)=0
virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T)
Definition: SemaExpr.cpp:17440
virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc)
Definition: SemaExpr.cpp:17446
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
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:14842
void DefineImplicitLambdaToFunctionPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv)
Define the "body" of the conversion from a lambda object to a function pointer.
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6794
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
std::optional< ExpressionEvaluationContextRecord::InitializationContext > InnermostDeclarationWithDelayedImmediateInvocations() const
Definition: Sema.h:6309
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition: Sema.h:10239
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:698
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args=std::nullopt, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2476
QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc)
FindCompositeObjCPointerType - Helper method to find composite type of two objective-c pointer types ...
Definition: SemaExpr.cpp:8833
void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr)
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:16070
bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:6372
ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val)
Definition: SemaExpr.cpp:3848
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15746
bool isValidRVVBitcast(QualType srcType, QualType destType)
Are the two types RVV-bitcast-compatible types? I.e.
Definition: SemaExpr.cpp:7739
bool isAlwaysConstantEvaluatedContext() const
Definition: Sema.h:6279
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:813
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Definition: SemaDecl.cpp:15291
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:6365
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7376
@ LookupObjCImplicitSelfParam
Look up implicit 'self' parameter of an objective-c method.
Definition: Sema.h:7415
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:7384
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:423
ExprResult ActOnConstantExpression(ExprResult Res)
Definition: SemaExpr.cpp:19883
QualType CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13485
VariadicCallType
Definition: Sema.h:2013
@ VariadicDoesNotApply
Definition: Sema.h:2018
@ VariadicFunction
Definition: Sema.h:2014
@ VariadicMethod
Definition: Sema.h:2016
@ VariadicConstructor
Definition: Sema.h:2017
@ VariadicBlock
Definition: Sema.h:2015
ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr)
Definition: SemaExpr.cpp:7223
bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose=true)
@ NTCUC_CompoundLiteral
Definition: Sema.h:3012
@ NTCUC_Assignment
Definition: Sema.h:3010
@ NTCUC_FunctionReturn
Definition: Sema.h:3002
@ NTCUC_LValueToRValueVolatile
Definition: Sema.h:3016
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:7767
bool isSelfExpr(Expr *RExpr)
Private Helper predicate to check for 'self'.
ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV)
Definition: SemaExpr.cpp:3110
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl)
Defines an implicitly-declared move assignment operator.
void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs)
Decomposes the given name into a DeclarationNameInfo, its location, and possibly a list of template a...
Definition: SemaExpr.cpp:2351
bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param)
SemaOpenMP & OpenMP()
Definition: Sema.h:1013
void ActOnStartStmtExpr()
Definition: SemaExpr.cpp:16090
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:17732
void ActOnStmtExprError()
Definition: SemaExpr.cpp:16096
DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
Definition: SemaExpr.cpp:3037
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:1561
void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE)
Definition: SemaExpr.cpp:12496
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:16553
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:12187
unsigned CapturingFunctionScopes
Track the number of currently active capturing scopes.
Definition: Sema.h:814
SemaCUDA & CUDA()
Definition: Sema.h:998
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17666
ObjCMethodDecl * LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false)
LookupInstanceMethodInGlobalPool - Returns the method and warns if there are multiple signatures.
Definition: Sema.h:12450
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:20632
ConditionKind
Definition: Sema.h:5898
@ 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'.
bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC)
Require that the context specified by SS be complete.
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:2692
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:807
bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType)
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:2245
Preprocessor & getPreprocessor() const
Definition: Sema.h:526
Scope * getScopeForContext(DeclContext *Ctx)
Determines the active Scope associated with the given declaration context.
Definition: Sema.cpp:2107
QualType GetSignedSizelessVectorType(QualType V)
Definition: SemaExpr.cpp:13059
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:6441
ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3788
DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD)
Definition: Sema.h:6353
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:18696
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:17451
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
Definition: SemaExpr.cpp:6846
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:10522
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:1420
bool isValidSveBitcast(QualType srcType, QualType destType)
Are the two types SVE-bitcast-compatible types? I.e.
Definition: SemaExpr.cpp:7718
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.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
Definition: SemaExpr.cpp:12025
void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables=false, ArrayRef< const Expr * > StopAt=std::nullopt)
Mark any declarations that appear within this expression or any potentially-evaluated subexpressions ...
Definition: SemaExpr.cpp:20417
ObjCMethodDecl * LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance)
LookupMethodInQualifiedType - Lookups up a method in protocol qualifier list of a qualified objective...
ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth)
Definition: SemaExpr.cpp:16109
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.
ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16762
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:1499
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:796
ExprResult CheckUnevaluatedOperand(Expr *E)
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but will create a trap if the resul...
Definition: SemaExpr.cpp:1046
void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc)
Definition: SemaExpr.cpp:14193
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
Definition: SemaExpr.cpp:5226
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
std::vector< Token > ExpandFunctionLocalPredefinedMacros(ArrayRef< Token > Toks)
Definition: SemaExpr.cpp:2003
bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind)
Definition: SemaExpr.cpp:7861
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
Definition: SemaExpr.cpp:14483
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:15278
ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond)
Definition: SemaStmt.cpp:1057
ASTContext & Context
Definition: Sema.h:858
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:6266
bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy)
Definition: SemaCast.cpp:2690
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:10217
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:20428
@ ACR_okay
Definition: Sema.h:12402
QualType CheckShiftOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:11852
ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI=nullptr)
BuildQualifiedDeclarationNameExpr - Build a C++ qualified declaration name, generally during template...
Definition: SemaExpr.cpp:2946
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:524
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:8128
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...
ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS)
bool CheckCaseExpression(Expr *E)
Definition: SemaExpr.cpp:21383
bool LookupBuiltin(LookupResult &R)
Lookup a builtin function, when name lookup would otherwise fail.
Definition: SemaLookup.cpp:918
QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign)
Type checking for matrix binary operators.
Definition: SemaExpr.cpp:13324
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:2635
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:5790
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1521
void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions)
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
void CleanupVarDeclMarking()
Definition: SemaExpr.cpp:19896
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition: SemaExpr.cpp:762
bool isImmediateFunctionContext() const
Definition: Sema.h:6291
ASTContext & getASTContext() const
Definition: Sema.h:527
ExprResult CallExprUnaryConversions(Expr *E)
CallExprUnaryConversions - a special case of an unary conversion performed on a function designator o...
Definition: SemaExpr.cpp:774
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:16025
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:19187
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:20147
void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions)
Definition: SemaExpr.cpp:15539
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:18092
AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS)
Definition: SemaExpr.cpp:9960
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:645
ExprResult DefaultArgumentPromotion(Expr *E)
DefaultArgumentPromotion (C99 6.5.2.2p6).
Definition: SemaExpr.cpp:879
ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedIdentKind IK)
Definition: SemaExpr.cpp:3736
bool CheckArgsForPlaceholders(MultiExprArg args)
Check an argument list for placeholders that we won't try to handle later.
Definition: SemaExpr.cpp:6373
bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen)
Definition: SemaExpr.cpp:3344
bool isBoundsAttrContext() const
Definition: Sema.h:5176
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:7237
ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl)
ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Definition: SemaExpr.cpp:16077
DefaultedComparisonKind
Kinds of defaulted comparison operator functions.
Definition: Sema.h:4483
@ None
This is not a defaultable comparison operator.
ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val)
Definition: SemaExpr.cpp:8144
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:13370
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1504
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:2206
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:16365
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:1675
CastKind PrepareCastToObjCObjectPointer(ExprResult &E)
Prepare a conversion of the given expression to an ObjC object pointer type.
Definition: SemaExpr.cpp:7471
AssumedTemplateKind
Definition: Sema.h:8875
ExprResult ActOnUnevaluatedStringLiteral(ArrayRef< Token > StringToks)
Definition: SemaExpr.cpp:1973
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
Warn if a value is moved to itself.
SourceRange getExprRange(Expr *E) const
Definition: SemaExpr.cpp:518
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:648
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:6324
void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID)
DiagnoseUnusedExprResult - If the statement passed in is an expression whose result is unused,...
Definition: SemaStmt.cpp:224
FPOptions & getCurFPFeatures()
Definition: Sema.h:522
RecordDecl * StdSourceLocationImplDecl
The C++ "std::source_location::__impl" struct, defined in <source_location>.
Definition: Sema.h:6435
ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK, bool MissingOK=false)
Definition: SemaExpr.cpp:20663
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:63
void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr)
@ UPPC_Block
Block expression.
Definition: Sema.h:10851
const LangOptions & getLangOpts() const
Definition: Sema.h:520
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:12523
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:7486
QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc)
Definition: SemaExpr.cpp:13299
ReuseLambdaContextDecl_t
Definition: Sema.h:5233
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:6717
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
void MarkExpressionAsImmediateEscalating(Expr *E)
Definition: SemaExpr.cpp:17767
NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D)
If D cannot be odr-used in the current expression evaluation context, return a reason explaining why.
Definition: SemaExpr.cpp:2254
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.
void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E)
Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
Definition: SemaExpr.cpp:20294
Preprocessor & PP
Definition: Sema.h:857
QualType CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:11304
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
Definition: SemaExpr.cpp:5904
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:6644
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
Definition: SemaExpr.cpp:14448
ExprResult BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext)
Definition: SemaExpr.cpp:17036
bool ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty, SourceLocation OpLoc, SourceRange R)
ActOnAlignasTypeArgument - Handle alignas(type-id) and _Alignas(type-name) .
Definition: SemaExpr.cpp:4948
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)
ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op)
Check an increment or decrement of a pseudo-object expression.
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:1916
bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy)
Are the two types matrix types and do they have the same dimensions i.e.
Definition: SemaExpr.cpp:7756
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:856
void EmitRelatedResultTypeNoteForReturn(QualType destType)
Given that we had incompatible pointer types in a return statement, check whether we're in a method w...
ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
__builtin_offsetof(type, a.b[123][456].c)
Definition: SemaExpr.cpp:16179
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2360
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:6912
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
Definition: SemaExpr.cpp:17788
ExprResult TemporaryMaterializationConversion(Expr *E)
If E is a prvalue denoting an unmaterialized temporary, materialize it as an xvalue.
Definition: SemaInit.cpp:8554
NamedDeclSetType UnusedPrivateFields
Set containing all declared private fields that are not used.
Definition: Sema.h:4796
SemaHLSL & HLSL()
Definition: Sema.h:1003
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
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:17752
ObjCLiteralKind
Definition: Sema.h:5720
@ LK_Boxed
Definition: Sema.h:5724
@ LK_Dictionary
Definition: Sema.h:5722
@ LK_String
Definition: Sema.h:5725
@ LK_Array
Definition: Sema.h:5721
@ LK_Numeric
Definition: Sema.h:5723
@ LK_None
Definition: Sema.h:5727
@ LK_Block
Definition: Sema.h:5726
void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D)
Definition: SemaExpr.cpp:204
@ 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:71
void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse)
Perform marking for a reference to an arbitrary declaration.
Definition: SemaExpr.cpp:20304
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)
Definition: SemaExpr.cpp:10244
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:5188
llvm::DenseMap< ParmVarDecl *, SourceLocation > UnparsedDefaultArgLocs
Definition: Sema.h:4822
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
Definition: Sema.cpp:1511
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:9761
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:10521
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
Definition: SemaExpr.cpp:944
bool isQualifiedMemberAccess(Expr *E)
Determine whether the given expression is a qualified member access expression, of a form that could ...
Definition: SemaExpr.cpp:15988
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 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...
static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy)
ScalarTypeToBooleanCastKind - Returns the cast kind corresponding to the conversion from scalar type ...
Definition: Sema.cpp:727
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:3340
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:892
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false)
The parser has read a name in, and Sema has detected that we're currently inside an ObjC method.
Definition: SemaExpr.cpp:3174
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
Definition: SemaExpr.cpp:3886
QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, ArithConvKind OperationKind)
Definition: SemaExpr.cpp:10772
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:10012
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:1663
llvm::DenseMap< const VarDecl *, int > RefsMinusAssignments
Increment when we find a reference; decrement when we find an ignored assignment.
Definition: Sema.h:5185
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:2079
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:651
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3432
ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S)
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool isInLifetimeExtendingContext() const
Definition: Sema.h:6295
void maybeExtendBlockObject(ExprResult &E)
Do an explicit extend of the given block pointer if we're in ARC.
Definition: SemaExpr.cpp:7456
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:1643
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:16554
ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr)
Prepare SplattedExpr for a vector splat operation, adding implicit casts if necessary.
Definition: SemaExpr.cpp:7902
sema::BlockScopeInfo * getCurBlock()
Retrieve the current block, if any.
Definition: Sema.cpp:2316
bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, ObjCMethodDecl *Method, ObjCIvarDecl *IV)
IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is an ivar synthesized for 'Meth...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:996
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
Definition: SemaInit.cpp:8535
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:21128
SuppressedDiagnosticsMap SuppressedDiagnostics
Definition: Sema.h:9571
@ VAK_Invalid
Definition: Sema.h:6053
@ VAK_Valid
Definition: Sema.h:6049
@ VAK_ValidInCXX11
Definition: Sema.h:6050
@ VAK_MSVCUndefined
Definition: Sema.h:6052
@ VAK_Undefined
Definition: Sema.h:6051
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5904
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:10530
ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc)
Definition: SemaExpr.cpp:16918
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:8153
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:20357
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:6287
DeclContext * getFunctionLevelDeclContext(bool AllowLambda=false) const
If AllowLambda is true, treat lambda as function.
Definition: Sema.cpp:1479
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition: Sema.h:6091
@ IncompatiblePointerDiscardsQualifiers
IncompatiblePointerDiscardsQualifiers - The assignment discards qualifiers that we don't permit to be...
Definition: Sema.h:6135
@ IntToPointer
IntToPointer - The assignment converts an int to a pointer, which we accept as an extension.
Definition: Sema.h:6101
@ IncompatibleBlockPointer
IncompatibleBlockPointer - The assignment is between two block pointers types that are not compatible...
Definition: Sema.h:6159
@ IncompatibleObjCQualifiedId
IncompatibleObjCQualifiedId - The assignment is between a qualified id type and something else (that ...
Definition: Sema.h:6164
@ IncompatibleVectors
IncompatibleVectors - The assignment is between two vector types that have the same size,...
Definition: Sema.h:6151
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition: Sema.h:6130
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition: Sema.h:6109
@ IncompatibleObjCWeakRef
IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an object with __weak qualifier.
Definition: Sema.h:6168
@ Compatible
Compatible - the types are compatible according to the standard.
Definition: Sema.h:6093
@ IncompatibleFunctionPointerStrict
IncompatibleFunctionPointerStrict - The assignment is between two function pointer types that are not...
Definition: Sema.h:6120
@ Incompatible
Incompatible - We reject this conversion outright, it is invalid to represent it in the AST.
Definition: Sema.h:6172
@ FunctionVoidPointer
FunctionVoidPointer - The assignment is between a function pointer and void*, which the standard does...
Definition: Sema.h:6105
@ IncompatibleFunctionPointer
IncompatibleFunctionPointer - The assignment is between two function pointers types that are not comp...
Definition: Sema.h:6114
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition: Sema.h:6126
@ IncompatibleNestedPointerQualifiers
IncompatibleNestedPointerQualifiers - The assignment is between two nested pointer types,...
Definition: Sema.h:6147
@ IncompatibleNestedPointerAddressSpaceMismatch
IncompatibleNestedPointerAddressSpaceMismatch - The assignment changes address spaces in nested point...
Definition: Sema.h:6141
@ PointerToInt
PointerToInt - The assignment converts a pointer to an int, which we accept as an extension.
Definition: Sema.h:6097
@ IntToBlockPointer
IntToBlockPointer - The assignment converts an int to a block pointer.
Definition: Sema.h:6155
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:8534
ArithConvKind
Context in which we're performing a usual arithmetic conversion.
Definition: Sema.h:5934
@ ACK_Arithmetic
An arithmetic operation.
Definition: Sema.h:5936
@ ACK_CompAssign
A compound assignment expression.
Definition: Sema.h:5944
@ ACK_BitwiseOp
A bitwise operation.
Definition: Sema.h:5938
@ ACK_Conditional
A conditional (?:) operator.
Definition: Sema.h:5942
@ ACK_Comparison
A comparison.
Definition: Sema.h:5940
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
Definition: SemaExpr.cpp:20251
ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E)
Definition: SemaExpr.cpp:4339
ExprResult ActOnSourceLocExpr(SourceLocIdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc)
Definition: SemaExpr.cpp:17003
llvm::PointerIntPair< ConstantExpr *, 1 > ImmediateInvocationCandidate
Definition: Sema.h:5022
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:21220
ExprResult TransformToPotentiallyEvaluated(Expr *E)
Definition: SemaExpr.cpp:17645
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:10484
SourceManager & getSourceManager() const
Definition: Sema.h:525
TryCaptureKind
Definition: Sema.h:5275
@ TryCapture_Implicit
Definition: Sema.h:5276
@ TryCapture_ExplicitByRef
Definition: Sema.h:5278
AssignmentAction
Definition: Sema.h:5196
@ AA_Returning
Definition: Sema.h:5199
@ AA_Passing_CFAudited
Definition: Sema.h:5204
@ AA_Initializing
Definition: Sema.h:5201
@ AA_Converting
Definition: Sema.h:5200
@ AA_Assigning
Definition: Sema.h:5197
@ AA_Passing
Definition: Sema.h:5198
@ AA_Casting
Definition: Sema.h:5203
@ AA_Sending
Definition: Sema.h:5202
ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
Create a new AsTypeExpr node (bitcast) from the arguments.
Definition: SemaExpr.cpp:6879
ExprResult checkPseudoObjectRValue(Expr *E)
bool CheckVecStepExpr(Expr *E)
Definition: SemaExpr.cpp:4612
void diagnoseARCUnbridgedCast(Expr *e)
Given that we saw an expression with the ARCUnbridgedCastTy placeholder type, complain bitterly.
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:9159
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:13075
QualType CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide)
Definition: SemaExpr.cpp:10947
ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr=false)
CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
ExprResult CheckLValueToRValueConversionOperand(Expr *E)
Definition: SemaExpr.cpp:19860
QualType CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:14032
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.
ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind)
ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
Definition: SemaExpr.cpp:21393
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
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 ...
@ NTCUK_Destruct
Definition: Sema.h:3028
@ NTCUK_Copy
Definition: Sema.h:3029
QualType CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect)
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:20498
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5707
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=std::nullopt, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
bool anyAltivecTypes(QualType srcType, QualType destType)
Definition: SemaExpr.cpp:7787
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:7833
void keepInLifetimeExtendingContext()
keepInLifetimeExtendingContext - Pull down InLifetimeExtendingContext flag from previous context.
Definition: Sema.h:6342
void PushBlockScope(Scope *BlockScope, BlockDecl *Block)
Definition: Sema.cpp:2138
sema::FunctionScopeInfo * getCurFunctionAvailabilityContext()
Retrieve the current function, if any, that should be analyzed for potential availability violations.
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:5020
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:227
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:8374
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:2058
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:11707
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15526
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:7935
@ CTK_ErrorRecovery
Definition: Sema.h:7605
void setFunctionHasBranchProtectedScope()
Definition: Sema.cpp:2301
bool isConstantEvaluatedContext() const
Definition: Sema.h:1864
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:3194
bool CheckForConstantInitializer(Expr *Init, unsigned DiagID=diag::err_init_element_not_constant)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:12680
ASTConsumer & Consumer
Definition: Sema.h:859
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:3424
const DeclContext * getCurObjCLexicalContext() const
Definition: Sema.h:5766
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:5192
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition: SemaExpr.cpp:120
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition: Sema.h:897
std::deque< PendingImplicitInstantiation > PendingInstantiations
The queue of implicit template instantiations that are required but have not yet been performed.
Definition: Sema.h:10513
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
Definition: SemaExpr.cpp:5349
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind)
Definition: SemaExpr.cpp:3784
QualType GetSignedVectorType(QualType V)
Definition: SemaExpr.cpp:13016
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:8641
ExpressionEvaluationContext
Describes how the expressions currently being parsed are evaluated at run-time, if at all.
Definition: Sema.h:4964
@ 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:2042
ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_astype(...)
Definition: SemaExpr.cpp:6871
ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R)
Build a sizeof or alignof expression given a type operand.
Definition: SemaExpr.cpp:4842
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:6122
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:20504
bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind)
Check the constraints on expression operands to unary type expression and type traits.
Definition: SemaExpr.cpp:4449
ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16755
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
Definition: SemaType.cpp:6235
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9276
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:830
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
ExprResult forceUnknownAnyToType(Expr *E, QualType ToType)
Force an expression with unknown-type to an expression of the given type.
Definition: SemaExpr.cpp:21148
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:19493
ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr)
Definition: SemaExpr.cpp:7970
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
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.
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition: Sema.h:6277
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr)
void DiscardCleanupsInEvaluationContext()
Definition: SemaExpr.cpp:18170
bool NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc)
Checks if the variable must be captured.
Definition: SemaExpr.cpp:19485
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6438
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1328
bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind)
Definition: SemaExpr.cpp:7882
bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization, RequiredTemplateKind RequiredTemplate=SourceLocation(), AssumedTemplateKind *ATK=nullptr, bool AllowTypoCorrection=true)
SourceManager & SourceMgr
Definition: Sema.h:861
bool CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo, SourceLocation OpLoc, SourceRange R)
Definition: SemaExpr.cpp:4933
ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo)
Build an altivec or OpenCL literal.
Definition: SemaExpr.cpp:8043
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious retain cycle.
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:2414
DiagnosticsEngine & Diags
Definition: Sema.h:860
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:521
FPOptions CurFPFeatures
Definition: Sema.h:854
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition: SemaExpr.cpp:527
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:650
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:7817
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:10662
void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc)
ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field)
Definition: SemaExpr.cpp:5781
void DiagnoseAssignmentAsCondition(Expr *E)
DiagnoseAssignmentAsCondition - Given that an expression is being used as a boolean condition,...
Definition: SemaExpr.cpp:20547
void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec)
We've found a use of a templated declaration that would trigger an implicit instantiation.
void EmitRelatedResultTypeNote(const Expr *E)
If the given expression involves a message send to a method with a related result type,...
void PopDeclContext()
Definition: SemaDecl.cpp:1335
QualType CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13421
llvm::MapVector< NamedDecl *, SourceLocation > UndefinedButUsed
UndefinedInternals - all the used, undefined objects which require a definition in this translation u...
Definition: Sema.h:4826
ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc)
Definition: SemaExpr.cpp:16104
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:999
void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr)
CheckStaticArrayArgument - If the given argument corresponds to a static array parameter,...
Definition: SemaExpr.cpp:6253
QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc)
Definition: SemaExpr.cpp:13136
ExprResult ConvertMemberDefaultInitExpression(FieldDecl *FD, Expr *InitExpr, SourceLocation InitLoc)
ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number)
BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the numeric literal expression.
bool IsInvalidSMECallConversion(QualType FromType, QualType ToType)
Definition: SemaExpr.cpp:9263
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:13226
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:16566
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:520
void MarkMemberReferenced(MemberExpr *E)
Perform reference-marking and odr-use handling for a MemberExpr.
Definition: SemaExpr.cpp:20274
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:17118
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:18353
ExprResult ActOnStmtExprResult(ExprResult E)
Definition: SemaExpr.cpp:16148
ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input)
Definition: SemaExpr.cpp:4993
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:6131
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
Definition: SemaLambda.cpp:280
bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, bool Diagnose=true)
Definition: SemaExpr.cpp:17044
void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE)
Redundant parentheses over an equality comparison can indicate that the user intended an assignment u...
Definition: SemaExpr.cpp:20605
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition: Sema.cpp:1899
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:21446
ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr)
Definition: SemaExpr.cpp:15589
ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope=nullptr)
Definition: SemaExpr.cpp:3920
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
Definition: SemaExpr.cpp:3212
ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7430
void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope)
ActOnBlockStart - This callback is invoked when a block literal is started.
Definition: SemaExpr.cpp:16404
ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, MultiExprArg ArgExprs, SourceLocation RLoc)
Definition: SemaExpr.cpp:5066
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:15058
AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType)
CheckAssignmentConstraints - Perform type checking for assignment, argument passing,...
Definition: SemaExpr.cpp:9538
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:6611
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:4916
QualType PreferredConditionType(ConditionKind K) const
Definition: Sema.h:6010
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:7429
@ LOLR_Raw
The lookup found a single 'raw' literal operator, which expects a string literal containing the spell...
Definition: Sema.h:7435
@ LOLR_Error
The lookup resulted in an error.
Definition: Sema.h:7427
@ LOLR_Cooked
The lookup found a single 'cooked' literal operator, which expects a normal literal to be built and p...
Definition: Sema.h:7432
@ LOLR_StringTemplatePack
The lookup found an overload set of literal operator templates, which expect the character type and c...
Definition: Sema.h:7443
@ LOLR_Template
The lookup found an overload set of literal operator templates, which expect the characters of the sp...
Definition: Sema.h:7439
void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope)
ActOnBlockArguments - This callback allows processing of block arguments.
Definition: SemaExpr.cpp:16433
QualType CheckRemainderOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign=false)
Definition: SemaExpr.cpp:10986
@ 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:10509
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:3222
ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef< AvailabilitySpec > AvailSpecs, SourceLocation AtLoc, SourceLocation RParen)
Definition: SemaExpr.cpp:21412
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:15959
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:13478
QualType CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType *CompLHSTy=nullptr)
Definition: SemaExpr.cpp:11419
static ConditionResult ConditionError()
Definition: Sema.h:5885
ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
__builtin_convertvector(...)
Definition: SemaExpr.cpp:6898
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:21152
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:5993
ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef< OffsetOfComponent > Components, SourceLocation RParenLoc)
Definition: SemaExpr.cpp:16346
bool hasAnyUnrecoverableErrorsInThisFunction() const
Determine whether any errors occurred within this function/method/ block.
Definition: Sema.cpp:2292
FullExprArg MakeFullExpr(Expr *Arg)
Definition: Sema.h:5841
bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy)
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
llvm::SmallVector< std::pair< SourceLocation, const BlockDecl * >, 1 > ImplicitlyRetainedSelfLocs
List of SourceLocations where 'self' is implicitly retained inside a block.
Definition: Sema.h:6446
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)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy)
Definition: SemaCast.cpp:2703
ExprResult HandleExprEvaluationContextForTypeof(Expr *E)
Definition: SemaExpr.cpp:18178
ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc)
Definition: SemaExpr.cpp:7362
bool isCheckingDefaultArgumentOrInitializer() const
Definition: Sema.h:6301
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:5577
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:6733
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:5234
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4727
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:267
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition: Overload.h:278
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
void setToType(unsigned Idx, QualType T)
Definition: Overload.h:359
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:4383
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:185
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
StmtClass getStmtClass() const
Definition: Stmt.h:1358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
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:1773
unsigned getLength() const
Definition: Expr.h:1890
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1865
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:1191
StringRef getString() const
Definition: Expr.h:1850
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3688
bool isUnion() const
Definition: Decl.h:3791
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3809
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
Exposes information about the current target.
Definition: TargetInfo.h:213
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1235
StringRef getPlatformName() const
Retrieve the name of the platform as it is used in the availability attribute.
Definition: TargetInfo.h:1623
@ CharPtrBuiltinVaList
typedef char* __builtin_va_list;
Definition: TargetInfo.h:316
virtual size_t getMaxBitIntWidth() const
Definition: TargetInfo.h:651
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:971
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Definition: TargetInfo.cpp:270
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:467
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:504
IntType getSizeType() const
Definition: TargetInfo.h:366
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:514
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1540
virtual bool supportsExtendIntArgs() const
Whether the option -fextend-arguments={32,64} is supported on the target.
Definition: TargetInfo.h:1633
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:1012
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1306
unsigned getIntMaxTWidth() const
Return the size of intmax_t and uintmax_t for this target, in bits.
Definition: TargetInfo.h:848
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:509
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
Definition: TargetInfo.h:1451
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:394
Represents a C++ template name within the type system.
Definition: TemplateName.h:202
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:3391
const Type * getTypeForDecl() const
Definition: Decl.h:3415
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3418
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:2684
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7120
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:7131
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1607
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition: Type.h:2190
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1870
bool isFixedPointOrIntegerType() const
Return true if this is a fixed point or integer type.
Definition: Type.h:7756
bool isBlockPointerType() const
Definition: Type.h:7410
bool isVoidType() const
Definition: Type.h:7695
bool isBooleanType() const
Definition: Type.h:7823
bool isObjCBuiltinType() const
Definition: Type.h:7585
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:1887
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:7870
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:729
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:7671
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition: Type.cpp:666
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2059
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:7850
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:2009
bool isVoidPointerType() const
Definition: Type.cpp:654
const ComplexType * getAsComplexIntegerType() const
Definition: Type.cpp:687
bool isArrayType() const
Definition: Type.h:7468
bool isCharType() const
Definition: Type.cpp:2077
bool isFunctionPointerType() const
Definition: Type.h:7436
bool isArithmeticType() const
Definition: Type.cpp:2269
bool isConstantMatrixType() const
Definition: Type.h:7526
bool isPointerType() const
Definition: Type.h:7402
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7735
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition: Type.cpp:2460
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7980
bool isReferenceType() const
Definition: Type.h:7414
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:7776
bool isEnumeralType() const
Definition: Type.h:7500
bool isScalarType() const
Definition: Type.h:7794
bool isVariableArrayType() const
Definition: Type.h:7480
bool isSizelessBuiltinType() const
Definition: Type.cpp:2421
bool isClkEventT() const
Definition: Type.h:7607
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition: Type.cpp:2487
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:2046
bool isObjCQualifiedIdType() const
Definition: Type.h:7555
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:7810
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e....
Definition: Type.cpp:2224
bool isExtVectorType() const
Definition: Type.h:7512
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition: Type.cpp:2113
bool isExtVectorBoolType() const
Definition: Type.h:7516
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition: Type.cpp:2513
bool isImageType() const
Definition: Type.h:7619
bool isNonOverloadPlaceholderType() const
Test for a placeholder type other than Overload; see BuiltinType::isNonOverloadPlaceholderType.
Definition: Type.h:7689
bool isPipeType() const
Definition: Type.h:7626
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2451
bool isBitIntType() const
Definition: Type.h:7630
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7664
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:7492
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2443
bool isAnyComplexType() const
Definition: Type.h:7504
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7748
bool isHalfType() const
Definition: Type.h:7699
bool isSaturatedFixedPointType() const
Return true if this is a saturated fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition: Type.h:7764
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2114
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:2284
const BuiltinType * getAsPlaceholderType() const
Definition: Type.h:7677
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
Definition: Type.cpp:2174
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition: Type.cpp:2444
bool isQueueT() const
Definition: Type.h:7611
bool isMemberPointerType() const
Definition: Type.h:7450
bool isAtomicType() const
Definition: Type.h:7547
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition: Type.h:7836
bool isObjCIdType() const
Definition: Type.h:7567
bool isMatrixType() const
Definition: Type.h:7522
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2461
bool isComplexIntegerType() const
Definition: Type.cpp:672
bool isUnscopedEnumerationType() const
Definition: Type.cpp:2070
bool isObjCObjectType() const
Definition: Type.h:7538
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:4792
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:7966
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4882
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:7829
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2350
bool isFunctionType() const
Definition: Type.h:7398
bool isObjCObjectPointerType() const
Definition: Type.h:7534
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
Definition: Type.cpp:2246
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:7790
bool isVectorType() const
Definition: Type.h:7508
bool isObjCQualifiedClassType() const
Definition: Type.h:7561
bool isObjCClassType() const
Definition: Type.h:7573
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:2254
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition: Type.cpp:2474
ScalarTypeKind
Definition: Type.h:2416
@ STK_FloatingComplex
Definition: Type.h:2425
@ STK_Floating
Definition: Type.h:2423
@ STK_BlockPointer
Definition: Type.h:2418
@ STK_Bool
Definition: Type.h:2421
@ STK_ObjCObjectPointer
Definition: Type.h:2419
@ STK_FixedPoint
Definition: Type.h:2426
@ STK_IntegralComplex
Definition: Type.h:2424
@ STK_CPointer
Definition: Type.h:2417
@ STK_Integral
Definition: Type.h:2422
@ STK_MemberPointer
Definition: Type.h:2420
bool isFloatingType() const
Definition: Type.cpp:2237
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:2184
bool isAnyPointerType() const
Definition: Type.h:7406
bool isRealType() const
Definition: Type.cpp:2260
TypeClass getTypeClass() const
Definition: Type.h:2094
bool isSamplerT() const
Definition: Type.h:7599
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7913
bool isNullPtrType() const
Definition: Type.h:7728
bool isRecordType() const
Definition: Type.h:7496
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4610
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition: Type.cpp:2456
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3535
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:6585
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2568
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2183
void setSubExpr(Expr *E)
Definition: Expr.h:2229
SourceLocation getOperatorLoc() const
getOperatorLoc - Return the location of the operator.
Definition: Expr.h:2232
Expr * getSubExpr() const
Definition: Expr.h:2228
Opcode getOpcode() const
Definition: Expr.h:2223
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition: Expr.cpp:1429
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:4838
bool isIncrementDecrementOp() const
Definition: Expr.h:2284
An artificial decl, representing a global anonymous constant value which is uniquified by value withi...
Definition: DeclCXX.h:4343
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:1024
void setImplicitSelfParam(const IdentifierInfo *Id)
Specify that this unqualified-id is an implicit 'self' parameter.
Definition: DeclSpec.h:1226
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3173
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:372
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3912
CXXRecordDecl * getNamingClass()
Retrieve the naming class of this lookup.
Definition: ExprCXX.cpp:1617
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:1579
A set of unresolved declarations.
Definition: UnresolvedSet.h:61
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:4667
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
void setType(QualType newType)
Definition: Decl.h:718
QualType getType() const
Definition: Decl.h:717
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition: Decl.cpp:5366
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3318
QualType getType() const
Definition: Value.cpp:234
Represents a variable declaration or definition.
Definition: Decl.h:918
bool hasInit() const
Definition: Decl.cpp:2395
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2254
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1558
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1270
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1213
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:2463
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:2876
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1531
const Expr * getInit() const
Definition: Decl.h:1355
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1204
bool isARCPseudoStrong() const
Determine whether this variable is an ARC pseudo-__strong variable.
Definition: Decl.h:1527
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1171
@ TLS_None
Not a TLS variable.
Definition: Decl.h:938
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1282
DefinitionKind hasDefinition(ASTContext &) const
Check whether this variable is defined in this translation unit.
Definition: Decl.cpp:2372
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:2505
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:2777
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1249
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:2756
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2867
Declaration of a variable template.
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3537
Expr * getSizeExpr() const
Definition: Type.h:3556
Represents a GCC generic vector type.
Definition: Type.h:3759
unsigned getNumElements() const
Definition: Type.h:3774
VectorKind getVectorKind() const
Definition: Type.h:3779
QualType getElementType() const
Definition: Type.h:3773
Retains information about a block that is currently being parsed.
Definition: ScopeInfo.h:784
Scope * TheScope
TheScope - This is the scope for the block itself, which contains arguments etc.
Definition: ScopeInfo.h:790
QualType FunctionType
BlockType - The function type of the block, if one was given.
Definition: ScopeInfo.h:794
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:810
unsigned short CapRegionKind
The kind of captured region.
Definition: ScopeInfo.h:825
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:739
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:729
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:752
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:749
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:731
Capture & getCapture(ValueDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Definition: ScopeInfo.h:765
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:878
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:865
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition: ScopeInfo.h:886
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:873
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:868
Defines the clang::TargetInfo interface.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
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.
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
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:294
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:209
@ OpenCL
Definition: LangStandard.h:65
@ CPlusPlus23
Definition: LangStandard.h:60
@ CPlusPlus20
Definition: LangStandard.h:59
@ CPlusPlus
Definition: LangStandard.h:55
@ CPlusPlus11
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:57
@ CPlusPlus17
Definition: LangStandard.h:58
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ OR_Success
Overload resolution succeeded.
Definition: Overload.h:52
@ GVA_StrongExternal
Definition: Linkage.h:76
bool isTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:77
CUDAFunctionTarget
Definition: Cuda.h:131
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:333
@ 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:146
@ OK_VectorComponent
A vector component is an element or range of elements on a vector.
Definition: Specifiers.h:154
@ 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:158
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition: Specifiers.h:148
@ OK_BitField
A bitfield object is a bitfield on a C or C++ record.
Definition: Specifiers.h:151
@ OK_MatrixComponent
A matrix component is a single element of a matrix.
Definition: Specifiers.h:166
BinaryOperatorKind
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
@ IK_TemplateId
A template-id, e.g., f<int>.
llvm::omp::Clause OpenMPClauseKind
OpenMP clauses.
Definition: OpenMPKinds.h:27
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:248
@ SC_Register
Definition: Specifiers.h:254
@ SC_None
Definition: Specifiers.h:247
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:51
ObjCMethodFamily
A family of Objective-C methods.
unsigned toTargetAddressSpace(LangAS AS)
Definition: AddressSpaces.h:81
ExprResult ExprEmpty()
Definition: Ownership.h:271
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Result
The result type of a method or function.
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition: Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition: Overload.h:139
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition: Overload.h:133
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition: Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition: Overload.h:202
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition: Overload.h:112
@ ICK_Identity
Identity conversion (no conversion)
Definition: Overload.h:106
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition: Overload.h:109
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition: Overload.h:136
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition: Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition: Overload.h:115
UnaryOperatorKind
bool isFunctionLocalStringLiteralMacro(tok::TokenKind K, const LangOptions &LO)
Return true if the token corresponds to a function local predefined macro, which expands to a string ...
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
ExprResult ExprError()
Definition: Ownership.h:264
@ AR_Unavailable
Definition: DeclBase.h:75
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.
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
Definition: OperatorKinds.h:36
@ TNK_Var_template
The name refers to a variable template whose specialization produces a variable.
Definition: TemplateKinds.h:33
bool isPtrSizeAddressSpace(LangAS AS)
Definition: AddressSpaces.h:91
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition: Specifiers.h:141
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
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:245
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition: Overload.h:251
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition: Overload.h:259
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition: Overload.h:248
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition: Overload.h:255
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1277
StringLiteralKind
Definition: Expr.h:1744
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ActionResult< Decl * > DeclResult
Definition: Ownership.h:254
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition: Specifiers.h:188
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:275
@ CC_X86VectorCall
Definition: Specifiers.h:280
@ CC_X86StdCall
Definition: Specifiers.h:277
@ CC_X86FastCall
Definition: Specifiers.h:278
@ 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:4714
@ None
No keyword precedes the qualified type name.
@ Other
Other implicit parameter.
PredefinedIdentKind
Definition: Expr.h:1970
@ Implicit
An implicit conversion.
CharacterLiteralKind
Definition: Expr.h:1584
@ AS_none
Definition: Specifiers.h:124
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:53
NonOdrUseReason
The reason why a DeclRefExpr does not constitute an odr-use.
Definition: Specifiers.h:170
@ NOUR_Discarded
This name appears as a potential result of a discarded value expression.
Definition: Specifiers.h:180
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition: Specifiers.h:174
@ NOUR_None
This is an odr-use.
Definition: Specifiers.h:172
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition: Specifiers.h:177
#define false
Definition: stdbool.h:22
#define bool
Definition: stdbool.h:20
ExprResult TransformCXXThisExpr(CXXThisExpr *E)
Definition: SemaExpr.cpp:5704
EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
Definition: SemaExpr.cpp:5691
ExprResult TransformBlockExpr(BlockExpr *E)
Definition: SemaExpr.cpp:5699
ExprResult TransformLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5698
bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E)
Definition: SemaExpr.cpp:5684
bool VisitCallExpr(CallExpr *E)
Definition: SemaExpr.cpp:5649
bool VisitCXXConstructExpr(CXXConstructExpr *E)
Definition: SemaExpr.cpp:5655
const ASTContext & Context
Definition: SemaExpr.cpp:5643
bool VisitLambdaExpr(LambdaExpr *E)
Definition: SemaExpr.cpp:5676
bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E)
Definition: SemaExpr.cpp:5680
bool VisitSourceLocExpr(SourceLocExpr *E)
Definition: SemaExpr.cpp:5665
bool shouldVisitImplicitCode() const
Definition: SemaExpr.cpp:5647
ImmediateCallVisitor(const ASTContext &Ctx)
Definition: SemaExpr.cpp:5644
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
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 HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:609
Extra information about a function prototype.
Definition: Type.h:4525
FunctionType::ExtInfo ExtInfo
Definition: Type.h:4526
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:9821
Data structure used to record current or nested expression evaluation contexts.
Definition: Sema.h:5026
llvm::SmallPtrSet< const Expr *, 8 > PossibleDerefs
Definition: Sema.h:5060
bool InLifetimeExtendingContext
Whether we are currently in a context in which all temporaries must be lifetime-extended,...
Definition: Sema.h:5106
SmallVector< Expr *, 2 > VolatileAssignmentLHSs
Expressions appearing as the LHS of a volatile assignment in this context.
Definition: Sema.h:5065
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:5073
llvm::SmallVector< ImmediateInvocationCandidate, 4 > ImmediateInvocationCandidates
Set of candidates for starting an immediate invocation.
Definition: Sema.h:5069
SmallVector< MaterializeTemporaryExpr *, 8 > ForRangeLifetimeExtendTemps
P2718R0 - Lifetime extension in range-based for loops.
Definition: Sema.h:5079
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:5045
ExpressionKind
Describes whether we are in an expression constext which we have to handle differently.
Definition: Sema.h:5083
CleanupInfo ParentCleanup
Whether the enclosing context needed a cleanup.
Definition: Sema.h:5031
unsigned NumTypos
The number of typos encountered during this expression evaluation context (i.e.
Definition: Sema.h:5039
ExpressionEvaluationContext Context
The expression evaluation context.
Definition: Sema.h:5028
unsigned NumCleanupObjects
The number of active cleanup objects when we entered this expression evaluation context.
Definition: Sema.h:5035
Abstract class used to diagnose incomplete types.
Definition: Sema.h:6379
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
uint64_t Width
Definition: ASTContext.h:153