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"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/ASTMutationListener.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/EvaluatedExprVisitor.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/ExprOpenMP.h"
27#include "clang/AST/OperationKinds.h"
28#include "clang/AST/ParentMapContext.h"
29#include "clang/AST/RecursiveASTVisitor.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/Basic/Builtins.h"
33#include "clang/Basic/DiagnosticSema.h"
34#include "clang/Basic/PartialDiagnostic.h"
35#include "clang/Basic/SourceManager.h"
36#include "clang/Basic/Specifiers.h"
37#include "clang/Basic/TargetInfo.h"
38#include "clang/Basic/TypeTraits.h"
39#include "clang/Lex/LiteralSupport.h"
40#include "clang/Lex/Preprocessor.h"
41#include "clang/Sema/AnalysisBasedWarnings.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/DelayedDiagnostic.h"
44#include "clang/Sema/Designator.h"
45#include "clang/Sema/EnterExpressionEvaluationContext.h"
46#include "clang/Sema/Initialization.h"
47#include "clang/Sema/Lookup.h"
48#include "clang/Sema/Overload.h"
49#include "clang/Sema/ParsedTemplate.h"
50#include "clang/Sema/Scope.h"
51#include "clang/Sema/ScopeInfo.h"
52#include "clang/Sema/SemaCUDA.h"
53#include "clang/Sema/SemaFixItUtils.h"
54#include "clang/Sema/SemaInternal.h"
55#include "clang/Sema/SemaOpenMP.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>(Val: 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, Loc: SourceLocation(), /*Diagnose*/ false))
85 return false;
86
87 // See if this is an aligned allocation/deallocation function that is
88 // unavailable.
89 if (TreatUnavailableAsInvalid &&
90 isUnavailableAlignedAllocationFunction(FD: *FD))
91 return false;
92 }
93
94 // See if this function is unavailable.
95 if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
96 cast<Decl>(Val: CurContext)->getAvailability() != AR_Unavailable)
97 return false;
98
99 if (isa<UnresolvedUsingIfExistsDecl>(Val: D))
100 return false;
101
102 return true;
103}
104
105static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
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>(Val: 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.
120void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
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.
130 DiagnoseDeletedDefaultedFunction(FD: Decl);
131 return;
132 }
133
134 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: Decl);
135 if (Ctor && Ctor->isInheritingConstructor())
136 return NoteDeletedInheritingConstructor(CD: Ctor);
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.
144static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
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.
160static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
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.
179 if (D->getFormalLinkage() != Linkage::Internal)
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>(Val: 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
198 S.MaybeSuggestAddingStaticToDecl(D: Current);
199
200 S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
201 << D;
202}
203
204void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
205 const FunctionDecl *First = Cur->getFirstDecl();
206
207 // Suggest "static" on the function, if possible.
208 if (!hasAnyExplicitStorageClass(D: First)) {
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///
227bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
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>(Val: 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(FD: *cast<FunctionDecl>(Val: 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>(Val: 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>(Val: D)) {
270 // See if this is a deleted function.
271 if (FD->isDeleted()) {
272 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: 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 }
282 NoteDeletedFunction(Decl: FD);
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, UsageLoc: 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, Callee: FD))
317 return true;
318
319 }
320
321 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
322 // Lambdas are only default-constructible or assignable in C++2a onwards.
323 if (MD->getParent()->isLambda() &&
324 ((isa<CXXConstructorDecl>(Val: MD) &&
325 cast<CXXConstructorDecl>(Val: 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>(Val: 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(ND: 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>(Val: CurContext);
350 if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
351 isa<VarDecl>(Val: D)) {
352 Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
353 << getCurFunction()->HasOMPDeclareReductionCombiner;
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>(Val: D) &&
364 !OpenMP().isOpenMPDeclareMapperVarDeclAllowed(VD: cast<VarDecl>(Val: D))) {
365 Diag(Loc, diag::err_omp_declare_mapper_wrong_var)
366 << OpenMP().getOpenMPDeclareMapperVarName();
367 Diag(D->getLocation(), diag::note_entity_declared_at) << D;
368 return true;
369 }
370
371 if (const auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(Val: 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(S&: *this, D, Loc);
381
382 diagnoseUseOfInternalDeclInInlineFunction(S&: *this, D, Loc);
383
384 if (D->hasAttr<AvailableOnlyInDefaultEvalMethodAttr>()) {
385 if (getLangOpts().getFPEvalMethod() !=
386 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine &&
387 PP.getLastFPEvalPragmaLocation().isValid() &&
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>(Val: D))
395 checkTypeSupport(Ty: VD->getType(), Loc, D: VD);
396
397 if (LangOpts.SYCLIsDevice ||
398 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice)) {
399 if (!Context.getTargetInfo().isTLSSupported())
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>(Val: D) && isa<RequiresExprBodyDecl>(D->getDeclContext()) &&
406 !isUnevaluatedContext()) {
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.
423void Sema::DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc,
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>(Val: D)) {
437 NumFormalParams = MD->param_size();
438 CalleeKind = CK_Method;
439 } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
440 NumFormalParams = FD->param_size();
441 CalleeKind = CK_Function;
442 } else if (const auto *VD = dyn_cast<VarDecl>(Val: 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>(Val: 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(E: 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(Loc: SentinelExpr->getEndLoc());
498 std::string NullValue;
499 if (CalleeKind == CK_Method && PP.isMacroDefined(Id: "nil"))
500 NullValue = "nil";
501 else if (getLangOpts().CPlusPlus11)
502 NullValue = "nullptr";
503 else if (PP.isMacroDefined(Id: "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
518SourceRange Sema::getExprRange(Expr *E) const {
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).
527ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
528 // Handle any placeholder expressions which made it here.
529 if (E->hasPlaceholderType()) {
530 ExprResult result = CheckPlaceholderExpr(E);
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>(Val: E->IgnoreParenCasts()))
540 if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl()))
541 if (!checkAddressOfFunctionIsAvailable(Function: FD, Complain: Diagnose, Loc: E->getExprLoc()))
542 return ExprError();
543
544 E = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
545 CK: 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()) {
559 ExprResult Res = ImpCastExprToType(E, Type: Context.getArrayDecayedType(T: Ty),
560 CK: CK_ArrayToPointerDecay);
561 if (Res.isInvalid())
562 return ExprError();
563 E = Res.get();
564 }
565 }
566 return E;
567}
568
569static void CheckForNullPointerDereference(Sema &S, Expr *E) {
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>(Val: 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(
583 Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull) &&
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();
602 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
603 if (!Member || !Member->isStr(Str: "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(IVarName: Member, ClassDeclared);
614 if (!ClassDeclared->getSuperClass()
615 && (*ClassDeclared->ivar_begin()) == IV) {
616 if (RHS) {
617 NamedDecl *ObjectSetClass =
618 S.LookupSingleName(S: S.TUScope,
619 Name: &S.Context.Idents.get(Name: "object_setClass"),
620 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
621 if (ObjectSetClass) {
622 SourceLocation RHSLocEnd = S.getLocForEndOfToken(Loc: RHS->getEndLoc());
623 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign)
624 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
625 "object_setClass(")
626 << FixItHint::CreateReplacement(
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 =
634 S.LookupSingleName(S: S.TUScope,
635 Name: &S.Context.Idents.get(Name: "object_getClass"),
636 Loc: SourceLocation(), NameKind: S.LookupOrdinaryName);
637 if (ObjectGetClass)
638 S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use)
639 << FixItHint::CreateInsertion(OIRE->getBeginLoc(),
640 "object_getClass(")
641 << FixItHint::CreateReplacement(
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
651ExprResult Sema::DefaultLvalueConversion(Expr *E) {
652 // Handle any placeholder expressions which made it here.
653 if (E->hasPlaceholderType()) {
654 ExprResult result = CheckPlaceholderExpr(E);
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).
669 if (T->canDecayToPointerType())
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(Ext: "cl_khr_fp16", LO: getLangOpts()) &&
691 T->isHalfType()) {
692 Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
693 << 0 << T;
694 return ExprError();
695 }
696
697 CheckForNullPointerDereference(S&: *this, E);
698 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: E->IgnoreParenCasts())) {
699 NamedDecl *ObjectGetClass = LookupSingleName(S: TUScope,
700 Name: &Context.Idents.get(Name: "object_getClass"),
701 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
702 if (ObjectGetClass)
703 Diag(E->getExprLoc(), diag::warn_objc_isa_use)
704 << FixItHint::CreateInsertion(OISA->getBeginLoc(), "object_getClass(")
705 << FixItHint::CreateReplacement(
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>(Val: E->IgnoreParenCasts()))
712 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: SourceLocation(), /* Expr*/RHS: 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() &&
728 Context.getTargetInfo().getCXXABI().isMicrosoft())
729 (void)isCompleteType(Loc: E->getExprLoc(), T);
730
731 ExprResult Res = CheckLValueToRValueConversionOperand(E);
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.
738 if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
739 Cleanup.setExprNeedsCleanups(true);
740
741 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
742 Cleanup.setExprNeedsCleanups(true);
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, Kind: CK, Operand: E, BasePath: nullptr, Cat: VK_PRValue,
748 FPO: CurFPFeatureOverrides());
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, Kind: CK_AtomicToNonAtomic, Operand: Res.get(),
756 BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
757 }
758
759 return Res;
760}
761
762ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
763 ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
764 if (Res.isInvalid())
765 return ExprError();
766 Res = DefaultLvalueConversion(E: 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.
774ExprResult Sema::CallExprUnaryConversions(Expr *E) {
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()) {
780 Res = ImpCastExprToType(E, Type: Context.getPointerType(T: Ty),
781 CK: CK_FunctionToPointerDecay);
782 if (Res.isInvalid())
783 return ExprError();
784 }
785 Res = DefaultLvalueConversion(E: 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.
796ExprResult Sema::UsualUnaryConversions(Expr *E) {
797 // First, convert to an r-value.
798 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
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() !=
809 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine ||
810 PP.getLastFPEvalPragmaLocation().isValid())) {
811 switch (EvalMethod) {
812 default:
813 llvm_unreachable("Unrecognized float evaluation method");
814 break;
815 case LangOptions::FEM_UnsetOnCommandLine:
816 llvm_unreachable("Float evaluation method should be set by now");
817 break;
818 case LangOptions::FEM_Double:
819 if (Context.getFloatingTypeOrder(LHS: Context.DoubleTy, RHS: Ty) > 0)
820 // Widen the expression to double.
821 return Ty->isComplexType()
822 ? ImpCastExprToType(E,
823 Type: Context.getComplexType(Context.DoubleTy),
824 CK: CK_FloatingComplexCast)
825 : ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast);
826 break;
827 case LangOptions::FEM_Extended:
828 if (Context.getFloatingTypeOrder(LHS: Context.LongDoubleTy, RHS: Ty) > 0)
829 // Widen the expression to long double.
830 return Ty->isComplexType()
831 ? ImpCastExprToType(
832 E, Type: Context.getComplexType(Context.LongDoubleTy),
833 CK: CK_FloatingComplexCast)
834 : ImpCastExprToType(E, Type: Context.LongDoubleTy,
835 CK: 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(E: Res.get(), Type: Context.FloatTy, CK: CK_FloatingCast);
843
844 // Try to perform integral promotions if the object has a theoretically
845 // promotable type.
846 if (Ty->isIntegralOrUnscopedEnumerationType()) {
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
861 QualType PTy = Context.isPromotableBitField(E);
862 if (!PTy.isNull()) {
863 E = ImpCastExprToType(E, Type: PTy, CK: CK_IntegralCast).get();
864 return E;
865 }
866 if (Context.isPromotableIntegerType(T: Ty)) {
867 QualType PT = Context.getPromotedIntegerType(PromotableType: Ty);
868 E = ImpCastExprToType(E, Type: PT, CK: 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().
879ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
880 QualType Ty = E->getType();
881 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
882
883 ExprResult Res = UsualUnaryConversions(E);
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(Ext: "cl_khr_fp64", LO: getLangOpts())) {
897 if (BTy->getKind() == BuiltinType::Half) {
898 E = ImpCastExprToType(E, Type: Context.FloatTy, CK: CK_FloatingCast).get();
899 }
900 } else {
901 E = ImpCastExprToType(E, Type: Context.DoubleTy, CK: CK_FloatingCast).get();
902 }
903 }
904 if (BTy &&
905 getLangOpts().getExtendIntArgs() ==
906 LangOptions::ExtendArgsKind::ExtendTo64 &&
907 Context.getTargetInfo().supportsExtendIntArgs() && Ty->isIntegerType() &&
908 Context.getTypeSizeInChars(BTy) <
909 Context.getTypeSizeInChars(Context.LongLongTy)) {
910 E = (Ty->isUnsignedIntegerType())
911 ? ImpCastExprToType(E, Type: Context.UnsignedLongLongTy, CK: CK_IntegralCast)
912 .get()
913 : ImpCastExprToType(E, Type: Context.LongLongTy, CK: CK_IntegralCast).get();
914 assert(8 == Context.getTypeSizeInChars(Context.LongLongTy).getQuantity() &&
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.
929 if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
930 ExprResult Temp = PerformCopyInitialization(
931 Entity: InitializedEntity::InitializeTemporary(Type: E->getType()),
932 EqualLoc: E->getExprLoc(), Init: 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.
944Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
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
962 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
963 return VAK_Invalid;
964
965 if (Context.getTargetInfo().getTriple().isWasm() &&
966 Ty.isWebAssemblyReferenceType()) {
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.
978 if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
979 if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
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
999void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
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:
1007 DiagRuntimeBehavior(
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:
1029 if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
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.
1046ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
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: 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
1064 ExprResult ExprRes = DefaultArgumentPromotion(E);
1065 if (ExprRes.isInvalid())
1066 return ExprError();
1067
1068 // Copy blocks to the heap.
1069 if (ExprRes.get()->getType()->isBlockPointerType())
1070 maybeExtendBlockObject(E&: 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().
1076 if (isValidVarArgType(Ty: E->getType()) == VAK_Undefined) {
1077 // Turn this into a trap.
1078 CXXScopeSpec SS;
1079 SourceLocation TemplateKWLoc;
1080 UnqualifiedId Name;
1081 Name.setIdentifier(Id: PP.getIdentifierInfo(Name: "__builtin_trap"),
1082 IdLoc: E->getBeginLoc());
1083 ExprResult TrapFn = ActOnIdExpression(S: TUScope, SS, TemplateKWLoc, Id&: Name,
1084 /*HasTrailingLParen=*/true,
1085 /*IsAddressOfOperand=*/false);
1086 if (TrapFn.isInvalid())
1087 return ExprError();
1088
1089 ExprResult Call = BuildCallExpr(S: TUScope, Fn: TrapFn.get(), LParenLoc: E->getBeginLoc(),
1090 ArgExprs: std::nullopt, RParenLoc: E->getEndLoc());
1091 if (Call.isInvalid())
1092 return ExprError();
1093
1094 ExprResult Comma =
1095 ActOnBinOp(S: TUScope, TokLoc: E->getBeginLoc(), Kind: tok::comma, LHSExpr: Call.get(), RHSExpr: E);
1096 if (Comma.isInvalid())
1097 return ExprError();
1098 return Comma.get();
1099 }
1100
1101 if (!getLangOpts().CPlusPlus &&
1102 RequireCompleteType(E->getExprLoc(), E->getType(),
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.
1115static bool handleComplexIntegerToFloatConversion(Sema &S, ExprResult &IntExpr,
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(E: IntExpr.get(), Type: fpTy, CK: CK_IntegralToFloating);
1125 } else {
1126 assert(IntTy->isComplexIntegerType());
1127 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: ComplexTy,
1128 CK: 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".
1143static QualType handleComplexFloatConversion(Sema &S, ExprResult &Shorter,
1144 QualType ShorterType,
1145 QualType LongerType,
1146 bool PromotePrecision) {
1147 bool LongerIsComplex = isa<ComplexType>(Val: LongerType.getCanonicalType());
1148 QualType Result =
1149 LongerIsComplex ? LongerType : S.Context.getComplexType(T: LongerType);
1150
1151 if (PromotePrecision) {
1152 if (isa<ComplexType>(Val: ShorterType.getCanonicalType())) {
1153 Shorter =
1154 S.ImpCastExprToType(E: Shorter.get(), Type: Result, CK: CK_FloatingComplexCast);
1155 } else {
1156 if (LongerIsComplex)
1157 LongerType = LongerType->castAs<ComplexType>()->getElementType();
1158 Shorter = S.ImpCastExprToType(E: Shorter.get(), Type: LongerType, CK: CK_FloatingCast);
1159 }
1160 }
1161 return Result;
1162}
1163
1164/// Handle arithmetic conversion with complex types. Helper function of
1165/// UsualArithmeticConversions()
1166static QualType handleComplexConversion(Sema &S, ExprResult &LHS,
1167 ExprResult &RHS, QualType LHSType,
1168 QualType RHSType, bool IsCompAssign) {
1169 // Handle (complex) integer types.
1170 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: RHS, ComplexExpr&: LHS, IntTy: RHSType, ComplexTy: LHSType,
1171 /*SkipCast=*/false))
1172 return LHSType;
1173 if (!handleComplexIntegerToFloatConversion(S, IntExpr&: LHS, ComplexExpr&: RHS, IntTy: LHSType, ComplexTy: 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(LHS: LHSType, RHS: RHSType);
1179 if (Order < 0)
1180 // Promote the precision of the LHS if not an assignment.
1181 return handleComplexFloatConversion(S, Shorter&: LHS, ShorterType: LHSType, LongerType: RHSType,
1182 /*PromotePrecision=*/!IsCompAssign);
1183 // Promote the precision of the RHS unless it is already the same as the LHS.
1184 return handleComplexFloatConversion(S, Shorter&: RHS, ShorterType: RHSType, LongerType: LHSType,
1185 /*PromotePrecision=*/Order > 0);
1186}
1187
1188/// Handle arithmetic conversion from integer to float. Helper function
1189/// of UsualArithmeticConversions()
1190static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
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(E: IntExpr.get(), Type: FloatTy,
1198 CK: 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(T: FloatTy);
1205
1206 // _Complex int -> _Complex float
1207 if (ConvertInt)
1208 IntExpr = S.ImpCastExprToType(E: IntExpr.get(), Type: result,
1209 CK: CK_IntegralComplexToFloatingComplex);
1210
1211 // float -> _Complex float
1212 if (ConvertFloat)
1213 FloatExpr = S.ImpCastExprToType(E: FloatExpr.get(), Type: result,
1214 CK: CK_FloatingRealToComplex);
1215
1216 return result;
1217}
1218
1219/// Handle arithmethic conversion with floating point types. Helper
1220/// function of UsualArithmeticConversions()
1221static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
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(E: RHS.get(), Type: LHSType, CK: CK_FixedPointToFloating);
1233 else if (!IsCompAssign)
1234 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: 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(LHS: LHSType, RHS: RHSType);
1242 if (order > 0) {
1243 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_FloatingCast);
1244 return LHSType;
1245 }
1246
1247 assert(order < 0 && "illegal float comparison");
1248 if (!IsCompAssign)
1249 LHS = S.ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: 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, FloatExpr&: LHS, IntExpr&: RHS, FloatTy: LHSType, IntTy: RHSType,
1259 /*ConvertFloat=*/!IsCompAssign,
1260 /*ConvertInt=*/ true);
1261 }
1262 assert(RHSFloat);
1263 return handleIntToFloatConversion(S, FloatExpr&: RHS, IntExpr&: LHS, FloatTy: RHSType, IntTy: 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(T: LHSElem);
1285 const llvm::fltSemantics &RHSSem = S.Context.getFloatTypeSemantics(T: 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(E: op, Type: toType, CK: CK_IntegralCast);
1303}
1304
1305ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1306 return S.ImpCastExprToType(E: op, Type: S.Context.getComplexType(T: toType),
1307 CK: CK_IntegralComplexCast);
1308}
1309}
1310
1311/// Handle integer arithmetic conversions. Helper function of
1312/// UsualArithmeticConversions()
1313template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1314static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
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(LHS: LHSType, RHS: 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(T: LHSType) != S.Context.getIntWidth(T: 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(T: 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()
1364static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
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, LHSType: LHSEltType, RHSType: RHSEltType, IsCompAssign);
1377
1378 return S.Context.getComplexType(T: ScalarType);
1379 }
1380
1381 if (LHSComplexInt) {
1382 QualType LHSEltType = LHSComplexInt->getElementType();
1383 QualType ScalarType =
1384 handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1385 (S, LHS, RHS, LHSType: LHSEltType, RHSType, IsCompAssign);
1386 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1387 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ComplexType,
1388 CK: 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, RHSType: RHSEltType, IsCompAssign);
1399 QualType ComplexType = S.Context.getComplexType(T: ScalarType);
1400
1401 if (!IsCompAssign)
1402 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ComplexType,
1403 CK: 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).
1457static QualType handleFixedPointConversion(Sema &S, QualType LHSTy,
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())
1471 LHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: LHSTy);
1472 else if (RHSTy->isUnsignedFixedPointType() && LHSTy->isSignedFixedPointType())
1473 RHSTy = S.Context.getCorrespondingSignedFixedPointType(Ty: RHSTy);
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(Ty: LHSTy);
1484 unsigned RHSTyRank = GetFixedPointRank(Ty: RHSTy);
1485
1486 QualType ResultTy = LHSTyRank > RHSTyRank ? LHSTy : RHSTy;
1487
1488 if (LHSTy->isSaturatedFixedPointType() || RHSTy->isSaturatedFixedPointType())
1489 ResultTy = S.Context.getCorrespondingSaturatedType(Ty: 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.
1496static void checkEnumArithmeticConversions(Sema &S, Expr *LHS, Expr *RHS,
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?).
1506 QualType L = LHS->getEnumCoercedType(Ctx: S.Context),
1507 R = RHS->getEnumCoercedType(Ctx: 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 &&
1521 !S.Context.hasSameUnqualifiedType(T1: L, T2: R)) {
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.
1561QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1562 SourceLocation Loc,
1563 ArithConvKind ACK) {
1564 checkEnumArithmeticConversions(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc, ACK);
1565
1566 if (ACK != ACK_CompAssign) {
1567 LHS = UsualUnaryConversions(E: LHS.get());
1568 if (LHS.isInvalid())
1569 return QualType();
1570 }
1571
1572 RHS = UsualUnaryConversions(E: 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(T1: LHSType, T2: RHSType))
1587 return Context.getCommonSugaredType(X: LHSType, Y: 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(T: LHSType))
1597 LHSType = Context.getPromotedIntegerType(PromotableType: LHSType);
1598 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(E: LHS.get());
1599 if (!LHSBitfieldPromoteTy.isNull())
1600 LHSType = LHSBitfieldPromoteTy;
1601 if (LHSType != LHSUnpromotedType && ACK != ACK_CompAssign)
1602 LHS = ImpCastExprToType(E: LHS.get(), Type: LHSType, CK: CK_IntegralCast);
1603
1604 // If both types are identical, no conversion is needed.
1605 if (Context.hasSameType(T1: LHSType, T2: RHSType))
1606 return Context.getCommonSugaredType(X: LHSType, Y: 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(S: *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(S&: *this, LHS, RHS, LHSType, RHSType,
1618 IsCompAssign: 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(S&: *this, LHS, RHS, LHSType, RHSType,
1623 IsCompAssign: ACK == ACK_CompAssign);
1624
1625 // Handle GCC complex int extension.
1626 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1627 return handleComplexIntConversion(S&: *this, LHS, RHS, LHSType, RHSType,
1628 IsCompAssign: ACK == ACK_CompAssign);
1629
1630 if (LHSType->isFixedPointType() || RHSType->isFixedPointType())
1631 return handleFixedPointConversion(S&: *this, LHSTy: LHSType, RHSTy: RHSType);
1632
1633 // Finally, we have two differing integer types.
1634 return handleIntegerConversion<doIntegralCast, doIntegralCast>
1635 (S&: *this, LHS, RHS, LHSType, RHSType, IsCompAssign: ACK == ACK_CompAssign);
1636}
1637
1638//===----------------------------------------------------------------------===//
1639// Semantic Analysis for various Expression Types
1640//===----------------------------------------------------------------------===//
1641
1642
1643ExprResult Sema::ActOnGenericSelectionExpr(
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(Ty: ArgTypes[i], TInfo: &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(Ty: ParsedType::getFromOpaquePtr(P: ControllingExprOrType),
1663 TInfo: &ControllingType);
1664 assert(ControllingType && "couldn't get the type out of the parser");
1665 ControllingExprOrType = ControllingType;
1666 }
1667
1668 ExprResult ER = CreateGenericSelectionExpr(
1669 KeyLoc, DefaultLoc, RParenLoc, PredicateIsExpr, ControllingExprOrType,
1670 Types: llvm::ArrayRef(Types, NumAssocs), Exprs: ArgExprs);
1671 delete [] Types;
1672 return ER;
1673}
1674
1675ExprResult Sema::CreateGenericSelectionExpr(
1676 SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc,
1677 bool PredicateIsExpr, void *ControllingExprOrType,
1678 ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs) {
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.
1690 EnterExpressionEvaluationContext Unevaluated(
1691 *this, Sema::ExpressionEvaluationContext::Unevaluated);
1692 ExprResult R = DefaultFunctionArrayLvalueConversion(
1693 E: 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(T1: Types[i]->getType(),
1793 T2: 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, GenericLoc: KeyLoc, ControllingExpr,
1816 AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
1817 ContainsUnexpandedParameterPack);
1818 return GenericSelectionExpr::Create(Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types,
1819 AssocExprs: 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 &&
1832 Context.typesAreCompatible(
1833 T1: ControllingExpr->getType().getCanonicalType(),
1834 T2: Types[i]->getType()))
1835 CompatIndices.push_back(Elt: i);
1836 else if (ControllingType &&
1837 Context.typesAreCompatible(
1838 T1: ControllingType->getType().getCanonicalType(),
1839 T2: Types[i]->getType()))
1840 CompatIndices.push_back(Elt: 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) {
1895 return GenericSelectionExpr::Create(
1896 Context, GenericLoc: KeyLoc, ControllingExpr, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
1897 ContainsUnexpandedParameterPack, ResultIndex);
1898 }
1899 return GenericSelectionExpr::Create(
1900 Context, GenericLoc: KeyLoc, ControllingType, AssocTypes: Types, AssocExprs: Exprs, DefaultLoc, RParenLoc,
1901 ContainsUnexpandedParameterPack, ResultIndex);
1902}
1903
1904static PredefinedIdentKind getPredefinedExprKind(tok::TokenKind Kind) {
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__:
1911 return PredefinedIdentKind::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__:
1921 return PredefinedIdentKind::PrettyFunction; // [GNU]
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.
1928static Decl *getPredefinedExprDecl(DeclContext *DC) {
1929 while (DC && !isa<BlockDecl, CapturedDecl, FunctionDecl, ObjCMethodDecl>(Val: DC))
1930 DC = DC->getParent();
1931 return cast_or_null<Decl>(Val: 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.
1936static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1937 unsigned Offset) {
1938 return Lexer::AdvanceToTokenCharacter(TokStart: TokLoc, Characters: Offset, SM: S.getSourceManager(),
1939 LangOpts: 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.
1944static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
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(T: ArgTy[ArgIdx]);
1956 }
1957
1958 DeclarationName OpName =
1959 S.Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
1960 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1961 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1962
1963 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1964 if (S.LookupLiteralOperator(S: Scope, R, ArgTys: llvm::ArrayRef(ArgTy, Args.size()),
1965 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1966 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
1967 /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1968 return ExprError();
1969
1970 return S.BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args, LitEndLoc);
1971}
1972
1973ExprResult Sema::ActOnUnevaluatedStringLiteral(ArrayRef<Token> StringToks) {
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(Toks: StringToks);
1978
1979 StringLiteralParser Literal(StringToks, PP,
1980 StringLiteralEvalMethod::Unevaluated);
1981 if (Literal.hadError)
1982 return ExprError();
1983
1984 SmallVector<SourceLocation, 4> StringTokLocs;
1985 for (const Token &Tok : StringToks)
1986 StringTokLocs.push_back(Elt: Tok.getLocation());
1987
1988 StringLiteral *Lit = StringLiteral::Create(
1989 Ctx: Context, Str: Literal.GetString(), Kind: StringLiteralKind::Unevaluated, Pascal: false, Ty: {},
1990 Loc: &StringTokLocs[0], NumConcatenated: StringTokLocs.size());
1991
1992 if (!Literal.getUDSuffix().empty()) {
1993 SourceLocation UDSuffixLoc =
1994 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
1995 Offset: Literal.getUDSuffixOffset());
1996 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1997 }
1998
1999 return Lit;
2000}
2001
2002std::vector<Token>
2003Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef<Token> Toks) {
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(DC: CurContext);
2015 if (!CurrentDecl)
2016 CurrentDecl = Context.getTranslationUnitDecl();
2017
2018 std::vector<Token> ExpandedToks;
2019 ExpandedToks.reserve(n: Toks.size());
2020 for (const Token &Tok : Toks) {
2021 if (!isFunctionLocalStringLiteralMacro(K: Tok.getKind(), LO: getLangOpts())) {
2022 assert(tok::isStringLiteral(Tok.getKind()));
2023 ExpandedToks.emplace_back(args: 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 << '"'
2043 << Lexer::Stringify(Str: PredefinedExpr::ComputeName(
2044 IK: getPredefinedExprKind(Kind: Tok.getKind()), CurrentDecl))
2045 << '"';
2046 PP.CreateString(Str: OS.str(), Tok&: Exp, ExpansionLocStart: Tok.getLocation(), ExpansionLocEnd: 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///
2057ExprResult
2058Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
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(Toks: 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(Elt: Tok.getLocation());
2073
2074 QualType CharTy = Context.CharTy;
2075 StringLiteralKind Kind = StringLiteralKind::Ordinary;
2076 if (Literal.isWide()) {
2077 CharTy = Context.getWideCharType();
2078 Kind = StringLiteralKind::Wide;
2079 } else if (Literal.isUTF8()) {
2080 if (getLangOpts().Char8)
2081 CharTy = Context.Char8Ty;
2082 Kind = StringLiteralKind::UTF8;
2083 } else if (Literal.isUTF16()) {
2084 CharTy = Context.Char16Ty;
2085 Kind = StringLiteralKind::UTF16;
2086 } else if (Literal.isUTF32()) {
2087 CharTy = Context.Char32Ty;
2088 Kind = StringLiteralKind::UTF32;
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.
2095 if (getLangOpts().CPlusPlus && !getLangOpts().CPlusPlus20 &&
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();
2109 RemovalDiag << FixItHint::CreateRemoval(RemoveRange: CharSourceRange::getCharRange(
2110 B: Tok.getLocation(),
2111 E: Lexer::AdvanceToTokenCharacter(TokStart: Tok.getLocation(), Characters: 2,
2112 SM: getSourceManager(), LangOpts: getLangOpts())));
2113 }
2114 }
2115 Diag(RemovalDiagLoc, RemovalDiag);
2116 }
2117
2118 QualType StrTy =
2119 Context.getStringLiteralArrayType(EltTy: CharTy, Length: Literal.GetNumStringChars());
2120
2121 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2122 StringLiteral *Lit = StringLiteral::Create(Ctx: Context, Str: Literal.GetString(),
2123 Kind, Pascal: Literal.Pascal, Ty: StrTy,
2124 Loc: &StringTokLocs[0],
2125 NumConcatenated: 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(Name: Literal.getUDSuffix());
2131 SourceLocation UDSuffixLoc =
2132 getUDSuffixLoc(S&: *this, TokLoc: StringTokLocs[Literal.getUDSuffixToken()],
2133 Offset: 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 =
2144 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
2145 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2146 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2147
2148 QualType ArgTy[] = {
2149 Context.getArrayDecayedType(T: StrTy), SizeType
2150 };
2151
2152 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2153 switch (LookupLiteralOperator(S: UDLScope, R, ArgTys: ArgTy,
2154 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2155 /*AllowStringTemplatePack*/ AllowStringTemplate: true,
2156 /*DiagnoseMissing*/ true, StringLit: Lit)) {
2157
2158 case LOLR_Cooked: {
2159 llvm::APInt Len(Context.getIntWidth(T: SizeType), Literal.GetNumStringChars());
2160 IntegerLiteral *LenArg = IntegerLiteral::Create(C: Context, V: Len, type: SizeType,
2161 l: 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(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2172 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: std::nullopt,
2173 LitEndLoc: StringTokLocs.back(), ExplicitTemplateArgs: &ExplicitArgs);
2174 }
2175
2176 case LOLR_StringTemplatePack: {
2177 TemplateArgumentListInfo ExplicitArgs;
2178
2179 unsigned CharBits = Context.getIntWidth(T: CharTy);
2180 bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
2181 llvm::APSInt Value(CharBits, CharIsUnsigned);
2182
2183 TemplateArgument TypeArg(CharTy);
2184 TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(T: CharTy));
2185 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(TypeArg, TypeArgInfo));
2186
2187 for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
2188 Value = Lit->getCodeUnit(i: I);
2189 TemplateArgument Arg(Context, Value, CharTy);
2190 TemplateArgumentLocInfo ArgInfo;
2191 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
2192 }
2193 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: std::nullopt,
2194 LitEndLoc: StringTokLocs.back(), ExplicitTemplateArgs: &ExplicitArgs);
2195 }
2196 case LOLR_Raw:
2197 case LOLR_ErrorNoDiagnostic:
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
2205DeclRefExpr *
2206Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2207 SourceLocation Loc,
2208 const CXXScopeSpec *SS) {
2209 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
2210 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
2211}
2212
2213DeclRefExpr *
2214Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2215 const DeclarationNameInfo &NameInfo,
2216 const CXXScopeSpec *SS, NamedDecl *FoundD,
2217 SourceLocation TemplateKWLoc,
2218 const TemplateArgumentListInfo *TemplateArgs) {
2219 NestedNameSpecifierLoc NNS =
2220 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
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.
2227static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema &S,
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>(Val: VD->getInit());
2235 if (!DRE)
2236 return false;
2237 auto *Referee = dyn_cast<VarDecl>(Val: 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>(Val: 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
2254NonOdrUseReason Sema::getNonOdrUseReasonInCurrentContext(ValueDecl *D) {
2255 // A declaration named in an unevaluated operand never constitutes an odr-use.
2256 if (isUnevaluatedContext())
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>(Val: D)) {
2270 if (VD->getType()->isReferenceType() &&
2271 !(getLangOpts().OpenMP && OpenMP().isOpenMPCapturedDecl(D)) &&
2272 !isCapturingReferenceToHostVarInCUDADeviceLambda(S: *this, VD) &&
2273 VD->isUsableInConstantExpressions(C: 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.
2284DeclRefExpr *
2285Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
2286 const DeclarationNameInfo &NameInfo,
2287 NestedNameSpecifierLoc NNS, NamedDecl *FoundD,
2288 SourceLocation TemplateKWLoc,
2289 const TemplateArgumentListInfo *TemplateArgs) {
2290 bool RefersToCapturedVariable = isa<VarDecl, BindingDecl>(Val: D) &&
2291 NeedToCaptureVariable(Var: D, Loc: NameInfo.getLoc());
2292
2293 DeclRefExpr *E = DeclRefExpr::Create(
2294 Context, QualifierLoc: NNS, TemplateKWLoc, D, RefersToEnclosingVariableOrCapture: RefersToCapturedVariable, NameInfo, T: Ty,
2295 VK, FoundD, TemplateArgs, NOUR: getNonOdrUseReasonInCurrentContext(D));
2296 MarkDeclRefReferenced(E);
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(ESpecType: FPT->getExceptionSpecType())) {
2312 if (const auto *NewFPT = ResolveExceptionSpec(Loc: NameInfo.getLoc(), FPT))
2313 E->setType(Context.getQualifiedType(NewFPT, Ty.getQualifiers()));
2314 }
2315 }
2316
2317 if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
2318 Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
2319 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getBeginLoc()))
2320 getCurFunction()->recordUseOfWeak(E);
2321
2322 const auto *FD = dyn_cast<FieldDecl>(Val: D);
2323 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(Val: 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())
2329 E->setObjectKind(OK_BitField);
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>(Val: 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
2351Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
2352 TemplateArgumentListInfo &Buffer,
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(In: TemplateArgsPtr, Out&: Buffer);
2362
2363 TemplateName TName = Id.TemplateId->Template.get();
2364 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
2365 NameInfo = Context.getNameForTemplate(Name: TName, NameLoc: TNameLoc);
2366 TemplateArgs = &Buffer;
2367 } else {
2368 NameInfo = GetNameFromUnqualifiedId(Name: Id);
2369 TemplateArgs = nullptr;
2370 }
2371}
2372
2373static void emitEmptyLookupTypoDiagnostic(
2374 const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
2375 DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
2376 unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
2377 DeclContext *Ctx =
2378 SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, EnteringContext: 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(LO: 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(Correction: TC, TypoDiag: SemaRef.PDiag(DiagID: DiagnosticSuggestID) << Typo,
2398 PrevNote: SemaRef.PDiag(DiagID: 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.
2414bool Sema::DiagnoseDependentMemberLookup(const LookupResult &R) {
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 ==
2421 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
2422 const auto *CurMethod = dyn_cast<CXXMethodDecl>(Val: 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;
2434 if (R.getRepresentativeDecl()->getDeclContext()->Equals(R.getNamingClass())) {
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(InsertionLoc: R.getNameLoc(), Code: "this->");
2447 CheckCXXThisCapture(Loc: R.getNameLoc());
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
2476bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
2477 CorrectionCandidateCallback &CCC,
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>(Val: DC)) {
2500 LookupQualifiedName(R, LookupCtx: DC);
2501
2502 if (!R.empty()) {
2503 // Don't give errors about ambiguities in this lookup.
2504 R.suppressDiagnostics();
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(),
2509 OverloadCandidateSet::CSK_Normal);
2510 AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args, CandidateSet&: Candidates);
2511 OverloadCandidateSet::iterator Best;
2512 if (Candidates.BestViableFunction(S&: *this, Loc: R.getNameLoc(), Best) ==
2513 OR_Success) {
2514 R.clear();
2515 R.addDecl(D: Best->FoundDecl.getDecl(), AS: Best->FoundDecl.getAccess());
2516 R.resolveKind();
2517 }
2518
2519 return DiagnoseDependentMemberLookup(R);
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 Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, CCC,
2536 TDG: [=](const TypoCorrection &TC) {
2537 emitEmptyLookupTypoDiagnostic(TC, SemaRef&: *this, SS, Typo: Name, TypoLoc, Args,
2538 DiagnosticID: diagnostic, DiagnosticSuggestID: diagnostic_suggest);
2539 },
2540 TRC: nullptr, Mode: CTK_ErrorRecovery, MemberContext: LookupCtx);
2541 if (*Out)
2542 return true;
2543 } else if (S && (Corrected =
2544 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S,
2545 SS: &SS, CCC, Mode: CTK_ErrorRecovery, MemberContext: LookupCtx))) {
2546 std::string CorrectedStr(Corrected.getAsString(LO: 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()) {
2556 OverloadCandidateSet OCS(R.getNameLoc(),
2557 OverloadCandidateSet::CSK_Normal);
2558 OverloadCandidateSet::iterator Best;
2559 for (NamedDecl *CD : Corrected) {
2560 if (FunctionTemplateDecl *FTD =
2561 dyn_cast<FunctionTemplateDecl>(Val: CD))
2562 AddTemplateOverloadCandidate(
2563 FunctionTemplate: FTD, FoundDecl: DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
2564 Args, CandidateSet&: OCS);
2565 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: CD))
2566 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
2567 AddOverloadCandidate(Function: FD, FoundDecl: DeclAccessPair::make(FD, AS_none),
2568 Args, CandidateSet&: OCS);
2569 }
2570 switch (OCS.BestViableFunction(S&: *this, Loc: 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(D: 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>(
2590 ND->getDeclContext()->getRedeclContext());
2591 R.setNamingClass(Record);
2592 }
2593
2594 auto *UnderlyingND = ND->getUnderlyingDecl();
2595 AcceptableWithRecovery = isa<ValueDecl>(Val: UnderlyingND) ||
2596 isa<FunctionTemplateDecl>(Val: 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>(Val: UnderlyingND) ||
2603 getAsTypeTemplateDecl(UnderlyingND) ||
2604 isa<ObjCInterfaceDecl>(Val: 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(Correction: Corrected, TypoDiag: PDiag(DiagID: diagnostic_suggest) << Name,
2617 PrevNote: PDiag(DiagID: NoteID), ErrorRecovery: 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 *
2651recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
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>(Val: 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(InsertionLoc: Loc, Code: "this->");
2674 return CXXDependentScopeMemberExpr::Create(
2675 Ctx: Context, /*This=*/Base: nullptr, BaseType: ThisType, /*IsArrow=*/true,
2676 /*Op=*/OperatorLoc: SourceLocation(), QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc,
2677 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: 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, Qualifier: NNS, R: SourceRange(Loc, Loc));
2686 return DependentScopeDeclRefExpr::Create(
2687 Context, QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2688 TemplateArgs);
2689}
2690
2691ExprResult
2692Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2693 SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2694 bool HasTrailingLParen, bool IsAddressOfOperand,
2695 CorrectionCandidateCallback *CCC,
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, Buffer&: 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, EnteringContext: 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: 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: &SS)) {
2756 if (auto *VD = dyn_cast<ValueDecl>(Val: 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(D: VD, Ty: type, VK: VK_LValue, Loc: NameLoc);
2761 }
2762 }
2763 }
2764
2765 // Perform the required lookup.
2766 LookupResult R(*this, NameInfo,
2767 (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2768 ? LookupObjCImplicitSelfParam
2769 : LookupOrdinaryName);
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, ObjectType: QualType(), /*EnteringContext=*/false,
2779 MemberOfUnknownSpecialization, RequiredTemplate: TemplateKWLoc,
2780 ATK: &AssumedTemplate))
2781 return ExprError();
2782
2783 if (MemberOfUnknownSpecialization ||
2784 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2785 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2786 isAddressOfOperand: IsAddressOfOperand, TemplateArgs);
2787 } else {
2788 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2789 LookupParsedName(R, S, SS: &SS, AllowBuiltinCreation: !IvarLookupFollowUp);
2790
2791 // If the result might be in a dependent base class, this is a dependent
2792 // id-expression.
2793 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2794 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2795 isAddressOfOperand: 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(LookUp&: R, S, II, AllowBuiltinCreation: 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(Loc: NameLoc, II&: *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(S&: *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 ? *CCC : DefaultValidator, ExplicitTemplateArgs: nullptr,
2853 Args: std::nullopt, LookupCtx: nullptr, Out: &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(LookUp&: R, S, II: 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, RequiresADL: ADL, TemplateArgs);
2937 }
2938
2939 return BuildDeclarationNameExpr(SS, R, NeedsADL: 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.
2946ExprResult Sema::BuildQualifiedDeclarationNameExpr(
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, EnteringContext: 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, LookupCtx: DC);
2963
2964 if (R.isAmbiguous())
2965 return ExprError();
2966
2967 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
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>(Val: 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(InsertionLoc: Loc, Code: "typename ");
3003
3004 // Recover by pretending this was an elaborated type.
3005 QualType Ty = Context.getTypeDeclType(Decl: TD);
3006 TypeLocBuilder TLB;
3007 TLB.pushTypeSpec(T: Ty).setNameLoc(NameInfo.getLoc());
3008
3009 QualType ET = getElaboratedType(Keyword: ElaboratedTypeKeyword::None, SS, T: Ty);
3010 ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(T: ET);
3011 QTL.setElaboratedKeywordLoc(SourceLocation());
3012 QTL.setQualifierLoc(SS.getWithLocInContext(Context));
3013
3014 *RecoveryTSI = TLB.getTypeSourceInfo(Context, T: 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)
3024 return BuildPossibleImplicitMemberExpr(SS,
3025 /*TemplateKWLoc=*/SourceLocation(),
3026 R, /*TemplateArgs=*/nullptr, S);
3027
3028 return BuildDeclarationNameExpr(SS, R, /* ADL */ NeedsADL: 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.
3037DeclResult Sema::LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
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() &&
3064 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
3065 ObjCInterfaceDecl *IFace = nullptr;
3066 if (LookForIvars) {
3067 IFace = CurMethod->getClassInterface();
3068 ObjCInterfaceDecl *ClassDeclared;
3069 ObjCIvarDecl *IV = nullptr;
3070 if (IFace && (IV = IFace->lookupInstanceVariable(IVarName: 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.
3078 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
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(IVarName: 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() &&
3097 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
3098 // If accessing a stand-alone ivar in a class method, this is an error.
3099 if (const ObjCIvarDecl *IV =
3100 dyn_cast<ObjCIvarDecl>(Val: 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
3110ExprResult Sema::BuildIvarRefExpr(Scope *S, SourceLocation Loc,
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(Name: "self");
3131 UnqualifiedId SelfName;
3132 SelfName.setImplicitSelfParam(&II);
3133 CXXScopeSpec SelfScopeSpec;
3134 SourceLocation TemplateKWLoc;
3135 ExprResult SelfExpr =
3136 ActOnIdExpression(S, SS&: SelfScopeSpec, TemplateKWLoc, Id&: SelfName,
3137 /*HasTrailingLParen=*/false,
3138 /*IsAddressOfOperand=*/false);
3139 if (SelfExpr.isInvalid())
3140 return ExprError();
3141
3142 SelfExpr = DefaultLvalueConversion(E: 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
3153 ObjCIvarRefExpr *Result = new (Context)
3154 ObjCIvarRefExpr(IV, IV->getUsageType(objectType: SelfExpr.get()->getType()), Loc,
3155 IV->getLocation(), SelfExpr.get(), true, true);
3156
3157 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3158 if (!isUnevaluatedContext() &&
3159 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
3160 getCurFunction()->recordUseOfWeak(E: Result);
3161 }
3162 if (getLangOpts().ObjCAutoRefCount && !isUnevaluatedContext())
3163 if (const BlockDecl *BD = CurContext->getInnermostBlockDecl())
3164 ImplicitlyRetainedSelfLocs.push_back(Elt: {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.
3173ExprResult
3174Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
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, Loc: Lookup.getNameLoc(),
3182 IV: cast<ObjCIvarDecl>(Val: Ivar.get()));
3183
3184 if (Lookup.empty() && II && AllowBuiltinCreation)
3185 LookupBuiltin(R&: 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.
3211ExprResult
3212Sema::PerformObjectMemberConversion(Expr *From,
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>(Val: Member)) {
3226 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(Decl: RD));
3227 auto FromPtrType = FromType->getAs<PointerType>();
3228 DestRecordType = Context.getAddrSpaceQualType(
3229 T: DestRecordType, AddressSpace: FromPtrType
3230 ? FromType->getPointeeType().getAddressSpace()
3231 : FromType.getAddressSpace());
3232
3233 if (FromPtrType) {
3234 DestType = Context.getPointerType(T: 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>(Val: 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(T: FromRecordType);
3261 QualType FromTypeWithDestAS =
3262 Context.getAddrSpaceQualType(T: FromRecordTypeWithoutAS, AddressSpace: DestAS);
3263 if (PointerConversions)
3264 FromTypeWithDestAS = Context.getPointerType(T: FromTypeWithDestAS);
3265 From = ImpCastExprToType(E: From, Type: FromTypeWithDestAS,
3266 CK: CK_AddressSpaceConversion, VK: 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(T1: FromRecordType, T2: 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(Loc: FromLoc, Derived: FromRecordType, Base: QRecordType)) {
3314 CXXCastPath BasePath;
3315 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: QRecordType,
3316 Loc: FromLoc, Range: FromRange, BasePath: &BasePath))
3317 return ExprError();
3318
3319 if (PointerConversions)
3320 QType = Context.getPointerType(T: QType);
3321 From = ImpCastExprToType(E: From, Type: QType, CK: CK_UncheckedDerivedToBase,
3322 VK, BasePath: &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(T1: FromRecordType, T2: DestRecordType))
3330 return From;
3331 }
3332 }
3333
3334 CXXCastPath BasePath;
3335 if (CheckDerivedToBaseConversion(Derived: FromRecordType, Base: DestRecordType,
3336 Loc: FromLoc, Range: FromRange, BasePath: &BasePath,
3337 /*IgnoreAccess=*/true))
3338 return ExprError();
3339
3340 return ImpCastExprToType(E: From, Type: DestType, CK: CK_UncheckedDerivedToBase,
3341 VK, BasePath: &BasePath);
3342}
3343
3344bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
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>(Val: D))
3376 D = cast<UsingShadowDecl>(Val: 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>(Val: D)) {
3385 // But also builtin functions.
3386 if (FDecl->getBuiltinID() && FDecl->isImplicit())
3387 return false;
3388 } else if (!isa<FunctionTemplateDecl>(Val: 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.
3400static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D,
3401 bool AcceptInvalid) {
3402 if (D->isInvalidDecl() && !AcceptInvalid)
3403 return true;
3404
3405 if (isa<TypedefNameDecl>(Val: D)) {
3406 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
3407 return true;
3408 }
3409
3410 if (isa<ObjCInterfaceDecl>(Val: D)) {
3411 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
3412 return true;
3413 }
3414
3415 if (isa<NamespaceDecl>(Val: 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.
3425static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
3426 assert(R.isSingleResult() && "Expected only a single result");
3427 const auto *FD = dyn_cast<FunctionDecl>(Val: R.getFoundDecl());
3428 return FD &&
3429 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
3430}
3431
3432ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
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() &&
3438 !R.getAsSingle<FunctionTemplateDecl>() &&
3439 !ShouldLookupResultBeMultiVersionOverload(R))
3440 return BuildDeclarationNameExpr(SS, NameInfo: R.getLookupNameInfo(), D: R.getFoundDecl(),
3441 FoundD: R.getRepresentativeDecl(), TemplateArgs: 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.
3447 if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
3448 CheckDeclInExpr(S&: *this, Loc: R.getNameLoc(), D: R.getFoundDecl(),
3449 AcceptInvalid: 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.
3455 R.suppressDiagnostics();
3456
3457 UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
3458 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
3459 NameInfo: R.getLookupNameInfo(), RequiresADL: NeedsADL, Begin: R.begin(), End: R.end(),
3460 /*KnownDependent=*/false);
3461
3462 return ULE;
3463}
3464
3465static void diagnoseUncapturableValueReferenceOrBinding(Sema &S,
3466 SourceLocation loc,
3467 ValueDecl *var);
3468
3469/// Complete semantic analysis for a reference to the given declaration.
3470ExprResult Sema::BuildDeclarationNameExpr(
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(S&: *this, Loc, D, AcceptInvalid: 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(Begin: NameInfo.getBeginLoc(), End: NameInfo.getEndLoc(), SubExprs: {});
3484 }
3485
3486 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Val: D)) {
3487 // Specifically diagnose references to class templates that are missing
3488 // a template argument list.
3489 diagnoseMissingTemplateArguments(Name: TemplateName(Template), Loc);
3490 return ExprError();
3491 }
3492
3493 // Make sure that we're referring to a value.
3494 if (!isa<ValueDecl, UnresolvedUsingIfExistsDecl>(Val: 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, Locs: Loc))
3505 return ExprError();
3506
3507 auto *VD = cast<ValueDecl>(Val: 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>(Val: VD);
3517 IndirectField && !IndirectField->isCXXClassMember())
3518 return BuildAnonymousStructUnionMemberReference(SS, nameLoc: NameInfo.getLoc(),
3519 indirectField: 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(Var: 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()) {
3634 if (!Context.BuiltinInfo.isDirectlyAddressable(ID: BID)) {
3635 type = Context.BuiltinFnTy;
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) {
3646 type = 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))
3663 type = Context.getFunctionNoProtoType(ResultTy: fty->getReturnType(),
3664 Info: 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) {
3693 type = 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(D: VD, Ty: type, VK: valueKind, NameInfo, SS: &SS, FoundD,
3714 /*FIXME: TemplateKWLoc*/ 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,
3725 SmallString<32> &Target) {
3726 Target.resize(N: CharByteWidth * (Source.size() + 1));
3727 char *ResultPtr = &Target[0];
3728 const llvm::UTF8 *ErrorPtr;
3729 bool success =
3730 llvm::ConvertUTF8toWide(WideCharWidth: CharByteWidth, Source, ResultPtr, ErrorPtr);
3731 (void)success;
3732 assert(success);
3733 Target.resize(N: ResultPtr - &Target[0]);
3734}
3735
3736ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3737 PredefinedIdentKind IK) {
3738 Decl *currentDecl = getPredefinedExprDecl(DC: 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>(Val: 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: currentDecl, ForceElaboratedPrinting);
3755 unsigned Length = Str.length();
3756
3757 llvm::APInt LengthI(32, Length + 1);
3758 if (IK == PredefinedIdentKind::LFunction ||
3759 IK == PredefinedIdentKind::LFuncSig) {
3760 ResTy =
3761 Context.adjustStringLiteralBaseType(StrLTy: Context.WideCharTy.withConst());
3762 SmallString<32> RawChars;
3763 ConvertUTF8ToWideString(CharByteWidth: Context.getTypeSizeInChars(T: ResTy).getQuantity(),
3764 Source: Str, Target&: RawChars);
3765 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3766 ASM: ArraySizeModifier::Normal,
3767 /*IndexTypeQuals*/ 0);
3768 SL = StringLiteral::Create(Ctx: Context, Str: RawChars, Kind: StringLiteralKind::Wide,
3769 /*Pascal*/ false, Ty: ResTy, Loc);
3770 } else {
3771 ResTy = Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst());
3772 ResTy = Context.getConstantArrayType(EltTy: ResTy, ArySize: LengthI, SizeExpr: nullptr,
3773 ASM: ArraySizeModifier::Normal,
3774 /*IndexTypeQuals*/ 0);
3775 SL = StringLiteral::Create(Ctx: Context, Str, Kind: StringLiteralKind::Ordinary,
3776 /*Pascal*/ false, Ty: ResTy, Loc);
3777 }
3778 }
3779
3780 return PredefinedExpr::Create(Ctx: Context, L: Loc, FNTy: ResTy, IK, IsTransparent: LangOpts.MicrosoftExt,
3781 SL);
3782}
3783
3784ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3785 return BuildPredefinedExpr(Loc, IK: getPredefinedExprKind(Kind));
3786}
3787
3788ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3789 SmallString<16> CharBuffer;
3790 bool Invalid = false;
3791 StringRef ThisTok = PP.getSpelling(Tok, Buffer&: CharBuffer, Invalid: &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
3817 CharacterLiteralKind Kind = CharacterLiteralKind::Ascii;
3818 if (Literal.isWide())
3819 Kind = CharacterLiteralKind::Wide;
3820 else if (Literal.isUTF16())
3821 Kind = CharacterLiteralKind::UTF16;
3822 else if (Literal.isUTF32())
3823 Kind = CharacterLiteralKind::UTF32;
3824 else if (Literal.isUTF8())
3825 Kind = CharacterLiteralKind::UTF8;
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(Name: Literal.getUDSuffix());
3835 SourceLocation UDSuffixLoc =
3836 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: 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(S&: *this, Scope: UDLScope, UDSuffix, UDSuffixLoc,
3845 Args: Lit, LitEndLoc: Tok.getLocation());
3846}
3847
3848ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3849 unsigned IntSize = Context.getTargetInfo().getIntWidth();
3850 return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3851 Context.IntTy, Loc);
3852}
3853
3854static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3855 QualType Ty, SourceLocation Loc) {
3856 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(T: Ty);
3857
3858 using llvm::APFloat;
3859 APFloat Val(Format);
3860
3861 APFloat::opStatus result = Literal.GetFloatValue(Result&: 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(Sem: Format).toString(Str&: buffer);
3872 } else {
3873 diagnostic = diag::warn_float_underflow;
3874 APFloat::getSmallest(Sem: Format).toString(Str&: 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(C: S.Context, V: Val, isexact: isExact, Type: Ty, L: 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;
3899 ExprResult R = VerifyIntegerConstantExpression(E, Result: &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
3920ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
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(Loc: Tok.getLocation(), Val: 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(N: 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, Buffer&: SpellingBuffer, Invalid: &Invalid);
3938 if (Invalid)
3939 return ExprError();
3940
3941 NumericLiteralParser Literal(TokSpelling, Tok.getLocation(),
3942 PP.getSourceManager(), PP.getLangOpts(),
3943 PP.getTargetInfo(), PP.getDiagnostics());
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(Name: Literal.getUDSuffix());
3950 SourceLocation UDSuffixLoc =
3951 getUDSuffixLoc(S&: *this, TokLoc: Tok.getLocation(), Offset: 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 =
3971 Context.DeclarationNames.getCXXLiteralOperatorName(II: UDSuffix);
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(S: UDLScope, R, ArgTys: CookedTy,
3981 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3982 /*AllowStringTemplatePack*/ AllowStringTemplate: false,
3983 /*DiagnoseMissing*/ !Literal.isImaginary)) {
3984 case LOLR_ErrorNoDiagnostic:
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(S&: *this, Literal, Ty: CookedTy, Loc: 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(C: Context, V: ResultVal, type: CookedTy,
4000 l: Tok.getLocation());
4001 }
4002 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: 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();
4010 QualType StrTy = Context.getConstantArrayType(
4011 EltTy: Context.adjustStringLiteralBaseType(StrLTy: Context.CharTy.withConst()),
4012 ArySize: llvm::APInt(32, Length + 1), SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0);
4013 Expr *Lit =
4014 StringLiteral::Create(Ctx: Context, Str: StringRef(TokSpelling.data(), Length),
4015 Kind: StringLiteralKind::Ordinary,
4016 /*Pascal*/ false, Ty: StrTy, Loc: &TokLoc, NumConcatenated: 1);
4017 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: Lit, LitEndLoc: 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(T: 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];
4031 TemplateArgument Arg(Context, Value, Context.CharTy);
4032 TemplateArgumentLocInfo ArgInfo;
4033 ExplicitArgs.addArgument(Loc: TemplateArgumentLoc(Arg, ArgInfo));
4034 }
4035 return BuildLiteralOperatorCall(R, SuffixInfo&: OpNameInfo, Args: std::nullopt, LitEndLoc: TokLoc,
4036 ExplicitTemplateArgs: &ExplicitArgs);
4037 }
4038 case LOLR_StringTemplatePack:
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(T: Ty);
4067
4068 bool isSigned = !Literal.isUnsigned;
4069 unsigned scale = Context.getFixedPointScale(Ty);
4070 unsigned bit_width = Context.getTypeInfo(T: Ty).Width;
4071
4072 llvm::APInt Val(bit_width, 0, isSigned);
4073 bool Overflowed = Literal.GetFixedPointValue(StoreVal&: Val, Scale: 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
4086 Res = FixedPointLiteral::CreateFromRawInt(C: Context, V: Val, type: Ty,
4087 l: Tok.getLocation(), Scale: scale);
4088 } else if (Literal.isFloatingLiteral()) {
4089 QualType Ty;
4090 if (Literal.isHalf){
4091 if (getLangOpts().HLSL ||
4092 getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16", LO: 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)
4101 Ty = !getLangOpts().HLSL ? Context.LongDoubleTy : Context.DoubleTy;
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(S&: *this, Literal, Ty, Loc: Tok.getLocation());
4110
4111 if (Ty == Context.DoubleTy) {
4112 if (getLangOpts().SinglePrecisionConstants) {
4113 if (Ty->castAs<BuiltinType>()->getKind() != BuiltinType::Float) {
4114 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: CK_FloatingCast).get();
4115 }
4116 } else if (getLangOpts().OpenCL && !getOpenCLOptions().isAvailableOption(
4117 Ext: "cl_khr_fp64", LO: getLangOpts())) {
4118 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4119 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64)
4120 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
4121 Res = ImpCastExprToType(E: Res, Type: Context.FloatTy, CK: 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)
4131 Diag(Tok.getLocation(), getLangOpts().CPlusPlus
4132 ? getLangOpts().CPlusPlus23
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 Str: Literal.getLiteralDigits(), Radix: Literal.getRadix())
4158 : Context.getTargetInfo().getIntMaxTWidth();
4159 llvm::APInt ResultVal(BitsNeeded, 0);
4160
4161 if (Literal.GetIntegerValue(Val&: 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;
4165 Ty = Context.UnsignedLongLongTy;
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(DestWidth: 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(a: ResultVal.getActiveBits(), b: 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 =
4202 Context.getTargetInfo().getMaxBitIntWidth();
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: Width);
4214 Ty = Context.getBitIntType(Unsigned: Literal.isUnsigned, NumBits: 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(
4222 T: Context.getTargetInfo().getSizeType());
4223
4224 // Does it fit in size_t?
4225 if (ResultVal.isIntN(N: SizeTSize)) {
4226 // Does it fit in ssize_t?
4227 if (!Literal.isUnsigned && ResultVal[SizeTSize - 1] == 0)
4228 Ty = Context.getSignedSizeType();
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(N: 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)
4246 Ty = Context.UnsignedIntTy;
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(N: 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)
4261 Ty = Context.UnsignedLongTy;
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 =
4266 Context.getTargetInfo().getLongLongWidth();
4267 Diag(Tok.getLocation(),
4268 getLangOpts().CPlusPlus
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);
4276 Ty = Context.UnsignedLongTy;
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(N: 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)
4295 Ty = Context.UnsignedLongLongTy;
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);
4319 Ty = Context.UnsignedLongLongTy;
4320 Width = Context.getTargetInfo().getLongLongWidth();
4321 }
4322
4323 if (ResultVal.getBitWidth() != Width)
4324 ResultVal = ResultVal.trunc(width: Width);
4325 }
4326 Res = IntegerLiteral::Create(C: Context, V: ResultVal, type: Ty, l: 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,
4332 Context.getComplexType(T: Res->getType()));
4333
4334 Diag(Tok.getLocation(), diag::ext_imaginary_constant);
4335 }
4336 return Res;
4337}
4338
4339ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
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
4348static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
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
4366static bool CheckVectorElementsTraitOperandType(Sema &S, QualType T,
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
4378static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
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(T: TraitKind) << ArgRange;
4402 return false;
4403 }
4404
4405 return true;
4406}
4407
4408static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
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.
4414 if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
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.
4426static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
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>(Val: 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.
4449bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
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) {
4459 ExprResult Result = CheckUnevaluatedOperand(E);
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() &&
4471 !E->isInstantiationDependent() &&
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() &&
4492 E->getType()->isWebAssemblyTableType()) {
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) {
4503 if (RequireCompleteSizedType(
4504 E->getExprLoc(), Context.getBaseElementType(E->getType()),
4505 diag::err_sizeof_alignof_incomplete_or_sizeless_type,
4506 getTraitSpelling(ExprKind), E->getSourceRange()))
4507 return true;
4508 } else {
4509 if (RequireCompleteSizedExprType(
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>(Val: E->IgnoreParens())) {
4531 if (const auto *PVD = dyn_cast<ParmVarDecl>(Val: 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>(Val: 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>(Val: Inner)) {
4570 D = DRE->getDecl();
4571 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: 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>(Val: 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
4612bool Sema::CheckVecStepExpr(Expr *E) {
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, ExprKind: UETT_VecStep);
4620}
4621
4622static void captureVariablyModifiedType(ASTContext &Context, QualType T,
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(Loc: Size->getExprLoc(), VLAType: VAT, CaptureType: 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.
4755bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
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(QT: ExprType);
4778
4779 if (ExprKind == UETT_VecStep)
4780 return CheckVecStepTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange);
4781
4782 if (ExprKind == UETT_VectorElements)
4783 return CheckVectorElementsTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc,
4784 ArgRange: ExprRange);
4785
4786 // Explicitly list some types as extensions.
4787 if (!CheckExtensionTraitOperandType(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4788 TraitKind: ExprKind))
4789 return false;
4790
4791 if (RequireCompleteSizedType(
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(S&: *this, T: ExprType, Loc: OpLoc, ArgRange: ExprRange,
4811 TraitKind: 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(x: FunctionScopes.rend());
4818 I != E; ++I) {
4819 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
4820 if (CSI == nullptr)
4821 break;
4822 DeclContext *DC = nullptr;
4823 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
4824 DC = LSI->CallOperator;
4825 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
4826 DC = CRSI->TheCapturedDecl;
4827 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
4828 DC = BSI->TheDecl;
4829 if (DC) {
4830 if (DC->containsDecl(TT->getDecl()))
4831 break;
4832 captureVariablyModifiedType(Context, T: ExprType, CSI);
4833 }
4834 }
4835 }
4836 }
4837
4838 return false;
4839}
4840
4841/// Build a sizeof or alignof expression given a type operand.
4842ExprResult Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
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(ExprType: T, OpLoc, ExprRange: R, ExprKind,
4853 KWName: getTraitSpelling(T: 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.
4869ExprResult
4870Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4871 UnaryExprOrTypeTrait ExprKind) {
4872 ExprResult PE = CheckPlaceholderExpr(E);
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(S&: *this, E, ExprKind);
4884 } else if (ExprKind == UETT_VecStep) {
4885 isInvalid = CheckVecStepExpr(E);
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, ExprKind: UETT_VectorElements);
4894 } else {
4895 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, ExprKind: UETT_SizeOf);
4896 }
4897
4898 if (isInvalid)
4899 return ExprError();
4900
4901 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4902 PE = TransformToPotentiallyEvaluated(E);
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.
4915ExprResult
4916Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
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(Ty: ParsedType::getFromOpaquePtr(P: TyOrEx), TInfo: &TInfo);
4925 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R: ArgRange);
4926 }
4927
4928 Expr *ArgEx = (Expr *)TyOrEx;
4929 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(E: ArgEx, OpLoc, ExprKind);
4930 return Result;
4931}
4932
4933bool Sema::CheckAlignasTypeArgument(StringRef KWName, TypeSourceInfo *TInfo,
4934 SourceLocation OpLoc, SourceRange R) {
4935 if (!TInfo)
4936 return true;
4937 return CheckUnaryExprOrTypeTraitOperand(ExprType: TInfo->getType(), OpLoc, ExprRange: R,
4938 ExprKind: 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)).
4948bool Sema::ActOnAlignasTypeArgument(StringRef KWName, ParsedType Ty,
4949 SourceLocation OpLoc, SourceRange R) {
4950 TypeSourceInfo *TInfo;
4951 (void)GetTypeFromParser(Ty: ParsedType::getFromOpaquePtr(P: Ty.getAsOpaquePtr()),
4952 TInfo: &TInfo);
4953 return CheckAlignasTypeArgument(KWName, TInfo, OpLoc, R);
4954}
4955
4956static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
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(E: 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(E: 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
4992ExprResult
4993Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4994 tok::TokenKind Kind, Expr *Input) {
4995 UnaryOperatorKind Opc;
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.
5003 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Input);
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
5013static bool checkArithmeticOnObjCPointer(Sema &S,
5014 SourceLocation opLoc,
5015 Expr *op) {
5016 assert(op->getType()->isObjCObjectPointerType());
5017 if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
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
5027static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
5028 auto *BaseNoParens = Base->IgnoreParens();
5029 if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(Val: BaseNoParens))
5030 return MSProp->getPropertyDecl()->getType()->isArrayType();
5031 return isa<MSPropertySubscriptExpr>(Val: 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
5046static QualType getDependentArraySubscriptType(Expr *LHS, Expr *RHS,
5047 const ASTContext &Ctx) {
5048 assert(LHS->isTypeDependent() || RHS->isTypeDependent());
5049 QualType LTy = LHS->getType(), RTy = RHS->getType();
5050 QualType Result = Ctx.DependentTy;
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
5066ExprResult Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base,
5067 SourceLocation lbLoc,
5068 MultiExprArg ArgExprs,
5069 SourceLocation rbLoc) {
5070
5071 if (base && !base->getType().isNull() &&
5072 base->hasPlaceholderType(K: BuiltinType::OMPArraySection))
5073 return OpenMP().ActOnOMPArraySectionExpr(Base: base, LBLoc: lbLoc, LowerBound: ArgExprs.front(),
5074 ColonLocFirst: SourceLocation(), ColonLocSecond: SourceLocation(),
5075 /*Length*/ nullptr,
5076 /*Stride=*/nullptr, RBLoc: rbLoc);
5077
5078 // Since this might be a postfix expression, get rid of ParenListExprs.
5079 if (isa<ParenListExpr>(Val: base)) {
5080 ExprResult result = MaybeConvertParenListExprToParenExpr(S, ME: 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>(Val: E) && cast<BinaryOperator>(Val: 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(K: BuiltinType::IncompleteMatrixIdx) &&
5102 !isa<MatrixSubscriptExpr>(Val: 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>(Val: 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(Base: matSubscriptE->getBase(),
5118 RowIdx: matSubscriptE->getRowIdx(),
5119 ColumnIdx: ArgExprs.front(), RBLoc: 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(S&: *this, Base: base);
5135 if (!IsMSPropertySubscript) {
5136 ExprResult result = CheckPlaceholderExpr(E: 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: base, RowIdx: ArgExprs.front(), ColumnIdx: nullptr,
5150 RBLoc: rbLoc);
5151 }
5152
5153 if (ArgExprs.size() == 1 && getLangOpts().CPlusPlus20) {
5154 Expr *idx = ArgExprs[0];
5155 if ((isa<BinaryOperator>(Val: idx) && cast<BinaryOperator>(Val: idx)->isCommaOp()) ||
5156 (isa<CXXOperatorCallExpr>(Val: idx) &&
5157 cast<CXXOperatorCallExpr>(Val: 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(E: ArgExprs[0]);
5166 if (result.isInvalid())
5167 return ExprError();
5168 ArgExprs[0] = result.get();
5169 } else {
5170 if (CheckArgsForPlaceholders(args: 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() ||
5177 Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs)) &&
5178 !isa<PackExpansionExpr>(Val: ArgExprs[0])) {
5179 return new (Context) ArraySubscriptExpr(
5180 base, ArgExprs.front(),
5181 getDependentArraySubscriptType(LHS: base, RHS: ArgExprs.front(), Ctx: 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>(Val: ArgExprs[0]) ||
5213 ArgExprs[0]->getType()->isRecordType())))) {
5214 return CreateOverloadedArraySubscriptExpr(LLoc: lbLoc, RLoc: rbLoc, Base: base, Args: ArgExprs);
5215 }
5216
5217 ExprResult Res =
5218 CreateBuiltinArraySubscriptExpr(Base: base, LLoc: lbLoc, Idx: ArgExprs.front(), RLoc: rbLoc);
5219
5220 if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Val: Res.get()))
5221 CheckSubscriptAccessOfNoDeref(E: cast<ArraySubscriptExpr>(Val: Res.get()));
5222
5223 return Res;
5224}
5225
5226ExprResult Sema::tryConvertExprToType(Expr *E, QualType Ty) {
5227 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: Ty);
5228 InitializationKind Kind =
5229 InitializationKind::CreateCopy(InitLoc: E->getBeginLoc(), EqualLoc: SourceLocation());
5230 InitializationSequence InitSeq(*this, Entity, Kind, E);
5231 return InitSeq.Perform(S&: *this, Entity, Kind, Args: E);
5232}
5233
5234ExprResult Sema::CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5235 Expr *ColumnIdx,
5236 SourceLocation RBLoc) {
5237 ExprResult BaseR = CheckPlaceholderExpr(E: Base);
5238 if (BaseR.isInvalid())
5239 return BaseR;
5240 Base = BaseR.get();
5241
5242 ExprResult RowR = CheckPlaceholderExpr(E: 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(E: 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(Ctx: 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 =
5284 tryConvertExprToType(E: IndexExpr, Ty: Context.getSizeType());
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>(Val: StrippedExpr)) && !Member->isArrow())
5308 StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
5309
5310 LastRecord.PossibleDerefs.erase(Ptr: StrippedExpr);
5311}
5312
5313void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
5314 if (isUnevaluatedContext())
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>(Val: 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>(Val: BaseTy) || isa<PointerType>(Val: BaseTy)))
5334 // Not a pointer access
5335 return;
5336
5337 const MemberExpr *Member = nullptr;
5338 while ((Member = dyn_cast<MemberExpr>(Val: Base->IgnoreParenCasts())) &&
5339 Member->isArrow())
5340 Base = Member->getBase();
5341
5342 if (const auto *Ptr = dyn_cast<PointerType>(Val: Base->getType())) {
5343 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
5344 LastRecord.PossibleDerefs.insert(E);
5345 }
5346}
5347
5348ExprResult
5349Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5350 Expr *Idx, SourceLocation RLoc) {
5351 Expr *LHSExp = Base;
5352 Expr *RHSExp = Idx;
5353
5354 ExprValueKind VK = VK_LValue;
5355 ExprObjectKind OK = OK_Ordinary;
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>()) {
5369 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: LHSExp);
5370 if (Result.isInvalid())
5371 return ExprError();
5372 LHSExp = Result.get();
5373 }
5374 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: RHSExp);
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 =
5391 getDependentArraySubscriptType(LHS: LHSExp, RHS: RHSExp, Ctx: getASTContext());
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.
5403 if (!LangOpts.isSubscriptPointerArithmetic())
5404 return BuildObjCSubscriptExpression(RB: RLoc, BaseExpr, IndexExpr, getterMethod: nullptr,
5405 setterMethod: 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();
5419 if (!LangOpts.isSubscriptPointerArithmetic()) {
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(E: 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(T: ResultType, Qs: 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(E: 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(T: ResultType, Qs: 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(E: LHSExp, Type: Context.getArrayDecayedType(T: LHSTy),
5481 CK: 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(E: RHSExp, Type: Context.getArrayDecayedType(T: RHSTy),
5492 CK: 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(K: BuiltinType::Char_S) ||
5508 IndexExpr->getType()->isSpecificBuiltinType(K: BuiltinType::Char_U)) &&
5509 !IndexExpr->isTypeDependent()) {
5510 std::optional<llvm::APSInt> IntegerContantExpr =
5511 IndexExpr->getIntegerConstantExpr(Ctx: getASTContext());
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() &&
5538 RequireCompleteSizedType(
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
5546 if (LHSExp->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5547 FunctionScopes.size() > 1) {
5548 if (auto *TT =
5549 LHSExp->IgnoreParenImpCasts()->getType()->getAs<TypedefType>()) {
5550 for (auto I = FunctionScopes.rbegin(),
5551 E = std::prev(x: FunctionScopes.rend());
5552 I != E; ++I) {
5553 auto *CSI = dyn_cast<CapturingScopeInfo>(Val: *I);
5554 if (CSI == nullptr)
5555 break;
5556 DeclContext *DC = nullptr;
5557 if (auto *LSI = dyn_cast<LambdaScopeInfo>(Val: CSI))
5558 DC = LSI->CallOperator;
5559 else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI))
5560 DC = CRSI->TheCapturedDecl;
5561 else if (auto *BSI = dyn_cast<BlockScopeInfo>(Val: CSI))
5562 DC = BSI->TheDecl;
5563 if (DC) {
5564 if (DC->containsDecl(TT->getDecl()))
5565 break;
5566 captureVariablyModifiedType(
5567 Context, T: LHSExp->IgnoreParenImpCasts()->getType(), CSI);
5568 }
5569 }
5570 }
5571 }
5572
5573 return new (Context)
5574 ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
5575}
5576
5577bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
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(Val: 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());
5593 Diag(UnparsedDefaultArgLocs[Param],
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.
5628 EnterExpressionEvaluationContext EvalContext(
5629 *this,
5630 FD->isImmediateFunction()
5631 ? ExpressionEvaluationContext::ImmediateFunctionContext
5632 : ExpressionEvaluationContext::PotentiallyEvaluated,
5633 Param);
5634 ExprEvalContexts.back().IsCurrentlyCheckingDefaultArgumentOrInitializer =
5635 SkipImmediateInvocations;
5636 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5637 MarkDeclarationsReferencedInExpr(E: Init, /*SkipLocalVariables=*/true);
5638 });
5639 return false;
5640}
5641
5642struct ImmediateCallVisitor : public RecursiveASTVisitor<ImmediateCallVisitor> {
5643 const ASTContext &Context;
5644 ImmediateCallVisitor(const ASTContext &Ctx) : Context(Ctx) {}
5645
5646 bool HasImmediateCalls = false;
5647 bool shouldVisitImplicitCode() const { return true; }
5648
5649 bool VisitCallExpr(CallExpr *E) {
5650 if (const FunctionDecl *FD = E->getDirectCallee())
5651 HasImmediateCalls |= FD->isImmediateFunction();
5652 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
5653 }
5654
5655 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
5656 if (const FunctionDecl *FD = E->getConstructor())
5657 HasImmediateCalls |= FD->isImmediateFunction();
5658 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
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.
5665 bool VisitSourceLocExpr(SourceLocExpr *E) {
5666 HasImmediateCalls = true;
5667 return RecursiveASTVisitor<ImmediateCallVisitor>::VisitStmt(E);
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.
5676 bool VisitLambdaExpr(LambdaExpr *E) {
5677 return VisitCXXMethodDecl(E->getCallOperator());
5678 }
5679
5680 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
5681 return TraverseStmt(E->getExpr());
5682 }
5683
5684 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
5685 return TraverseStmt(E->getExpr());
5686 }
5687};
5688
5689struct EnsureImmediateInvocationInDefaultArgs
5690 : TreeTransform<EnsureImmediateInvocationInDefaultArgs> {
5691 EnsureImmediateInvocationInDefaultArgs(Sema &SemaRef)
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.
5698 ExprResult TransformLambdaExpr(LambdaExpr *E) { return E; }
5699 ExprResult TransformBlockExpr(BlockExpr *E) { return E; }
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.
5704 ExprResult TransformCXXThisExpr(CXXThisExpr *E) { return E; }
5705};
5706
5707ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
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 =
5716 OutermostDeclarationWithDelayedImmediateInvocations();
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.
5728 EnterExpressionEvaluationContext EvalContext(
5729 *this,
5730 FD->isImmediateFunction()
5731 ? ExpressionEvaluationContext::ImmediateFunctionContext
5732 : ExpressionEvaluationContext::PotentiallyEvaluated,
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.
5743 ImmediateCallVisitor V(getASTContext());
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.
5755 keepInLifetimeExtendingContext();
5756 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5757 ExprResult Res;
5758 runWithSufficientStackSpace(Loc: CallLoc, Fn: [&] {
5759 Res = Immediate.TransformInitializer(Param->getInit(),
5760 /*NotCopy=*/false);
5761 });
5762 if (Res.isInvalid())
5763 return ExprError();
5764 Res = ConvertParamDefaultArgument(Param, DefaultArg: Res.get(),
5765 EqualLoc: Res.get()->getBeginLoc());
5766 if (Res.isInvalid())
5767 return ExprError();
5768 Init = Res.get();
5769 }
5770 }
5771
5772 if (CheckCXXDefaultArgExpr(
5773 CallLoc, FD, Param, RewrittenInit: Init,
5774 /*SkipImmediateInvocations=*/NestedDefaultChecking))
5775 return ExprError();
5776
5777 return CXXDefaultArgExpr::Create(C: Context, Loc: InitializationContext->Loc, Param,
5778 RewrittenExpr: Init, UsedContext: InitializationContext->Context);
5779}
5780
5781ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
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>(Val: Field->getParent());
5791
5792 std::optional<ExpressionEvaluationContextRecord::InitializationContext>
5793 InitializationContext =
5794 OutermostDeclarationWithDelayedImmediateInvocations();
5795 if (!InitializationContext.has_value())
5796 InitializationContext.emplace(Loc, Field, CurContext);
5797
5798 Expr *Init = nullptr;
5799
5800 bool NestedDefaultChecking = isCheckingDefaultArgumentOrInitializer();
5801
5802 EnterExpressionEvaluationContext EvalContext(
5803 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Field);
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(Kind: ParentRD->getTemplateSpecializationKind())) {
5809 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
5810 DeclContext::lookup_result Lookup =
5811 ClassPattern->lookup(Name: 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(PointOfInstantiation: Loc, Instantiation: Field, Pattern,
5821 TemplateArgs: getTemplateInstantiationArgs(Field))) {
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.
5833 ImmediateCallVisitor V(getASTContext());
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
5842 EnsureImmediateInvocationInDefaultArgs Immediate(*this);
5843 ExprResult Res;
5844 runWithSufficientStackSpace(Loc, Fn: [&] {
5845 Res = Immediate.TransformInitializer(Field->getInClassInitializer(),
5846 /*CXXDirectInit=*/false);
5847 });
5848 if (!Res.isInvalid())
5849 Res = ConvertMemberDefaultInitExpression(FD: Field, InitExpr: Res.get(), InitLoc: 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)
5860 runWithSufficientStackSpace(Loc, Fn: [&] {
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(Expr: E, /*DiscardedValue=*/false);
5867 if (Res.isInvalid()) {
5868 Field->setInvalidDecl();
5869 return ExprError();
5870 }
5871 Init = Res.get();
5872
5873 return CXXDefaultInitExpr::Create(Ctx: Context, Loc: InitializationContext->Loc,
5874 Field, UsedContext: InitializationContext->Context,
5875 RewrittenInitExpr: 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
5903Sema::VariadicCallType
5904Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
5905 Expr *Fn) {
5906 if (Proto && Proto->isVariadic()) {
5907 if (isa_and_nonnull<CXXConstructorDecl>(Val: 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>(Val: 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
5936 return FunctionCallFilterCCC::ValidateCandidate(candidate);
5937 }
5938
5939 std::unique_ptr<CorrectionCandidateCallback> clone() override {
5940 return std::make_unique<FunctionCallCCC>(args&: *this);
5941 }
5942
5943private:
5944 const IdentifierInfo *const FunctionName;
5945};
5946}
5947
5948static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
5949 FunctionDecl *FDecl,
5950 ArrayRef<Expr *> Args) {
5951 MemberExpr *ME = dyn_cast<MemberExpr>(Val: 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(
5957 Typo: DeclarationNameInfo(FuncName, NameLoc), LookupKind: Sema::LookupOrdinaryName,
5958 S: S.getScopeForContext(Ctx: S.CurContext), SS: nullptr, CCC,
5959 Mode: Sema::CTK_ErrorRecovery)) {
5960 if (NamedDecl *ND = Corrected.getFoundDecl()) {
5961 if (Corrected.isOverloaded()) {
5962 OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
5963 OverloadCandidateSet::iterator Best;
5964 for (NamedDecl *CD : Corrected) {
5965 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
5966 S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
5967 OCS);
5968 }
5969 switch (OCS.BestViableFunction(S, Loc: 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>(Val: ND) || isa<FunctionTemplateDecl>(Val: 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
5993Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
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())
6002 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
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(S&: *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;
6028 diagnoseTypo(
6029 Correction: TC, TypoDiag: PDiag(DiagID: 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(S&: *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;
6075 diagnoseTypo(
6076 Correction: TC, TypoDiag: PDiag(DiagID: 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(NewNumArgs: NumParams);
6113 return true;
6114 }
6115 }
6116 SmallVector<Expr *, 8> AllArgs;
6117 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
6118
6119 Invalid = GatherArgumentsForCall(CallLoc: Call->getBeginLoc(), FDecl, Proto, FirstParam: 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(Arg: i, ArgExpr: AllArgs[i]);
6126
6127 Call->computeDependence();
6128 return false;
6129}
6130
6131bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
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(e: 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: i).isNoEscape() &&
6165 ProtoArgType->isBlockPointerType())
6166 if (auto *BE = dyn_cast<BlockExpr>(Val: Arg->IgnoreParenNoopCasts(Ctx: Context)))
6167 BE->getBlockDecl()->setDoesNotEscape();
6168
6169 InitializedEntity Entity =
6170 Param ? InitializedEntity::InitializeParameter(Context, Parm: Param,
6171 Type: ProtoArgType)
6172 : InitializedEntity::InitializeParameter(
6173 Context, Type: ProtoArgType, Consumed: Proto->isParamConsumed(I: i));
6174
6175 // Remember that parameter belongs to a CF audited API.
6176 if (CFAudited)
6177 Entity.setParameterCFAudited();
6178
6179 ExprResult ArgE = PerformCopyInitialization(
6180 Entity, EqualLoc: SourceLocation(), Init: Arg, TopLevelOfInitList: 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, FD: 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(E: Arg);
6199
6200 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6201 CheckStaticArrayArgument(CallLoc, Param, ArgExpr: Arg);
6202
6203 AllArgs.push_back(Elt: 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(N: ArgIx)) {
6213 QualType paramType; // ignored
6214 ExprResult arg = checkUnknownAnyArg(callLoc: CallLoc, result: A, paramType);
6215 Invalid |= arg.isInvalid();
6216 AllArgs.push_back(Elt: arg.get());
6217 }
6218
6219 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6220 } else {
6221 for (Expr *A : Args.slice(N: ArgIx)) {
6222 ExprResult Arg = DefaultVariadicArgumentPromotion(E: A, CT: CallType, FDecl);
6223 Invalid |= Arg.isInvalid();
6224 AllArgs.push_back(Elt: Arg.get());
6225 }
6226 }
6227
6228 // Check for array bounds violations.
6229 for (Expr *A : Args.slice(N: ArgIx))
6230 CheckArrayAccess(E: A);
6231 }
6232 return Invalid;
6233}
6234
6235static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
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
6253Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
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(T: OrigTy);
6263 if (!AT || AT->getSizeModifier() != ArraySizeModifier::Static)
6264 return;
6265
6266 if (ArgExpr->isNullPointerConstant(Ctx&: Context,
6267 NPC: Expr::NPC_NeverValueDependent)) {
6268 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
6269 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6270 return;
6271 }
6272
6273 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: AT);
6274 if (!CAT)
6275 return;
6276
6277 const ConstantArrayType *ArgCAT =
6278 Context.getAsConstantArrayType(T: ArgExpr->IgnoreParenCasts()->getType());
6279 if (!ArgCAT)
6280 return;
6281
6282 if (getASTContext().hasSameUnqualifiedType(T1: CAT->getElementType(),
6283 T2: ArgCAT->getElementType())) {
6284 if (ArgCAT->getSize().ult(RHS: CAT->getSize())) {
6285 Diag(CallLoc, diag::warn_static_array_too_small)
6286 << ArgExpr->getSourceRange() << (unsigned)ArgCAT->getZExtSize()
6287 << (unsigned)CAT->getZExtSize() << 0;
6288 DiagnoseCalleeStaticArrayParam(S&: *this, PVD: Param);
6289 }
6290 return;
6291 }
6292
6293 std::optional<CharUnits> ArgSize =
6294 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
6295 std::optional<CharUnits> ParmSize =
6296 getASTContext().getTypeSizeInCharsIfKnown(CAT);
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(S&: *this, PVD: Param);
6302 }
6303}
6304
6305/// Given a function expression of unknown-any type, try to rebuild it
6306/// to have a function type.
6307static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
6308
6309/// Is the given type a placeholder that we need to lower out
6310/// immediately during argument processing?
6311static bool isPlaceholderToRemoveAsArg(QualType type) {
6312 // Placeholders are never sugared.
6313 const BuiltinType *placeholder = dyn_cast<BuiltinType>(Val&: 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
6373bool Sema::CheckArgsForPlaceholders(MultiExprArg args) {
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(type: args[i]->getType())) {
6379 ExprResult result = CheckPlaceholderExpr(E: 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.
6398static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
6399 FunctionDecl *FDecl,
6400 MultiExprArg ArgExprs) {
6401
6402 QualType DeclType = FDecl->getType();
6403 const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Val&: DeclType);
6404
6405 if (!Context.BuiltinInfo.hasPtrArgsOrResult(ID: 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 =
6417 Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
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() ||
6425 isPtrSizeAddressSpace(ArgType->getPointeeType().getAddressSpace())) {
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
6444 FunctionProtoType::ExtProtoInfo EPI;
6445 EPI.Variadic = FT->isVariadic();
6446 QualType OverloadTy = Context.getFunctionType(ResultTy: FT->getReturnType(),
6447 Args: 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);
6455 SmallVector<ParmVarDecl*, 16> Params;
6456 FT = cast<FunctionProtoType>(Val&: 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(scopeDepth: 0, parameterIndex: i);
6464 Params.push_back(Elt: 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(NumParams: Callee->getNumParams(), NumArgs: 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(Function: Callee, CallLoc: Fn->getBeginLoc(), Args: ArgExprs, MissingImplicitThis: 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
6498static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
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>(Val: 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>(Val: 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 =
6528 UME->getNamingClass()->getCanonicalDecl();
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(Base: NamingClass);
6537}
6538
6539static void
6540tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
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
6557 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
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(Loc: CallLoc, /*Explcit*/ Explicit: false, /*Diagnose*/ BuildAndDiagnose: false))
6569 S.CheckCXXThisCapture(Loc: 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(Loc: 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.
6581static void DiagnosedUnqualifiedCallsToStdFunctions(Sema &S,
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>(Val: E))
6589 return;
6590 const DeclRefExpr *DRE = dyn_cast_if_present<DeclRefExpr>(Val: 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)
6607 << FD->getQualifiedNameAsString()
6608 << FixItHint::CreateInsertion(DRE->getLocation(), "std::");
6609}
6610
6611ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
6612 MultiExprArg ArgExprs, SourceLocation RParenLoc,
6613 Expr *ExecConfig) {
6614 ExprResult Call =
6615 BuildCallExpr(S: 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>(Val: Fn);
6623 ULE && ULE->hasExplicitTemplateArgs() &&
6624 ULE->decls_begin() == ULE->decls_end()) {
6625 Diag(Fn->getExprLoc(), getLangOpts().CPlusPlus20
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>(Val: Call.get()))
6636 DiagnosedUnqualifiedCallsToStdFunctions(S&: *this, Call: CE);
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.
6644ExprResult Sema::BuildCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
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.
6649 ExprResult Result = MaybeConvertParenListExprToParenExpr(S: Scope, ME: Fn);
6650 if (Result.isInvalid()) return ExprError();
6651 Fn = Result.get();
6652
6653 if (CheckArgsForPlaceholders(args: 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>(Val: 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)
6662 << FixItHint::CreateRemoval(
6663 SourceRange(ArgExprs.front()->getBeginLoc(),
6664 ArgExprs.back()->getEndLoc()));
6665 }
6666
6667 return CallExpr::Create(Ctx: Context, Fn, /*Args=*/{}, Ty: Context.VoidTy,
6668 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6669 }
6670 if (Fn->getType() == Context.PseudoObjectTy) {
6671 ExprResult result = CheckPlaceholderExpr(E: 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(Exprs: ArgExprs)) {
6679 if (ExecConfig) {
6680 return CUDAKernelCallExpr::Create(Ctx: Context, Fn,
6681 Config: cast<CallExpr>(Val: ExecConfig), Args: ArgExprs,
6682 Ty: Context.DependentTy, VK: VK_PRValue,
6683 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides());
6684 } else {
6685
6686 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6687 *this, dyn_cast<UnresolvedMemberExpr>(Val: Fn->IgnoreParens()),
6688 Fn->getBeginLoc());
6689
6690 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6691 VK: VK_PRValue, RParenLoc, FPFeatures: 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(S: Scope, Object: Fn, LParenLoc, Args: ArgExprs,
6698 RParenLoc);
6699
6700 if (Fn->getType() == Context.UnknownAnyTy) {
6701 ExprResult result = rebuildUnknownAnyFunction(S&: *this, fn: Fn);
6702 if (result.isInvalid()) return ExprError();
6703 Fn = result.get();
6704 }
6705
6706 if (Fn->getType() == Context.BoundMemberTy) {
6707 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: 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) {
6715 OverloadExpr::FindResult find = OverloadExpr::find(E: Fn);
6716
6717 // We aren't supposed to apply this logic if there's an '&' involved.
6718 if (!find.HasFormOfMemberPointer) {
6719 if (Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))
6720 return CallExpr::Create(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6721 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6722 OverloadExpr *ovl = find.Expression;
6723 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: ovl))
6724 return BuildOverloadedCallExpr(
6725 S: Scope, Fn, ULE, LParenLoc, Args: ArgExprs, RParenLoc, ExecConfig,
6726 /*AllowTypoCorrection=*/true, CalleesAddressIsTaken: find.IsAddressOfOperand);
6727 return BuildCallToMemberFunction(S: Scope, MemExpr: Fn, LParenLoc, Args: 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(S&: *this, fn: 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>(Val: 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>(Val: NakedFn)) {
6752 NDecl = DRE->getDecl();
6753
6754 FunctionDecl *FDecl = dyn_cast<FunctionDecl>(Val: 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(Sema: this, Context, FDecl, ArgExprs))) {
6761 NDecl = FDecl;
6762 Fn = DeclRefExpr::Create(
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>(Val: NakedFn))
6769 NDecl = ME->getMemberDecl();
6770
6771 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: NDecl)) {
6772 if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
6773 Function: FD, /*Complain=*/true, Loc: Fn->getBeginLoc()))
6774 return ExprError();
6775
6776 checkDirectCallValidity(S&: *this, Fn, Callee: 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(i: 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.
6802 getASTContext().getTargetAddressSpace(AS: ArgAS) == getASTContext().getTargetAddressSpace(AS: ParamAS));
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, T: ArgExprs[Idx]->getType(), Kind: CK_NoOp, Operand: ArgExprs[Idx],
6810 BasePath: nullptr, Cat: VK_PRValue, FPO: 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(T: ArgPtTy.getUnqualifiedType(), Qs: ArgPtQuals);
6818 auto NewArgTy =
6819 Context.getQualifiedType(T: Context.getPointerType(T: NewArgPtTy),
6820 Qs: ArgTy.getQualifiers());
6821
6822 // Finally perform an implicit address space cast
6823 ArgExprs[Idx] = ImpCastExprToType(E: ArgExprs[Idx], Type: NewArgTy,
6824 CK: CK_AddressSpaceConversion)
6825 .get();
6826 }
6827 }
6828 }
6829
6830 if (Context.isDependenceAllowed() &&
6831 (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(Exprs: ArgExprs))) {
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(Ctx: Context, Fn, Args: ArgExprs, Ty: Context.DependentTy,
6838 VK: VK_PRValue, RParenLoc, FPFeatures: CurFPFeatureOverrides());
6839 }
6840 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Arg: ArgExprs, RParenLoc,
6841 Config: ExecConfig, IsExecConfig);
6842}
6843
6844/// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
6845// with the specified CallArgs
6846Expr *Sema::BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
6847 MultiExprArg CallArgs) {
6848 StringRef Name = Context.BuiltinInfo.getName(ID: Id);
6849 LookupResult R(*this, &Context.Idents.get(Name), Loc,
6850 Sema::LookupOrdinaryName);
6851 LookupName(R, S: 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
6860 ExprResult Call =
6861 BuildCallExpr(/*Scope=*/nullptr, Fn: DeclRef.get(), LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: 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///
6871ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
6872 SourceLocation BuiltinLoc,
6873 SourceLocation RParenLoc) {
6874 QualType DstTy = GetTypeFromParser(Ty: ParsedDestTy);
6875 return BuildAsTypeExpr(E, DestTy: DstTy, BuiltinLoc, RParenLoc);
6876}
6877
6878/// Create a new AsTypeExpr node (bitcast) from the arguments.
6879ExprResult Sema::BuildAsTypeExpr(Expr *E, QualType DestTy,
6880 SourceLocation BuiltinLoc,
6881 SourceLocation RParenLoc) {
6882 ExprValueKind VK = VK_PRValue;
6883 ExprObjectKind OK = OK_Ordinary;
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///
6898ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
6899 SourceLocation BuiltinLoc,
6900 SourceLocation RParenLoc) {
6901 TypeSourceInfo *TInfo;
6902 GetTypeFromParser(Ty: ParsedDestTy, TInfo: &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
6912ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
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>(Val: 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(Feature: "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(Feature: "sse") || TI.hasFeature(Feature: "x87") || TI.hasFeature(Feature: "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.
6960 ExprResult Result;
6961 QualType ResultTy;
6962 if (BuiltinID &&
6963 Fn->getType()->isSpecificBuiltinType(K: 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(E: Fn, Type: FnPtrTy, CK: CK_BuiltinFnToFnPtr).get();
6970 ResultTy = FDecl->getCallResultType();
6971 } else {
6972 Result = CallExprUnaryConversions(E: Fn);
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(ID: 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(S&: *this, fn: 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>(Val: 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(Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config),
7021 Args, Ty: ResultTy, VK: VK_PRValue, RP: RParenLoc,
7022 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams);
7023 } else {
7024 TheCall =
7025 CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc,
7026 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL);
7027 }
7028
7029 if (!Context.isDependenceAllowed()) {
7030 // Forget about the nulled arguments since typo correction
7031 // do not handle them well.
7032 TheCall->shrinkNumArgs(NewNumArgs: 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.
7037 ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
7038 if (!Result.isUsable()) return ExprError();
7039 CallExpr *TheOldCall = TheCall;
7040 TheCall = dyn_cast<CallExpr>(Val: 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)
7051 TheCall = CUDAKernelCallExpr::Create(
7052 Ctx: Context, Fn, Config: cast<CallExpr>(Val: Config), Args, Ty: ResultTy, VK: VK_PRValue,
7053 RP: RParenLoc, FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams);
7054 else
7055 TheCall =
7056 CallExpr::Create(Ctx: Context, Fn, Args, Ty: ResultTy, VK: VK_PRValue, RParenLoc,
7057 FPFeatures: CurFPFeatureOverrides(), MinNumArgs: NumParams, UsesADL);
7058 }
7059 // We can now handle the nulled arguments for the default arguments.
7060 TheCall->setNumArgsUnsafe(std::max<unsigned>(a: Args.size(), b: NumParams));
7061 }
7062
7063 // Bail out early if calling a builtin with custom type checking.
7064 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(ID: 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>() &&
7077 !FuncT->getReturnType()->isInstantiationDependentType())
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(ReturnType: FuncT->getReturnType(), Loc: Fn->getBeginLoc(), CE: TheCall,
7090 FD: FDecl))
7091 return ExprError();
7092
7093 // We know the result type of the call, set it.
7094 TheCall->setType(FuncT->getCallResultType(Context));
7095 TheCall->setValueKind(Expr::getValueKindForType(T: FuncT->getReturnType()));
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(Call: 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(Definition&: 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()) {
7153 InitializedEntity Entity = InitializedEntity::InitializeParameter(
7154 Context, Type: Proto->getParamType(i), Consumed: Proto->isParamConsumed(I: i));
7155 ExprResult ArgE =
7156 PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: Arg);
7157 if (ArgE.isInvalid())
7158 return true;
7159
7160 Arg = ArgE.getAs<Expr>();
7161
7162 } else {
7163 ExprResult ArgE = DefaultArgumentPromotion(E: Arg);
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(Arg: i, ArgExpr: 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(D: NDecl, Loc: 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>(Val: 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(FD: 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(E: MaybeBindToTemporary(TheCall), Decl: FDecl);
7220}
7221
7222ExprResult
7223Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
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: &TInfo);
7230 if (!TInfo)
7231 TInfo = Context.getTrivialTypeSourceInfo(T: literalType);
7232
7233 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, LiteralExpr: InitExpr);
7234}
7235
7236ExprResult
7237Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
7238 SourceLocation RParenLoc, Expr *LiteralExpr) {
7239 QualType literalType = TInfo->getType();
7240
7241 if (literalType->isArrayType()) {
7242 if (RequireCompleteSizedType(
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>(Val: 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
7273 = InitializedEntity::InitializeCompoundLiteralInit(TSI: TInfo);
7274 InitializationKind Kind
7275 = InitializationKind::CreateCStyleCast(StartLoc: LParenLoc,
7276 TypeRange: SourceRange(LParenLoc, RParenLoc),
7277 /*InitList=*/true);
7278 InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
7279 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: LiteralExpr,
7280 ResultType: &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>(Val: LiteralExpr))
7312 for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
7313 Expr *Init = ILE->getInit(Init: i);
7314 ILE->setInit(i, ConstantExpr::Create(Context, E: 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(Init: 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.
7341 if (E->getType().hasNonTrivialToPrimitiveDestructCUnion())
7342 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
7343 UseContext: NTCUC_CompoundLiteral, NonTrivialKind: NTCUK_Destruct);
7344
7345 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7346 if (literalType.isDestructedType()) {
7347 Cleanup.setExprNeedsCleanups(true);
7348 ExprCleanupObjects.push_back(Elt: E);
7349 getCurFunction()->setHasBranchProtectedScope();
7350 }
7351 }
7352
7353 if (E->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7354 E->getType().hasNonTrivialToPrimitiveCopyCUnion())
7355 checkNonTrivialCUnionInInitializer(Init: E->getInitializer(),
7356 Loc: E->getInitializer()->getExprLoc());
7357
7358 return MaybeBindToTemporary(E);
7359}
7360
7361ExprResult
7362Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
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>(Val: 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>(Val: 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>(Val: InitArgList[0])) {
7404 DiagnosedMixedDesignator = true;
7405 auto *DIE = cast<DesignatedInitExpr>(Val: 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
7429ExprResult
7430Sema::BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
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(E: 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.
7456void Sema::maybeExtendBlockObject(ExprResult &E) {
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
7463 E = ImplicitCastExpr::Create(
7464 Context, T: E.get()->getType(), Kind: CK_ARCExtendBlockObject, Operand: E.get(),
7465 /*base path*/ BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
7466 Cleanup.setExprNeedsCleanups(true);
7467}
7468
7469/// Prepare a conversion of the given expression to an ObjC object
7470/// pointer type.
7471CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
7472 QualType type = E.get()->getType();
7473 if (type->isObjCObjectPointerType()) {
7474 return CK_BitCast;
7475 } else if (type->isBlockPointerType()) {
7476 maybeExtendBlockObject(E);
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.
7486CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
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(T1: SrcTy, T2: DestTy))
7493 return CK_NoOp;
7494
7495 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
7496 case Type::STK_MemberPointer:
7497 llvm_unreachable("member pointer type in C");
7498
7499 case Type::STK_CPointer:
7500 case Type::STK_BlockPointer:
7501 case Type::STK_ObjCObjectPointer:
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(T1: SrcTy, T2: DestTy))
7509 return CK_NoOp;
7510 return CK_BitCast;
7511 }
7512 case Type::STK_BlockPointer:
7513 return (SrcKind == Type::STK_BlockPointer
7514 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
7515 case Type::STK_ObjCObjectPointer:
7516 if (SrcKind == Type::STK_ObjCObjectPointer)
7517 return CK_BitCast;
7518 if (SrcKind == Type::STK_CPointer)
7519 return CK_CPointerToObjCPointerCast;
7520 maybeExtendBlockObject(E&: Src);
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:
7527 case Type::STK_FloatingComplex:
7528 case Type::STK_IntegralComplex:
7529 case Type::STK_MemberPointer:
7530 case Type::STK_FixedPoint:
7531 llvm_unreachable("illegal cast from pointer");
7532 }
7533 llvm_unreachable("Should have returned before this");
7534
7535 case Type::STK_FixedPoint:
7536 switch (DestTy->getScalarTypeKind()) {
7537 case Type::STK_FixedPoint:
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;
7545 case Type::STK_IntegralComplex:
7546 case Type::STK_FloatingComplex:
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:
7552 case Type::STK_ObjCObjectPointer:
7553 case Type::STK_BlockPointer:
7554 case Type::STK_MemberPointer:
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:
7563 case Type::STK_ObjCObjectPointer:
7564 case Type::STK_BlockPointer:
7565 if (Src.get()->isNullPointerConstant(Ctx&: Context,
7566 NPC: Expr::NPC_ValueDependentIsNull))
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;
7575 case Type::STK_IntegralComplex:
7576 Src = ImpCastExprToType(E: Src.get(),
7577 Type: DestTy->castAs<ComplexType>()->getElementType(),
7578 CK: CK_IntegralCast);
7579 return CK_IntegralRealToComplex;
7580 case Type::STK_FloatingComplex:
7581 Src = ImpCastExprToType(E: Src.get(),
7582 Type: DestTy->castAs<ComplexType>()->getElementType(),
7583 CK: CK_IntegralToFloating);
7584 return CK_FloatingRealToComplex;
7585 case Type::STK_MemberPointer:
7586 llvm_unreachable("member pointer type in C");
7587 case Type::STK_FixedPoint:
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;
7600 case Type::STK_FloatingComplex:
7601 Src = ImpCastExprToType(E: Src.get(),
7602 Type: DestTy->castAs<ComplexType>()->getElementType(),
7603 CK: CK_FloatingCast);
7604 return CK_FloatingRealToComplex;
7605 case Type::STK_IntegralComplex:
7606 Src = ImpCastExprToType(E: Src.get(),
7607 Type: DestTy->castAs<ComplexType>()->getElementType(),
7608 CK: CK_FloatingToIntegral);
7609 return CK_IntegralRealToComplex;
7610 case Type::STK_CPointer:
7611 case Type::STK_ObjCObjectPointer:
7612 case Type::STK_BlockPointer:
7613 llvm_unreachable("valid float->pointer cast?");
7614 case Type::STK_MemberPointer:
7615 llvm_unreachable("member pointer type in C");
7616 case Type::STK_FixedPoint:
7617 return CK_FloatingToFixedPoint;
7618 }
7619 llvm_unreachable("Should have returned before this");
7620
7621 case Type::STK_FloatingComplex:
7622 switch (DestTy->getScalarTypeKind()) {
7623 case Type::STK_FloatingComplex:
7624 return CK_FloatingComplexCast;
7625 case Type::STK_IntegralComplex:
7626 return CK_FloatingComplexToIntegralComplex;
7627 case Type::STK_Floating: {
7628 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7629 if (Context.hasSameType(T1: ET, T2: DestTy))
7630 return CK_FloatingComplexToReal;
7631 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_FloatingComplexToReal);
7632 return CK_FloatingCast;
7633 }
7634 case Type::STK_Bool:
7635 return CK_FloatingComplexToBoolean;
7636 case Type::STK_Integral:
7637 Src = ImpCastExprToType(E: Src.get(),
7638 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7639 CK: CK_FloatingComplexToReal);
7640 return CK_FloatingToIntegral;
7641 case Type::STK_CPointer:
7642 case Type::STK_ObjCObjectPointer:
7643 case Type::STK_BlockPointer:
7644 llvm_unreachable("valid complex float->pointer cast?");
7645 case Type::STK_MemberPointer:
7646 llvm_unreachable("member pointer type in C");
7647 case Type::STK_FixedPoint:
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
7655 case Type::STK_IntegralComplex:
7656 switch (DestTy->getScalarTypeKind()) {
7657 case Type::STK_FloatingComplex:
7658 return CK_IntegralComplexToFloatingComplex;
7659 case Type::STK_IntegralComplex:
7660 return CK_IntegralComplexCast;
7661 case Type::STK_Integral: {
7662 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
7663 if (Context.hasSameType(T1: ET, T2: DestTy))
7664 return CK_IntegralComplexToReal;
7665 Src = ImpCastExprToType(E: Src.get(), Type: ET, CK: CK_IntegralComplexToReal);
7666 return CK_IntegralCast;
7667 }
7668 case Type::STK_Bool:
7669 return CK_IntegralComplexToBoolean;
7670 case Type::STK_Floating:
7671 Src = ImpCastExprToType(E: Src.get(),
7672 Type: SrcTy->castAs<ComplexType>()->getElementType(),
7673 CK: CK_IntegralComplexToReal);
7674 return CK_IntegralToFloating;
7675 case Type::STK_CPointer:
7676 case Type::STK_ObjCObjectPointer:
7677 case Type::STK_BlockPointer:
7678 llvm_unreachable("valid complex int->pointer cast?");
7679 case Type::STK_MemberPointer:
7680 llvm_unreachable("member pointer type in C");
7681 case Type::STK_FixedPoint:
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.
7718bool Sema::isValidSveBitcast(QualType srcTy, QualType destTy) {
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.
7739bool Sema::isValidRVVBitcast(QualType srcTy, QualType destTy) {
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?
7756bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy) {
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
7767bool Sema::areVectorTypesSameSize(QualType SrcTy, QualType DestTy) {
7768 assert(DestTy->isVectorType() || SrcTy->isVectorType());
7769
7770 uint64_t SrcLen, DestLen;
7771 QualType SrcEltTy, DestEltTy;
7772 if (!breakDownVectorType(type: SrcTy, len&: SrcLen, eltType&: SrcEltTy))
7773 return false;
7774 if (!breakDownVectorType(type: DestTy, len&: DestLen, eltType&: 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(T: SrcEltTy);
7781 uint64_t DestEltSize = Context.getTypeSize(T: 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.
7787bool Sema::anyAltivecTypes(QualType SrcTy, QualType DestTy) {
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() ==
7793 VectorKind::AltiVecVector) ||
7794 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7795 VectorKind::AltiVecBool) ||
7796 (SrcTy->castAs<VectorType>()->getVectorKind() ==
7797 VectorKind::AltiVecPixel));
7798
7799 bool IsDestTyAltivec = DestTy->isVectorType() &&
7800 ((DestTy->castAs<VectorType>()->getVectorKind() ==
7801 VectorKind::AltiVecVector) ||
7802 (DestTy->castAs<VectorType>()->getVectorKind() ==
7803 VectorKind::AltiVecBool) ||
7804 (DestTy->castAs<VectorType>()->getVectorKind() ==
7805 VectorKind::AltiVecPixel));
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.
7817bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
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: srcTy, DestTy: destTy);
7829}
7830
7831/// Is this a legal conversion between two types, one of which is
7832/// known to be a vector type?
7833bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
7834 assert(destTy->isVectorType() || srcTy->isVectorType());
7835
7836 switch (Context.getLangOpts().getLaxVectorConversions()) {
7837 case LangOptions::LaxVectorConversionKind::None:
7838 return false;
7839
7840 case LangOptions::LaxVectorConversionKind::Integer:
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
7854 case LangOptions::LaxVectorConversionKind::All:
7855 break;
7856 }
7857
7858 return areLaxCompatibleVectorTypes(srcTy, destTy);
7859}
7860
7861bool Sema::CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
7862 CastKind &Kind) {
7863 if (SrcTy->isMatrixType() && DestTy->isMatrixType()) {
7864 if (!areMatrixTypesOfTheSameDimension(srcTy: SrcTy, destTy: 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
7882bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
7883 CastKind &Kind) {
7884 assert(VectorTy->isVectorType() && "Not a vector type!");
7885
7886 if (Ty->isVectorType() || Ty->isIntegralType(Ctx: 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
7902ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
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(E: SplattedExpr, Type: Context.IntTy,
7919 CK: 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(Src&: CastExprRes, DestTy: DestElemTy);
7928 if (CastExprRes.isInvalid())
7929 return ExprError();
7930 SplattedExpr = CastExprRes.get();
7931 }
7932 return ImpCastExprToType(E: SplattedExpr, Type: DestElemTy, CK);
7933}
7934
7935ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
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: SrcTy, destTy: DestTy) ||
7947 (getLangOpts().OpenCL &&
7948 !Context.hasSameUnqualifiedType(T1: DestTy, T2: 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(VectorTy: DestTy, SplattedExpr: CastExpr);
7967}
7968
7969ExprResult
7970Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
7971 Declarator &D, ParsedType &Ty,
7972 SourceLocation RParenLoc, Expr *CastExpr) {
7973 assert(!D.isInvalidType() && (CastExpr != nullptr) &&
7974 "ActOnCastExpr(): missing type or expr");
7975
7976 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, FromTy: CastExpr->getType());
7977 if (D.isInvalidType())
7978 return ExprError();
7979
7980 if (getLangOpts().CPlusPlus) {
7981 // Check that there are no default arguments (C++ only).
7982 CheckExtraCXXDefaultArguments(D);
7983 } else {
7984 // Make sure any TypoExprs have been dealt with.
7985 ExprResult Res = CorrectDelayedTyposInExpr(E: CastExpr);
7986 if (!Res.isUsable())
7987 return ExprError();
7988 CastExpr = Res.get();
7989 }
7990
7991 checkUnusedDeclAttributes(D);
7992
7993 QualType castType = castTInfo->getType();
7994 Ty = CreateParsedType(T: castType, TInfo: 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>(Val: CastExpr);
8001 ParenListExpr *PLE = dyn_cast<ParenListExpr>(Val: 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(Init: 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, E: CastExpr, TInfo: 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>(Val: CastExpr)) {
8026 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: 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
8034 CheckTollFreeBridgeCast(castType, castExpr: CastExpr);
8035
8036 CheckObjCBridgeRelatedCast(castType, castExpr: CastExpr);
8037
8038 DiscardMisalignedMemberAddress(T: castType.getTypePtr(), E: CastExpr);
8039
8040 return BuildCStyleCastExpr(LParenLoc, Ty: castTInfo, RParenLoc, Op: CastExpr);
8041}
8042
8043ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
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>(Val: 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>(Val: E)->getLParen();
8060 LiteralRParenLoc = cast<ParenExpr>(Val: E)->getRParen();
8061 subExpr = cast<ParenExpr>(Val: 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
8077 if (CheckAltivecInitFromScalar(R: E->getSourceRange(), VecTy: Ty,
8078 SrcTy: VTy->getElementType()))
8079 return ExprError();
8080 if (ShouldSplatAltivecScalarInCast(VecTy: VTy)) {
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(E: exprs[0]);
8087 if (Literal.isInvalid())
8088 return ExprError();
8089 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8090 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8091 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: 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(in_start: exprs, in_end: 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.
8104 if (getLangOpts().OpenCL && VTy->getVectorKind() == VectorKind::Generic &&
8105 numExprs == 1) {
8106 QualType ElemTy = VTy->getElementType();
8107 ExprResult Literal = DefaultLvalueConversion(E: exprs[0]);
8108 if (Literal.isInvalid())
8109 return ExprError();
8110 Literal = ImpCastExprToType(E: Literal.get(), Type: ElemTy,
8111 CK: PrepareScalarCast(Src&: Literal, DestTy: ElemTy));
8112 return BuildCStyleCastExpr(LParenLoc, Ty: TInfo, RParenLoc, Op: Literal.get());
8113 }
8114
8115 initExprs.append(in_start: exprs, in_end: 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.
8127ExprResult
8128Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
8129 ParenListExpr *E = dyn_cast<ParenListExpr>(Val: OrigExpr);
8130 if (!E)
8131 return OrigExpr;
8132
8133 ExprResult Result(E->getExpr(Init: 0));
8134
8135 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
8136 Result = ActOnBinOp(S, TokLoc: E->getExprLoc(), Kind: tok::comma, LHSExpr: Result.get(),
8137 RHSExpr: E->getExpr(Init: i));
8138
8139 if (Result.isInvalid()) return ExprError();
8140
8141 return ActOnParenExpr(L: E->getLParenLoc(), R: E->getRParenLoc(), E: Result.get());
8142}
8143
8144ExprResult Sema::ActOnParenListExpr(SourceLocation L,
8145 SourceLocation R,
8146 MultiExprArg Val) {
8147 return ParenListExpr::Create(Ctx: Context, LParenLoc: L, Exprs: Val, RParenLoc: 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;
8157 Expr::NullPointerConstantKind NullKind =
8158 NullExpr->isNullPointerConstant(Ctx&: Context,
8159 NPC: Expr::NPC_ValueDependentIsNotNull);
8160
8161 if (NullKind == Expr::NPCK_NotNull) {
8162 NullExpr = RHSExpr;
8163 NonPointerExpr = LHSExpr;
8164 NullKind =
8165 NullExpr->isNullPointerConstant(Ctx&: Context,
8166 NPC: Expr::NPC_ValueDependentIsNotNull);
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, name: "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.
8213static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
8214 QualType PointerTy) {
8215 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
8216 !NullExpr.get()->isNullPointerConstant(Ctx&: S.Context,
8217 NPC: Expr::NPC_ValueDependentIsNull))
8218 return true;
8219
8220 NullExpr = S.ImpCastExprToType(E: NullExpr.get(), Type: PointerTy, CK: CK_NullToPointer);
8221 return false;
8222}
8223
8224/// Checks compatibility between two pointers and return the resulting
8225/// type.
8226static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
8227 ExprResult &RHS,
8228 SourceLocation Loc) {
8229 QualType LHSTy = LHS.get()->getType();
8230 QualType RHSTy = RHS.get()->getType();
8231
8232 if (S.Context.hasSameType(T1: LHSTy, T2: RHSTy)) {
8233 // Two identical pointers types are always compatible.
8234 return S.Context.getCommonSugaredType(X: LHSTy, Y: 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(other: rhQual))
8269 ResultAddrSpace = LAddrSpace;
8270 else if (rhQual.isAddressSpaceSupersetOf(other: 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(T: lhptee.getUnqualifiedType(), Qs: lhQual);
8302 rhptee = S.Context.getQualifiedType(T: rhptee.getUnqualifiedType(), Qs: 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(T: S.Context.VoidTy, AddressSpace: ResultAddrSpace));
8315 LHS = S.ImpCastExprToType(E: LHS.get(), Type: incompatTy, CK: LHSCastKind);
8316 RHS = S.ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: 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(T: CompositeTy.getUnqualifiedType(), Qs: CompositeQuals)
8342 .withCVRQualifiers(CVR: MergedCVRQual);
8343 }
8344 return CompositeTy.withCVRQualifiers(CVR: MergedCVRQual);
8345 }();
8346 if (IsBlockPointer)
8347 ResultTy = S.Context.getBlockPointerType(T: ResultTy);
8348 else
8349 ResultTy = S.Context.getPointerType(T: ResultTy);
8350
8351 LHS = S.ImpCastExprToType(E: LHS.get(), Type: ResultTy, CK: LHSCastKind);
8352 RHS = S.ImpCastExprToType(E: RHS.get(), Type: ResultTy, CK: RHSCastKind);
8353 return ResultTy;
8354}
8355
8356/// Return the resulting type when the operands are both block pointers.
8357static QualType checkConditionalBlockPointerCompatibility(Sema &S,
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()) {
8366 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
8367 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_BitCast);
8368 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: 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
8383checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
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(T: lhptee, Qs: rhptee.getQualifiers());
8399 QualType destType = S.Context.getPointerType(T: destPointee);
8400 // Add qualifiers if necessary.
8401 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp);
8402 // Promote to void*.
8403 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_BitCast);
8404 return destType;
8405 }
8406 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
8407 QualType destPointee
8408 = S.Context.getQualifiedType(T: rhptee, Qs: lhptee.getQualifiers());
8409 QualType destType = S.Context.getPointerType(T: destPointee);
8410 // Add qualifiers if necessary.
8411 RHS = S.ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp);
8412 // Promote to void*.
8413 LHS = S.ImpCastExprToType(E: LHS.get(), Type: destType, CK: 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.
8422static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
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(E: Int.get(), Type: PointerExpr->getType(),
8436 CK: 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.
8452static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
8453 ExprResult &RHS,
8454 SourceLocation QuestionLoc) {
8455 LHS = S.DefaultFunctionArrayLvalueConversion(E: LHS.get());
8456 if (LHS.isInvalid())
8457 return QualType();
8458 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
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 =
8465 S.Context.getCanonicalType(T: LHS.get()->getType()).getUnqualifiedType();
8466 QualType RHSType =
8467 S.Context.getCanonicalType(T: RHS.get()->getType()).getUnqualifiedType();
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
8507OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
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(VectorType: ResTy, NumElts: NumElements);
8518
8519 // Ensure that all types have the same number of bits
8520 if (S.Context.getTypeSize(T: CV->getElementType())
8521 != S.Context.getTypeSize(T: 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(E: LHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8535 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VectorTy, CK: CK_VectorSplat);
8536
8537 return VectorTy;
8538}
8539
8540/// Return false if this is a valid OpenCL condition vector
8541static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
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(T: CVE) != S.Context.getTypeSize(T: 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
8589OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
8590 ExprResult &LHS, ExprResult &RHS,
8591 SourceLocation QuestionLoc) {
8592 Cond = S.DefaultFunctionArrayLvalueConversion(E: Cond.get());
8593 if (Cond.isInvalid())
8594 return QualType();
8595 QualType CondTy = Cond.get()->getType();
8596
8597 if (checkOpenCLConditionVector(S, Cond: 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, Loc: QuestionLoc,
8608 /*isCompAssign*/ IsCompAssign: false,
8609 /*AllowBothBool*/ true,
8610 /*AllowBoolConversions*/ AllowBoolConversion: false,
8611 /*AllowBooleanOperation*/ AllowBoolOperation: 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>(Val: 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
8641QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
8642 ExprResult &RHS, ExprValueKind &VK,
8643 ExprObjectKind &OK,
8644 SourceLocation QuestionLoc) {
8645
8646 ExprResult LHSResult = CheckPlaceholderExpr(E: LHS.get());
8647 if (!LHSResult.isUsable()) return QualType();
8648 LHS = LHSResult;
8649
8650 ExprResult RHSResult = CheckPlaceholderExpr(E: 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&: Cond, lhs&: LHS, rhs&: RHS, VK, OK, questionLoc: QuestionLoc);
8657
8658 VK = VK_PRValue;
8659 OK = OK_Ordinary;
8660
8661 if (Context.isDependenceAllowed() &&
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(S&: *this, Cond, LHS, RHS, QuestionLoc);
8676
8677 // First, check the condition.
8678 Cond = UsualUnaryConversions(E: Cond.get());
8679 if (Cond.isInvalid())
8680 return QualType();
8681 if (checkCondition(S&: *this, Cond: 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, Loc: QuestionLoc, /*isCompAssign*/ IsCompAssign: false,
8688 /*AllowBothBool*/ true,
8689 /*AllowBoolConversions*/ AllowBoolConversion: false,
8690 /*AllowBooleanOperation*/ AllowBoolOperation: false,
8691 /*ReportInvalid*/ true);
8692
8693 QualType ResTy =
8694 UsualArithmeticConversions(LHS, RHS, Loc: QuestionLoc, ACK: 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(S: *this, LHSType: LHSTy, RHSType: 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(S&: *this, E: LHS.get()) | (int)checkBlockType(S&: *this, E: 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(E: LHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: LHS, DestTy: ResTy));
8737 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: PrepareScalarCast(Src&: RHS, DestTy: 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.
8749 return Context.getCommonSugaredType(X: LHSTy.getUnqualifiedType(),
8750 Y: 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(X: LHSTy, Y: 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(E: LHS.get(), Type: ResTy, CK: CK_ToVoid);
8770 RHS = ImpCastExprToType(E: RHS.get(), Type: ResTy, CK: 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(T1: LHSTy, T2: 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(S&: *this, NullExpr&: RHS, PointerTy: LHSTy)) return LHSTy;
8783 if (!checkConditionalNullPointer(S&: *this, NullExpr&: LHS, PointerTy: 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(S&: *this, LHS, RHS,
8797 Loc: QuestionLoc);
8798
8799 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8800 if (LHSTy->isPointerType() && RHSTy->isPointerType())
8801 return checkConditionalObjectPointersCompatibility(S&: *this, LHS, RHS,
8802 Loc: QuestionLoc);
8803
8804 // GCC compatibility: soften pointer/integer mismatch. Note that
8805 // null pointers have been filtered out by this point.
8806 if (checkPointerIntegerMismatch(S&: *this, Int&: LHS, PointerExpr: RHS.get(), Loc: QuestionLoc,
8807 /*IsIntFirstExpr=*/true))
8808 return RHSTy;
8809 if (checkPointerIntegerMismatch(S&: *this, Int&: RHS, PointerExpr: LHS.get(), Loc: 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(LHSExpr: LHS.get(), RHSExpr: 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(T1: LHSTy, T2: RHSTy))
8822 return Context.getCommonSugaredType(X: LHSTy, Y: 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.
8833QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
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() &&
8842 (Context.hasSameType(T1: RHSTy, T2: Context.getObjCClassRedefinitionType()))) {
8843 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSTy, CK: CK_CPointerToObjCPointerCast);
8844 return LHSTy;
8845 }
8846 if (RHSTy->isObjCClassType() &&
8847 (Context.hasSameType(T1: LHSTy, T2: Context.getObjCClassRedefinitionType()))) {
8848 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSTy, CK: CK_CPointerToObjCPointerCast);
8849 return RHSTy;
8850 }
8851 // And the same for struct objc_object* / id
8852 if (LHSTy->isObjCIdType() &&
8853 (Context.hasSameType(T1: RHSTy, T2: Context.getObjCIdRedefinitionType()))) {
8854 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSTy, CK: CK_CPointerToObjCPointerCast);
8855 return LHSTy;
8856 }
8857 if (RHSTy->isObjCIdType() &&
8858 (Context.hasSameType(T1: LHSTy, T2: Context.getObjCIdRedefinitionType()))) {
8859 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSTy, CK: CK_CPointerToObjCPointerCast);
8860 return RHSTy;
8861 }
8862 // And the same for struct objc_selector* / SEL
8863 if (Context.isObjCSelType(T: LHSTy) &&
8864 (Context.hasSameType(T1: RHSTy, T2: Context.getObjCSelRedefinitionType()))) {
8865 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSTy, CK: CK_BitCast);
8866 return LHSTy;
8867 }
8868 if (Context.isObjCSelType(T: RHSTy) &&
8869 (Context.hasSameType(T1: LHSTy, T2: Context.getObjCSelRedefinitionType()))) {
8870 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSTy, CK: 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(T: LHSTy) == Context.getCanonicalType(T: 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(LHSOPT: RHSOPT, RHSOPT: LHSOPT)) {
8903 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
8904 } else if ((LHSOPT->isObjCQualifiedIdType() ||
8905 RHSOPT->isObjCQualifiedIdType()) &&
8906 Context.ObjCQualifiedIdTypesAreCompatible(LHS: LHSOPT, RHS: RHSOPT,
8907 ForCompare: 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(E: LHS.get(), Type: incompatTy, CK: CK_BitCast);
8921 RHS = ImpCastExprToType(E: RHS.get(), Type: incompatTy, CK: CK_BitCast);
8922 return incompatTy;
8923 }
8924 // The object pointer types are compatible.
8925 LHS = ImpCastExprToType(E: LHS.get(), Type: compositeType, CK: CK_BitCast);
8926 RHS = ImpCastExprToType(E: RHS.get(), Type: compositeType, CK: 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(T: lhptee, Qs: rhptee.getQualifiers());
8943 QualType destType = Context.getPointerType(T: destPointee);
8944 // Add qualifiers if necessary.
8945 LHS = ImpCastExprToType(E: LHS.get(), Type: destType, CK: CK_NoOp);
8946 // Promote to void*.
8947 RHS = ImpCastExprToType(E: RHS.get(), Type: destType, CK: 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(T: rhptee, Qs: lhptee.getQualifiers());
8963 QualType destType = Context.getPointerType(T: destPointee);
8964 // Add qualifiers if necessary.
8965 RHS = ImpCastExprToType(E: RHS.get(), Type: destType, CK: CK_NoOp);
8966 // Promote to void*.
8967 LHS = ImpCastExprToType(E: LHS.get(), Type: destType, CK: 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.
8975static void SuggestParentheses(Sema &Self, SourceLocation Loc,
8976 const PartialDiagnostic &Note,
8977 SourceRange ParenRange) {
8978 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: ParenRange.getEnd());
8979 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
8980 EndLoc.isValid()) {
8981 Self.Diag(Loc, Note)
8982 << FixItHint::CreateInsertion(InsertionLoc: ParenRange.getBegin(), Code: "(")
8983 << FixItHint::CreateInsertion(InsertionLoc: EndLoc, Code: ")");
8984 } else {
8985 // We can't display the parentheses, so just show the bare note.
8986 Self.Diag(Loc, Note) << ParenRange;
8987 }
8988}
8989
8990static bool IsArithmeticOp(BinaryOperatorKind Opc) {
8991 return BinaryOperator::isAdditiveOp(Opc) ||
8992 BinaryOperator::isMultiplicativeOp(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();
9009 E = E->IgnoreConversionOperatorSingleStep();
9010 E = E->IgnoreImpCasts();
9011 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: E)) {
9012 E = MTE->getSubExpr();
9013 E = E->IgnoreImpCasts();
9014 }
9015
9016 // Built-in binary operator.
9017 if (const auto *OP = dyn_cast<BinaryOperator>(Val: E);
9018 OP && IsArithmeticOp(Opc: 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>(Val: 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
9036 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
9037 if (IsArithmeticOp(Opc: 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>(Val: E))
9056 return OP->isComparisonOp() || OP->isLogicalOp();
9057 if (const auto *OP = dyn_cast<UnaryOperator>(Val: 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".
9071static void DiagnoseConditionalPrecedence(Sema &Self, SourceLocation OpLoc,
9072 Expr *Condition, const Expr *LHSExpr,
9073 const Expr *RHSExpr) {
9074 BinaryOperatorKind CondOpcode;
9075 const Expr *CondRHS;
9076
9077 if (!IsArithmeticBinaryExpr(E: Condition, Opcode: &CondOpcode, RHSExprs: &CondRHS))
9078 return;
9079 if (!ExprLooksBoolean(E: 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(Op: CondOpcode);
9092
9093 SuggestParentheses(
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.
9105static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
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.
9115 if (*Kind == NullabilityKind::NullableResult)
9116 return NullabilityKind::Nullable;
9117 return *Kind;
9118 }
9119 return NullabilityKind::Unspecified;
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(Context: Ctx);
9151
9152 // Create a new AttributedType with the new nullability kind.
9153 auto NewAttr = AttributedType::getNullabilityAttrKind(kind: MergedKind);
9154 return Ctx.getAttributedType(attrKind: NewAttr, modifiedType: ResTy, equivalentType: 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.
9159ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
9160 SourceLocation ColonLoc,
9161 Expr *CondExpr, Expr *LHSExpr,
9162 Expr *RHSExpr) {
9163 if (!Context.isDependenceAllowed()) {
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(E: CondExpr);
9168 ExprResult LHSResult = CorrectDelayedTyposInExpr(E: LHSExpr);
9169 ExprResult RHSResult = CorrectDelayedTyposInExpr(E: 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(E: 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(T1: commonExpr->getType(), T2: RHSExpr->getType()))) {
9210 ExprResult commonRes = UsualUnaryConversions(E: 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(E: 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();
9235 ExprValueKind VK = VK_PRValue;
9236 ExprObjectKind OK = OK_Ordinary;
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(Self&: *this, OpLoc: QuestionLoc, Condition: Cond.get(), LHSExpr: LHS.get(),
9245 RHSExpr: RHS.get());
9246
9247 CheckBoolLikeConversion(E: Cond.get(), CC: QuestionLoc);
9248
9249 result = computeConditionalNullability(ResTy: result, IsBin: commonExpr, LHSTy, RHSTy,
9250 Ctx&: Context);
9251
9252 if (!commonExpr)
9253 return new (Context)
9254 ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
9255 RHS.get(), result, VK, OK);
9256
9257 return new (Context) BinaryConditionalOperator(
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.
9263bool Sema::IsInvalidSMECallConversion(QualType FromType, QualType ToType) {
9264 unsigned FromAttributes = 0, ToAttributes = 0;
9265 if (const auto *FromFn =
9266 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: FromType)))
9267 FromAttributes =
9268 FromFn->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask;
9269 if (const auto *ToFn =
9270 dyn_cast<FunctionProtoType>(Val: Context.getCanonicalType(T: 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.
9280static bool IsInvalidCmseNSCallConversion(Sema &S, QualType FromType,
9281 QualType ToType) {
9282 if (const auto *ToFn =
9283 dyn_cast<FunctionType>(Val: S.Context.getCanonicalType(T: ToType))) {
9284 if (const auto *FromFn =
9285 dyn_cast<FunctionType>(Val: S.Context.getCanonicalType(T: 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.
9300static Sema::AssignConvertType
9301checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType,
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(args&: lhptee, args&: lhq) =
9310 cast<PointerType>(Val&: LHSType)->getPointeeType().split().asPair();
9311 std::tie(args&: rhptee, args&: rhq) =
9312 cast<PointerType>(Val&: RHSType)->getPointeeType().split().asPair();
9313
9314 Sema::AssignConvertType ConvTy = Sema::Compatible;
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() &&
9322 lhq.compatiblyIncludesObjCLifetime(other: rhq)) {
9323 // Ignore lifetime for further calculation.
9324 lhq.removeObjCLifetime();
9325 rhq.removeObjCLifetime();
9326 }
9327
9328 if (!lhq.compatiblyIncludes(other: rhq)) {
9329 // Treat address-space mismatches as fatal.
9330 if (!lhq.isAddressSpaceSupersetOf(other: rhq))
9331 return Sema::IncompatiblePointerDiscardsQualifiers;
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()
9336 .compatiblyIncludes(
9337 other: rhq.withoutObjCGCAttr().withoutObjCLifetime())
9338 && (lhptee->isVoidType() || rhptee->isVoidType()))
9339 ; // keep old
9340
9341 // Treat lifetime mismatches as fatal.
9342 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
9343 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
9344
9345 // For GCC/MS compatibility, other qualifier mismatches are treated
9346 // as still compatible in C.
9347 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
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());
9359 return Sema::FunctionVoidPointer;
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());
9368 return Sema::FunctionVoidPointer;
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))
9376 return Sema::IncompatibleFunctionPointerStrict;
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(T1: ltrans, T2: 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(T: ltrans);
9389
9390 if (rhptee->isCharType())
9391 rtrans = S.Context.UnsignedCharTy;
9392 else if (rhptee->hasSignedIntegerRepresentation())
9393 rtrans = S.Context.getCorrespondingUnsignedType(T: 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
9402 return Sema::IncompatiblePointerSign;
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>(Val: lhptee) && isa<PointerType>(Val: rhptee)) {
9410 do {
9411 std::tie(args&: lhptee, args&: lhq) =
9412 cast<PointerType>(Val: lhptee)->getPointeeType().split().asPair();
9413 std::tie(args&: rhptee, args&: rhq) =
9414 cast<PointerType>(Val: 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())
9425 return Sema::IncompatibleNestedPointerAddressSpaceMismatch;
9426
9427 } while (isa<PointerType>(Val: lhptee) && isa<PointerType>(Val: rhptee));
9428
9429 if (lhptee == rhptee)
9430 return Sema::IncompatibleNestedPointerQualifiers;
9431 }
9432
9433 // General pointer incompatibility takes priority over qualifiers.
9434 if (RHSType->isFunctionPointerType() && LHSType->isFunctionPointerType())
9435 return Sema::IncompatibleFunctionPointer;
9436 return Sema::IncompatiblePointer;
9437 }
9438 if (!S.getLangOpts().CPlusPlus &&
9439 S.IsFunctionConversion(FromType: ltrans, ToType: rtrans, ResultTy&: ltrans))
9440 return Sema::IncompatibleFunctionPointer;
9441 if (IsInvalidCmseNSCallConversion(S, FromType: ltrans, ToType: rtrans))
9442 return Sema::IncompatibleFunctionPointer;
9443 if (S.IsInvalidSMECallConversion(FromType: rtrans, ToType: ltrans))
9444 return Sema::IncompatibleFunctionPointer;
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.
9452static Sema::AssignConvertType
9453checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
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>(Val&: LHSType)->getPointeeType();
9462 rhptee = cast<BlockPointerType>(Val&: RHSType)->getPointeeType();
9463
9464 // In C++, the types have to match exactly.
9465 if (S.getLangOpts().CPlusPlus)
9466 return Sema::IncompatibleBlockPointer;
9467
9468 Sema::AssignConvertType ConvTy = Sema::Compatible;
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)
9478 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
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) {
9491 if (!S.Context.typesAreBlockPointerCompatible(
9492 S.Context.getQualifiedType(T: LHSType.getUnqualifiedType(), Qs: LQuals),
9493 S.Context.getQualifiedType(T: RHSType.getUnqualifiedType(), Qs: RQuals)))
9494 return Sema::IncompatibleBlockPointer;
9495 } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
9496 return Sema::IncompatibleBlockPointer;
9497
9498 return ConvTy;
9499}
9500
9501/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9502/// for assignment compatibility.
9503static Sema::AssignConvertType
9504checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
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())
9513 return Sema::IncompatiblePointer;
9514 return Sema::Compatible;
9515 }
9516 if (RHSType->isObjCBuiltinType()) {
9517 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
9518 !LHSType->isObjCQualifiedClassType())
9519 return Sema::IncompatiblePointer;
9520 return Sema::Compatible;
9521 }
9522 QualType lhptee = LHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9523 QualType rhptee = RHSType->castAs<ObjCObjectPointerType>()->getPointeeType();
9524
9525 if (!lhptee.isAtLeastAsQualifiedAs(other: rhptee) &&
9526 // make an exception for id<P>
9527 !LHSType->isObjCQualifiedIdType())
9528 return Sema::CompatiblePointerDiscardsQualifiers;
9529
9530 if (S.Context.typesAreCompatible(T1: LHSType, T2: RHSType))
9531 return Sema::Compatible;
9532 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
9533 return Sema::IncompatibleObjCQualifiedId;
9534 return Sema::IncompatiblePointer;
9535}
9536
9537Sema::AssignConvertType
9538Sema::CheckAssignmentConstraints(SourceLocation Loc,
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, RHS&: RHSPtr, Kind&: 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.
9576Sema::AssignConvertType
9577Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
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(T: LHSType).getUnqualifiedType();
9585 RHSType = Context.getCanonicalType(T: 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>(Val&: 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>(Val&: LHSType)) {
9605 Sema::AssignConvertType result =
9606 CheckAssignmentConstraints(LHSType: AtomicTy->getValueType(), RHS, Kind);
9607 if (result != Compatible)
9608 return result;
9609 if (Kind != CK_NoOp && ConvertRHS)
9610 RHS = ImpCastExprToType(E: RHS.get(), Type: AtomicTy->getValueType(), CK: 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(T1: LHSTypeRef->getPointeeType(), T2: 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(VectorTy: LHSType, SplattedExpr: 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(FirstVec: LHSType, SecondVec: 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(srcTy: RHSType, destTy: 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(srcTy: RHSType, destTy: LHSType)) {
9679 if (Context.getTargetInfo().getTriple().isPPC() &&
9680 (VecType->getVectorKind() == VectorKind::AltiVecVector ||
9681 VecType->getVectorKind() == VectorKind::AltiVecBool ||
9682 VecType->getVectorKind() == VectorKind::AltiVecPixel))
9683 Diag(RHS.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all)
9684 << RHSType << LHSType;
9685 ExprResult *VecExpr = &RHS;
9686 *VecExpr = ImpCastExprToType(E: VecExpr->get(), Type: LHSType, CK: 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(FirstType: LHSType, SecondType: RHSType) ||
9696 Context.areLaxCompatibleSveTypes(FirstType: LHSType, SecondType: 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(FirstType: LHSType, SecondType: RHSType) ||
9705 Context.areLaxCompatibleRVVTypes(FirstType: LHSType, SecondType: 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(S: *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(Src&: RHS, DestTy: LHSType);
9730 return Compatible;
9731 }
9732
9733 // Conversions to normal pointers.
9734 if (const PointerType *LHSPointer = dyn_cast<PointerType>(Val&: LHSType)) {
9735 // U* -> T*
9736 if (isa<PointerType>(Val: 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(T1: RHSType, T2: 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>(Val: 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(T1: LHSType,
9767 T2: Context.getObjCClassRedefinitionType())) {
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>(Val: 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(S&: *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>(Val: LHSType)) {
9830 // A* -> B*
9831 if (RHSType->isObjCObjectPointerType()) {
9832 Kind = CK_BitCast;
9833 Sema::AssignConvertType result =
9834 checkObjCPointerTypesForAssignment(S&: *this, LHSType, RHSType);
9835 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
9836 result == Compatible &&
9837 !CheckObjCARCUnavailableWeakConversion(castType: OrigLHSType, ExprType: 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>(Val: 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(T1: RHSType,
9861 T2: Context.getObjCClassRedefinitionType())) {
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() &&
9870 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
9871 if (ConvertRHS)
9872 maybeExtendBlockObject(E&: RHS);
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() &&
9882 RHS.get()->isNullPointerConstant(Ctx&: Context,
9883 NPC: Expr::NPC_ValueDependentIsNull)) {
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>(Val: 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>(Val: 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>(Val: LHSType) && isa<TagType>(Val: RHSType)) {
9925 if (Context.typesAreCompatible(T1: LHSType, T2: 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.
9941static void ConstructTransparentUnion(Sema &S, ASTContext &C,
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();
9947 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
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(T: UnionType);
9955 EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
9956 VK_PRValue, Initializer, false);
9957}
9958
9959Sema::AssignConvertType
9960Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
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
9986 if (RHS.get()->isNullPointerConstant(Context,
9987 Expr::NPC_ValueDependentIsNull)) {
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(S&: *this, C&: Context, EResult&: RHS, UnionType: ArgType, Field: InitField);
10008 return Compatible;
10009}
10010
10011Sema::AssignConvertType
10012Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
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(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10045 Action: AA_Assigning);
10046 } else {
10047 ImplicitConversionSequence ICS =
10048 TryImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10049 /*SuppressUserConversions=*/false,
10050 AllowExplicit: AllowedExplicit::None,
10051 /*InOverloadResolution=*/false,
10052 /*CStyle=*/false,
10053 /*AllowObjCWritebackConversion=*/false);
10054 if (ICS.isFailure())
10055 return Incompatible;
10056 RHS = PerformImplicitConversion(From: RHS.get(), ToType: LHSType.getUnqualifiedType(),
10057 ICS, Action: AA_Assigning);
10058 }
10059 if (RHS.isInvalid())
10060 return Incompatible;
10061 Sema::AssignConvertType result = Compatible;
10062 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10063 !CheckObjCARCUnavailableWeakConversion(castType: LHSType, ExprType: 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;
10076 if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
10077 AddressOfExpr: RHS.get(), TargetType: LHSType, /*Complain=*/false, Found&: DAP))
10078 RHS = FixOverloadedFunctionReference(E: RHS.get(), FoundDecl: DAP, Fn: 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.
10096 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get(), Diagnose);
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()) ||
10111 RHS.get()->isNullPointerConstant(Ctx&: Context,
10112 NPC: Expr::NPC_ValueDependentIsNull))) {
10113 if (Diagnose || ConvertRHS) {
10114 CastKind Kind;
10115 CXXCastPath Path;
10116 CheckPointerConversion(From: RHS.get(), ToType: LHSType, Kind, BasePath&: Path,
10117 /*IgnoreBaseAccess=*/false, Diagnose);
10118 if (ConvertRHS)
10119 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: Kind, VK: VK_PRValue, BasePath: &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(From: RHS.get(), ToType: Context.VoidPtrTy, Kind, BasePath&: Path,
10137 /*IgnoreBaseAccess=*/false, Diagnose);
10138 if (ConvertRHS)
10139 RHS = ImpCastExprToType(E: RHS.get(), Type: Context.VoidPtrTy, CK: Kind, VK: VK_PRValue,
10140 BasePath: &Path);
10141 }
10142 }
10143
10144 // OpenCL queue_t type assignment.
10145 if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
10146 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull)) {
10147 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
10148 return Compatible;
10149 }
10150
10151 CastKind Kind;
10152 Sema::AssignConvertType result =
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) {
10162 QualType Ty = LHSType.getNonLValueExprType(Context);
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() &&
10169 CheckObjCConversion(castRange: SourceRange(), castType: Ty, op&: E,
10170 CCK: CheckedConversionKind::Implicit, Diagnose,
10171 DiagnoseCFAudited) != ACR_okay) {
10172 if (!Diagnose)
10173 return Incompatible;
10174 }
10175 if (getLangOpts().ObjC &&
10176 (CheckObjCBridgeRelatedConversions(Loc: E->getBeginLoc(), DestType: LHSType,
10177 SrcType: E->getType(), SrcExpr&: E, Diagnose) ||
10178 CheckConversionToObjCLiteral(DstType: LHSType, SrcExpr&: 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, Type: Ty, CK: 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>(Val: Op))
10201 Op = MTE->getSubExpr();
10202 if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Val: Op))
10203 Op = BTE->getSubExpr();
10204 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: 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
10217QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
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.
10244QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
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)
10280static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
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(Ctx: S.Context)) {
10290 if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
10291 (scalarTy->isIntegerType() &&
10292 S.Context.getIntegerTypeOrder(LHS: vectorEltTy, RHS: scalarTy) < 0))) {
10293 DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
10294 return true;
10295 }
10296 if (!scalarTy->isIntegralType(Ctx: 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(LHS: vectorEltTy, RHS: 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(Ctx: 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(E: scalar->get(), Type: vectorEltTy, CK: scalarCast);
10320 *scalar = S.ImpCastExprToType(E: scalar->get(), Type: vectorTy, CK: 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(VectorType: ElementType, NumElts: VecTy->getNumElements())
10333 : S.Context.getVectorType(VectorType: ElementType, NumElts: VecTy->getNumElements(),
10334 VecKind: 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>(Val: 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, Type: NewVecTy, CK: Cast);
10344}
10345
10346/// Test if a (constant) integer Int can be casted to another integer type
10347/// IntTy without losing precision.
10348static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
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(Result&: EVResult, Ctx: S.Context);
10357 int Order = S.Context.getIntegerTypeOrder(LHS: OtherIntTy, RHS: 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(T: 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(T: 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.
10386static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
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(Result&: EVResult, Ctx: 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(T: FloatTy));
10404 Float.convertFromAPInt(Input: Result, IsSigned: IntTy->hasSignedIntegerRepresentation(),
10405 RM: llvm::APFloat::rmTowardZero);
10406 llvm::APSInt ConvertBack(S.Context.getIntWidth(T: IntTy),
10407 !IntTy->hasSignedIntegerRepresentation());
10408 bool Ignored = false;
10409 Float.convertToInteger(Result&: ConvertBack, RM: llvm::APFloat::rmNearestTiesToEven,
10410 IsExact: &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(T: IntTy);
10417 unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
10418 S.Context.getFloatTypeSemantics(T: 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.
10430static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *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(Ctx: S.Context) &&
10464 ScalarTy->isIntegralType(Ctx: S.Context) &&
10465 S.Context.getIntegerTypeOrder(LHS: VectorEltTy, RHS: ScalarTy)) {
10466
10467 if (canConvertIntToOtherIntTy(S, Int: Scalar, OtherIntTy: VectorEltTy))
10468 return true;
10469
10470 ScalarCast = CK_IntegralCast;
10471 } else if (VectorEltTy->isIntegralType(Ctx: S.Context) &&
10472 ScalarTy->isRealFloatingType()) {
10473 if (S.Context.getTypeSize(T: VectorEltTy) == S.Context.getTypeSize(T: 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, Ctx: S.Context);
10490 int Order = S.Context.getFloatingTypeOrder(LHS: VectorEltTy, RHS: 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(ToSemantics: S.Context.getFloatTypeSemantics(T: VectorEltTy),
10499 RM: llvm::APFloat::rmNearestTiesToEven, losesInfo: &Truncated);
10500 if (Truncated)
10501 return true;
10502 }
10503
10504 ScalarCast = CK_FloatingCast;
10505 } else if (ScalarTy->isIntegralType(Ctx: S.Context)) {
10506 if (canConvertIntTyToFloatTy(S, Int: Scalar, FloatTy: 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(E: Scalar->get(), Type: VectorEltTy, CK: ScalarCast);
10518 *Scalar = S.ImpCastExprToType(E: Scalar->get(), Type: VectorTy, CK: CK_VectorSplat);
10519 return false;
10520}
10521
10522QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
10523 SourceLocation Loc, bool IsCompAssign,
10524 bool AllowBothBool,
10525 bool AllowBoolConversions,
10526 bool AllowBoolOperation,
10527 bool ReportInvalid) {
10528 if (!IsCompAssign) {
10529 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
10530 if (LHS.isInvalid())
10531 return QualType();
10532 }
10533 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
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(T1: LHSType, T2: RHSType))
10560 return Context.getCommonSugaredType(X: LHSType, Y: RHSType);
10561
10562 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10563 if (LHSVecType && RHSVecType &&
10564 Context.areCompatibleVectorTypes(FirstVec: LHSType, SecondVec: RHSType)) {
10565 if (isa<ExtVectorType>(Val: LHSVecType)) {
10566 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
10567 return LHSType;
10568 }
10569
10570 if (!IsCompAssign)
10571 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: 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(T: LHSVecType->getElementType()) ==
10581 Context.getTypeSize(T: RHSVecType->getElementType()))) {
10582 if (LHSVecType->getVectorKind() == VectorKind::AltiVecVector &&
10583 LHSVecType->getElementType()->isIntegerType() &&
10584 RHSVecType->getVectorKind() == VectorKind::AltiVecBool) {
10585 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: 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(E: LHS.get(), Type: RHSType, CK: 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) {
10604 if (VecType->getVectorKind() == VectorKind::SveFixedLengthData ||
10605 VecType->getVectorKind() == VectorKind::SveFixedLengthPredicate)
10606 return true;
10607 if (VecType->getVectorKind() == VectorKind::RVVFixedLengthData ||
10608 VecType->getVectorKind() == VectorKind::RVVFixedLengthMask) {
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() ==
10637 VectorKind::SveFixedLengthPredicate)
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>(Val: LHSVecType)) {
10673 if (!tryVectorConvertAndSplat(S&: *this, scalar: &RHS, scalarTy: RHSType,
10674 vectorEltTy: LHSVecType->getElementType(), vectorTy: LHSType,
10675 DiagID))
10676 return LHSType;
10677 } else {
10678 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
10679 return LHSType;
10680 }
10681 }
10682 if (!LHSVecType) {
10683 if (isa<ExtVectorType>(Val: RHSVecType)) {
10684 if (!tryVectorConvertAndSplat(S&: *this, scalar: (IsCompAssign ? nullptr : &LHS),
10685 scalarTy: LHSType, vectorEltTy: RHSVecType->getElementType(),
10686 vectorTy: RHSType, DiagID))
10687 return RHSType;
10688 } else {
10689 if (LHS.get()->isLValue() ||
10690 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &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(srcTy: OtherType, destTy: 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(E: OtherExpr->get(), Type: VecType, CK: 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(E: RHSExpr->get(), Type: LHSType, CK: 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>(Val: RHSVecType) &&
10743 LHSVecType && isa<ExtVectorType>(Val: 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>(Val: RHSVecType)) ||
10754 (LHSVecType && !isa<ExtVectorType>(Val: 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
10772QualType Sema::CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
10773 SourceLocation Loc,
10774 bool IsCompAssign,
10775 ArithConvKind OperationKind) {
10776 if (!IsCompAssign) {
10777 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
10778 if (LHS.isInvalid())
10779 return QualType();
10780 }
10781 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
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(T1: LHSType, T2: RHSType))
10801 return LHSType;
10802
10803 if (LHSType->isSveVLSBuiltinType() && !RHSType->isSveVLSBuiltinType()) {
10804 if (!tryGCCVectorConvertAndSplat(S&: *this, Scalar: &RHS, Vector: &LHS))
10805 return LHSType;
10806 }
10807 if (RHSType->isSveVLSBuiltinType() && !LHSType->isSveVLSBuiltinType()) {
10808 if (LHS.get()->isLValue() ||
10809 !tryGCCVectorConvertAndSplat(S&: *this, Scalar: &LHS, Vector: &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(VecTy: LHSBuiltinTy).EC !=
10823 Context.getBuiltinVectorTypeInfo(VecTy: 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.
10850static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
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>(Val: LHS.get()->IgnoreParenImpCasts());
10856 bool RHSNull = isa<GNUNullExpr>(Val: 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
10886static void DiagnoseDivisionSizeofPointerOrArray(Sema &S, Expr *LHS, Expr *RHS,
10887 SourceLocation Loc) {
10888 const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: LHS);
10889 const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(Val: 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(T1: LHSTy->getPointeeType(), T2: RHSTy))
10907 return;
10908
10909 S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
10910 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: 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(T: LHSTy)) {
10916 QualType ArrayElemTy = ArrayTy->getElementType();
10917 if (ArrayElemTy != S.Context.getBaseElementType(VAT: ArrayTy) ||
10918 ArrayElemTy->isDependentType() || RHSTy->isDependentType() ||
10919 RHSTy->isReferenceType() || ArrayElemTy->isCharType() ||
10920 S.Context.getTypeSize(T: ArrayElemTy) == S.Context.getTypeSize(T: 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>(Val: 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
10934static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
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
10947QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
10948 SourceLocation Loc,
10949 bool IsCompAssign, bool IsDiv) {
10950 checkArithmeticNull(S&: *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*/ AllowBoolOperation: false,
10959 /*ReportInvalid*/ true);
10960 if (LHSTy->isSveVLSBuiltinType() || RHSTy->isSveVLSBuiltinType())
10961 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
10962 OperationKind: ACK_Arithmetic);
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
10971 QualType compType = UsualArithmeticConversions(
10972 LHS, RHS, Loc, ACK: 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(S&: *this, LHS, RHS, Loc, IsDiv);
10981 DiagnoseDivisionSizeofPointerOrArray(S&: *this, LHS: LHS.get(), RHS: RHS.get(), Loc);
10982 }
10983 return compType;
10984}
10985
10986QualType Sema::CheckRemainderOperands(
10987 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
10988 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/false);
10989
10990 if (LHS.get()->getType()->isVectorType() ||
10991 RHS.get()->getType()->isVectorType()) {
10992 if (LHS.get()->getType()->hasIntegerRepresentation() &&
10993 RHS.get()->getType()->hasIntegerRepresentation())
10994 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10995 /*AllowBothBool*/ getLangOpts().AltiVec,
10996 /*AllowBoolConversions*/ false,
10997 /*AllowBooleanOperation*/ AllowBoolOperation: 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() &&
11005 RHS.get()->getType()->hasIntegerRepresentation())
11006 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
11007 OperationKind: ACK_Arithmetic);
11008
11009 return InvalidOperands(Loc, LHS, RHS);
11010 }
11011
11012 QualType compType = UsualArithmeticConversions(
11013 LHS, RHS, Loc, ACK: 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(S&: *this, LHS, RHS, Loc, IsDiv: false /* IsDiv */);
11020 return compType;
11021}
11022
11023/// Diagnose invalid arithmetic on two void pointers.
11024static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
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.
11034static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
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///
11047static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
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///
11059static void diagnoseSubtractionOnNullPointer(Sema &S, SourceLocation Loc,
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?
11066 if (S.Diags.getSuppressSystemWarnings() && S.SourceMgr.isInSystemMacro(loc: Loc))
11067 return;
11068
11069 S.DiagRuntimeBehavior(Loc, Pointer,
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.
11076static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
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.
11085 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
11086 RHS->getType())
11087 << RHS->getType()->getPointeeType()
11088 << LHS->getSourceRange() << RHS->getSourceRange();
11089}
11090
11091/// Diagnose invalid arithmetic on a function pointer.
11092static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
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
11106static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
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).
11128static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
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, Pointer: Operand);
11139 return !S.getLangOpts().CPlusPlus;
11140 }
11141 if (PointeeTy->isFunctionType()) {
11142 diagnoseArithmeticOnFunctionPointer(S, Loc, Pointer: 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).
11160static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
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(T: 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, Pointer: LHSExpr);
11186 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, Pointer: 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, Pointer: LHSExpr);
11196 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
11197 Pointer: RHSExpr);
11198 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHS: LHSExpr, RHS: RHSExpr);
11199
11200 return !S.getLangOpts().CPlusPlus;
11201 }
11202
11203 if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: LHSExpr))
11204 return false;
11205 if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, Operand: RHSExpr))
11206 return false;
11207
11208 return true;
11209}
11210
11211/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11212/// literal.
11213static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
11214 Expr *LHSExpr, Expr *RHSExpr) {
11215 StringLiteral* StrExpr = dyn_cast<StringLiteral>(Val: LHSExpr->IgnoreImpCasts());
11216 Expr* IndexExpr = RHSExpr;
11217 if (!StrExpr) {
11218 StrExpr = dyn_cast<StringLiteral>(Val: RHSExpr->IgnoreImpCasts());
11219 IndexExpr = LHSExpr;
11220 }
11221
11222 bool IsStringPlusInt = StrExpr &&
11223 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
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(Loc: RHSExpr->getEndLoc());
11234 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11235 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11236 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
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.
11243static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
11244 Expr *LHSExpr, Expr *RHSExpr) {
11245 const Expr *StringRefExpr = LHSExpr;
11246 const CharacterLiteral *CharExpr =
11247 dyn_cast<CharacterLiteral>(Val: RHSExpr->IgnoreImpCasts());
11248
11249 if (!CharExpr) {
11250 CharExpr = dyn_cast<CharacterLiteral>(Val: 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(N: Ctx.getCharWidth(), x: 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>(Val: RHSExpr->IgnoreImpCasts())) {
11283 SourceLocation EndLoc = Self.getLocForEndOfToken(Loc: RHSExpr->getEndLoc());
11284 Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
11285 << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
11286 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
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.
11294static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
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
11304QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
11305 SourceLocation Loc, BinaryOperatorKind Opc,
11306 QualType* CompLHSTy) {
11307 checkArithmeticNull(S&: *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, IsCompAssign: CompLHSTy,
11313 /*AllowBothBool*/ getLangOpts().AltiVec,
11314 /*AllowBoolConversions*/ getLangOpts().ZVector,
11315 /*AllowBooleanOperation*/ AllowBoolOperation: 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, IsCompAssign: CompLHSTy, OperationKind: 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, IsCompAssign: CompLHSTy);
11334 if (CompLHSTy)
11335 *CompLHSTy = compType;
11336 return compType;
11337 }
11338
11339 QualType compType = UsualArithmeticConversions(
11340 LHS, RHS, Loc, ACK: 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(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11347 diagnoseStringPlusChar(Self&: *this, OpLoc: Loc, LHSExpr: LHS.get(), RHSExpr: 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(a&: PExp, b&: 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.
11381 if (PExp->IgnoreParenCasts()->isNullPointerConstant(
11382 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull)) {
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(Result&: KnownVal, Ctx: Context) ||
11388 KnownVal.Val.getInt() != 0))) {
11389 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11390 bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
11391 Ctx&: Context, Opc: BO_Add, LHS: PExp, RHS: IExp);
11392 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: PExp, IsGNUIdiom);
11393 }
11394 }
11395
11396 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: PExp))
11397 return QualType();
11398
11399 if (isObjCPointer && checkArithmeticOnObjCPointer(S&: *this, opLoc: Loc, op: PExp))
11400 return QualType();
11401
11402 // Check array bounds for pointer arithemtic
11403 CheckArrayAccess(BaseExpr: PExp, IndexExpr: IExp);
11404
11405 if (CompLHSTy) {
11406 QualType LHSTy = Context.isPromotableBitField(E: LHS.get());
11407 if (LHSTy.isNull()) {
11408 LHSTy = LHS.get()->getType();
11409 if (Context.isPromotableIntegerType(T: LHSTy))
11410 LHSTy = Context.getPromotedIntegerType(PromotableType: LHSTy);
11411 }
11412 *CompLHSTy = LHSTy;
11413 }
11414
11415 return PExp->getType();
11416}
11417
11418// C99 6.5.6
11419QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
11420 SourceLocation Loc,
11421 QualType* CompLHSTy) {
11422 checkArithmeticNull(S&: *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, IsCompAssign: CompLHSTy,
11428 /*AllowBothBool*/ getLangOpts().AltiVec,
11429 /*AllowBoolConversions*/ getLangOpts().ZVector,
11430 /*AllowBooleanOperation*/ AllowBoolOperation: 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, IsCompAssign: CompLHSTy, OperationKind: 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, IsCompAssign: CompLHSTy);
11449 if (CompLHSTy)
11450 *CompLHSTy = compType;
11451 return compType;
11452 }
11453
11454 QualType compType = UsualArithmeticConversions(
11455 LHS, RHS, Loc, ACK: 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(S&: *this, opLoc: Loc, op: 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.
11481 if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Ctx&: Context,
11482 NPC: Expr::NPC_ValueDependentIsNotNull)) {
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(Result&: KnownVal, Ctx: Context) ||
11488 KnownVal.Val.getInt() != 0))) {
11489 diagnoseArithmeticOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), IsGNUIdiom: false);
11490 }
11491 }
11492
11493 if (!checkArithmeticOpPointerOperand(S&: *this, Loc, Operand: LHS.get()))
11494 return QualType();
11495
11496 // Check array bounds for pointer arithemtic
11497 CheckArrayAccess(BaseExpr: LHS.get(), IndexExpr: RHS.get(), /*ArraySubscriptExpr*/ASE: 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(T1: lpointee, T2: rpointee)) {
11512 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11513 }
11514 } else {
11515 // Pointee types must be compatible C99 6.5.6p3
11516 if (!Context.typesAreCompatible(
11517 T1: Context.getCanonicalType(T: lpointee).getUnqualifiedType(),
11518 T2: Context.getCanonicalType(T: rpointee).getUnqualifiedType())) {
11519 diagnosePointerIncompatibility(S&: *this, Loc, LHSExpr: LHS.get(), RHSExpr: RHS.get());
11520 return QualType();
11521 }
11522 }
11523
11524 if (!checkArithmeticBinOpPointerOperands(S&: *this, Loc,
11525 LHSExpr: LHS.get(), RHSExpr: RHS.get()))
11526 return QualType();
11527
11528 bool LHSIsNullPtr = LHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11529 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
11530 bool RHSIsNullPtr = RHS.get()->IgnoreParenCasts()->isNullPointerConstant(
11531 Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNotNull);
11532
11533 // Subtracting nullptr or from nullptr is suspect
11534 if (LHSIsNullPtr)
11535 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: LHS.get(), BothNull: RHSIsNullPtr);
11536 if (RHSIsNullPtr)
11537 diagnoseSubtractionOnNullPointer(S&: *this, Loc, Pointer: RHS.get(), BothNull: 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(T: 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
11559static bool isScopedEnumerationType(QualType T) {
11560 if (const EnumType *ET = T->getAs<EnumType>())
11561 return ET->getDecl()->isScoped();
11562 return false;
11563}
11564
11565static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
11566 SourceLocation Loc, BinaryOperatorKind Opc,
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(Result&: RHSResult, Ctx: 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(T: LHSExprType);
11589 if (LHSExprType->isBitIntType())
11590 LeftSize = S.Context.getIntWidth(T: LHSExprType);
11591 else if (LHSExprType->isFixedPointType()) {
11592 auto FXSema = S.Context.getFixedPointSemantics(Ty: LHSExprType);
11593 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
11594 }
11595 if (Right.uge(RHS: 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() ||
11614 LHSType->hasUnsignedIntegerRepresentation() ||
11615 !LHS.get()->EvaluateAsInt(Result&: LHSResult, Ctx: 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(RHS: LeftSize))
11638 return;
11639 llvm::APSInt Result = Left.extend(width: ResultBits.getLimitedValue());
11640 Result = Result.shl(ShiftAmt: Right);
11641
11642 // Print the bit representation of the signed integer as an unsigned
11643 // hexadecimal number.
11644 SmallString<40> HexResult;
11645 Result.toString(Str&: HexResult, Radix: 16, /*Signed =*/false, /*Literal =*/formatAsCLiteral: 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.
11666static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
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(E: LHS.get());
11679 if (LHS.isInvalid()) return QualType();
11680 }
11681
11682 RHS = S.UsualUnaryConversions(E: 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(E: LHS.get(),Type: RHSEleType, CK: CK_IntegralCast);
11724 LHSEleType = RHSEleType;
11725 }
11726 QualType VecTy =
11727 S.Context.getExtVectorType(VectorType: LHSEleType, NumElts: RHSVecTy->getNumElements());
11728 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: 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(VectorType: RHSEleType, NumElts: LHSVecTy->getNumElements());
11754 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
11755 }
11756
11757 return LHSType;
11758}
11759
11760static QualType checkSizelessVectorShift(Sema &S, ExprResult &LHS,
11761 ExprResult &RHS, SourceLocation Loc,
11762 bool IsCompAssign) {
11763 if (!IsCompAssign) {
11764 LHS = S.UsualUnaryConversions(E: LHS.get());
11765 if (LHS.isInvalid())
11766 return QualType();
11767 }
11768
11769 RHS = S.UsualUnaryConversions(E: 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(VecTy: LHSBuiltinTy).EC !=
11807 S.Context.getBuiltinVectorTypeInfo(VecTy: 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(E: LHS.get(), Type: RHSEleType, CK: clang::CK_IntegralCast);
11820 LHSEleType = RHSEleType;
11821 }
11822 const llvm::ElementCount VecSize =
11823 S.Context.getBuiltinVectorTypeInfo(VecTy: RHSBuiltinTy).EC;
11824 QualType VecTy =
11825 S.Context.getScalableVectorType(EltTy: LHSEleType, NumElts: VecSize.getKnownMinValue());
11826 LHS = S.ImpCastExprToType(E: LHS.get(), Type: VecTy, CK: 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(VecTy: LHSBuiltinTy).EC;
11839 if (LHSEleType != RHSEleType) {
11840 RHS = S.ImpCastExprToType(E: RHS.get(), Type: LHSEleType, CK: clang::CK_IntegralCast);
11841 RHSEleType = LHSEleType;
11842 }
11843 QualType VecTy =
11844 S.Context.getScalableVectorType(EltTy: RHSEleType, NumElts: VecSize.getKnownMinValue());
11845 RHS = S.ImpCastExprToType(E: RHS.get(), Type: VecTy, CK: CK_VectorSplat);
11846 }
11847
11848 return LHSType;
11849}
11850
11851// C99 6.5.7
11852QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
11853 SourceLocation Loc, BinaryOperatorKind Opc,
11854 bool IsCompAssign) {
11855 checkArithmeticNull(S&: *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(S&: *this, LHS, RHS, Loc, IsCompAssign);
11872 }
11873
11874 if (LHS.get()->getType()->isSveVLSBuiltinType() ||
11875 RHS.get()->getType()->isSveVLSBuiltinType())
11876 return checkSizelessVectorShift(S&: *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(E: 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(E: 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(T: LHSType) ||
11906 isScopedEnumerationType(T: RHSType)) {
11907 return InvalidOperands(Loc, LHS, RHS);
11908 }
11909 DiagnoseBadShiftValues(S&: *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.
11916static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
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.
11927static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
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, E1&: LHS, E2&: RHS);
11944 if (T.isNull()) {
11945 if ((LHSType->isAnyPointerType() || LHSType->isMemberPointerType()) &&
11946 (RHSType->isAnyPointerType() || RHSType->isMemberPointerType()))
11947 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/IsError: true);
11948 else
11949 S.InvalidOperands(Loc, LHS, RHS);
11950 return true;
11951 }
11952
11953 return false;
11954}
11955
11956static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
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
11966static bool isObjCObjectLiteral(ExprResult &E) {
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) {
11980 const ObjCObjectPointerType *Type =
11981 LHS->getType()->getAs<ObjCObjectPointerType>();
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(Sel: IsEqualSel,
11997 Ty: InterfaceType,
11998 /*IsInstance=*/true);
11999 if (!Method) {
12000 if (Type->isObjCIdType()) {
12001 // For 'id', just check the global pool.
12002 Method = S.LookupInstanceMethodInGlobalPool(Sel: IsEqualSel, R: SourceRange(),
12003 /*receiverId=*/receiverIdOrClass: true);
12004 } else {
12005 // Check protocols.
12006 Method = S.LookupMethodInQualifiedType(Sel: IsEqualSel, OPT: 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
12025Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
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>(Val: 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>(Val: 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
12067static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
12068 ExprResult &LHS, ExprResult &RHS,
12069 BinaryOperator::Opcode Opc){
12070 Expr *Literal;
12071 Expr *Other;
12072 if (isObjCObjectLiteral(E&: 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(Ctx&: S.getASTContext(),
12083 NPC: Expr::NPC_ValueDependentIsNotNull))
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(FromE: 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
12102 if (BinaryOperator::isEqualityOp(Opc) &&
12103 hasIsEqualMethod(S, LHS: LHS.get(), RHS: RHS.get())) {
12104 SourceLocation Start = LHS.get()->getBeginLoc();
12105 SourceLocation End = S.getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
12106 CharSourceRange OpRange =
12107 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
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.
12117static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
12118 ExprResult &RHS, SourceLocation Loc,
12119 BinaryOperatorKind Opc) {
12120 // Check that left hand side is !something.
12121 UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: 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(Loc: 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(Loc: 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>(Val: E)) {
12162 D = DR->getDecl();
12163 } else if (const MemberExpr *Mem = dyn_cast<MemberExpr>(Val: 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.
12173static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
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)) ||
12183 S.inTemplateInstantiation())
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(E1: LHS, E2: 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(E: LHSStripped) && checkForArray(E: 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>(Val: LHSStripped))
12276 LHSStripped = LHSStripped->IgnoreParenCasts();
12277 if (isa<CastExpr>(Val: 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>(Val: LHSStripped) || isa<ObjCEncodeExpr>(Val: LHSStripped)) &&
12285 !RHSStripped->isNullPointerConstant(Ctx&: S.Context,
12286 NPC: Expr::NPC_ValueDependentIsNull)) {
12287 LiteralString = LHS;
12288 LiteralStringStripped = LHSStripped;
12289 } else if ((isa<StringLiteral>(Val: RHSStripped) ||
12290 isa<ObjCEncodeExpr>(Val: RHSStripped)) &&
12291 !LHSStripped->isNullPointerConstant(Ctx&: S.Context,
12292 NPC: Expr::NPC_ValueDependentIsNull)) {
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
12305static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
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:
12321 return ICK_Function_To_Pointer;
12322 case CK_IntegralCast:
12323 return ICK_Integral_Conversion;
12324 case CK_FloatingCast:
12325 return ICK_Floating_Conversion;
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:
12333 return ICK_Complex_Conversion;
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
12344static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
12345 QualType FromType,
12346 SourceLocation Loc) {
12347 // Check for a narrowing implicit conversion.
12348 StandardConversionSequence SCS;
12349 SCS.setAsIdentityConversion();
12350 SCS.setToType(Idx: 0, T: FromType);
12351 SCS.setToType(Idx: 1, T: ToType);
12352 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E))
12353 SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
12354
12355 APValue PreNarrowingValue;
12356 QualType PreNarrowingType;
12357 switch (SCS.getNarrowingKind(Context&: S.Context, Converted: E, ConstantValue&: PreNarrowingValue,
12358 ConstantType&: PreNarrowingType,
12359 /*IgnoreFloatToIntegralConversion*/ true)) {
12360 case NK_Dependent_Narrowing:
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
12366 case NK_Constant_Narrowing:
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
12374 case NK_Variable_Narrowing:
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
12387static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
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, LHS&: LHSStripped, RHS&: 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, LHS&: LHSStripped, RHS&: 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(T1: LHSStrippedType, T2: 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(T: IntType))
12435 IntType = S.Context.getPromotedIntegerType(PromotableType: IntType);
12436
12437 LHS = S.ImpCastExprToType(E: LHS.get(), Type: IntType, CK: CK_IntegralCast);
12438 RHS = S.ImpCastExprToType(E: RHS.get(), Type: IntType, CK: 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 =
12445 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: Sema::ACK_Comparison);
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 =
12452 getComparisonCategoryForBuiltinCmp(T: Type);
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
12465 return S.CheckComparisonCategoryType(
12466 Kind: *CCT, Loc, Usage: Sema::ComparisonCategoryUsage::OperatorInExpression);
12467}
12468
12469static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
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 =
12478 S.UsualArithmeticConversions(LHS, RHS, Loc, ACK: Sema::ACK_Comparison);
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
12485 if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
12486 return S.InvalidOperands(Loc, LHS, RHS);
12487
12488 // Check for comparisons of floating point operands using != and ==.
12489 if (Type->hasFloatingRepresentation())
12490 S.CheckFloatComparison(Loc, LHS: LHS.get(), RHS: RHS.get(), Opcode: Opc);
12491
12492 // The result of comparisons is 'bool' in C++, 'int' in C.
12493 return S.Context.getLogicalOperationType();
12494}
12495
12496void Sema::CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE) {
12497 if (!NullE.get()->getType()->isAnyPointerType())
12498 return;
12499 int NullValue = PP.isMacroDefined(Id: "NULL") ? 0 : 1;
12500 if (!E.get()->getType()->isAnyPointerType() &&
12501 E.get()->isNullPointerConstant(Ctx&: Context,
12502 NPC: Expr::NPC_ValueDependentIsNotNull) ==
12503 Expr::NPCK_ZeroExpression) {
12504 if (const auto *CL = dyn_cast<CharacterLiteral>(Val: E.get())) {
12505 if (CL->getValue() == 0)
12506 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12507 << NullValue
12508 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12509 NullValue ? "NULL" : "(void *)0");
12510 } else if (const auto *CE = dyn_cast<CStyleCastExpr>(Val: E.get())) {
12511 TypeSourceInfo *TI = CE->getTypeInfoAsWritten();
12512 QualType T = Context.getCanonicalType(T: TI->getType()).getUnqualifiedType();
12513 if (T == Context.CharTy)
12514 Diag(E.get()->getExprLoc(), diag::warn_pointer_compare)
12515 << NullValue
12516 << FixItHint::CreateReplacement(E.get()->getExprLoc(),
12517 NullValue ? "NULL" : "(void *)0");
12518 }
12519 }
12520}
12521
12522// C99 6.5.8, C++ [expr.rel]
12523QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
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)) {
12540 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
12541 if (LHS.isInvalid())
12542 return QualType();
12543 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
12544 if (RHS.isInvalid())
12545 return QualType();
12546 } else {
12547 LHS = DefaultLvalueConversion(E: LHS.get());
12548 if (LHS.isInvalid())
12549 return QualType();
12550 RHS = DefaultLvalueConversion(E: RHS.get());
12551 if (RHS.isInvalid())
12552 return QualType();
12553 }
12554
12555 checkArithmeticNull(S&: *this, LHS, RHS, Loc, /*IsCompare=*/true);
12556 if (!getLangOpts().CPlusPlus && BinaryOperator::isEqualityOp(Opc)) {
12557 CheckPtrComparisonWithNullChar(E&: LHS, NullE&: RHS);
12558 CheckPtrComparisonWithNullChar(E&: RHS, NullE&: LHS);
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(S&: *this, LHS, RHS, Loc, Opc);
12571 diagnoseTautologicalComparison(S&: *this, Loc, LHS: LHS.get(), RHS: 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(S&: *this, LHS, RHS, Loc, Opc);
12578
12579 if ((LHSType->isPointerType() &&
12580 LHSType->getPointeeType().isWebAssemblyReferenceType()) ||
12581 (RHSType->isPointerType() &&
12582 RHSType->getPointeeType().isWebAssemblyReferenceType()))
12583 return InvalidOperands(Loc, LHS, RHS);
12584
12585 const Expr::NullPointerConstantKind LHSNullKind =
12586 LHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
12587 const Expr::NullPointerConstantKind RHSNullKind =
12588 RHS.get()->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull);
12589 bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
12590 bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
12591
12592 auto computeResultTy = [&]() {
12593 if (Opc != BO_Cmp)
12594 return Context.getLogicalOperationType();
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 =
12602 getComparisonCategoryForBuiltinCmp(T: CompositeTy);
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
12616 return CheckComparisonCategoryType(
12617 Kind: *CCT, Loc, Usage: ComparisonCategoryUsage::OperatorInExpression);
12618 };
12619
12620 if (!IsOrdered && LHSIsNull != RHSIsNull) {
12621 bool IsEquality = Opc == BO_EQ;
12622 if (RHSIsNull)
12623 DiagnoseAlwaysNonNullPointer(E: LHS.get(), NullType: RHSNullKind, IsEqual: IsEquality,
12624 Range: RHS.get()->getSourceRange());
12625 else
12626 DiagnoseAlwaysNonNullPointer(E: RHS.get(), NullType: LHSNullKind, IsEqual: IsEquality,
12627 Range: 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.
12660 diagnoseFunctionPointerToVoidComparison(
12661 S&: *this, Loc, LHS, RHS, /*isError*/ IsError: (bool)isSFINAEContext());
12662
12663 if (isSFINAEContext())
12664 return QualType();
12665
12666 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: 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(S&: *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(T1: LCanPointeeTy.getUnqualifiedType(),
12701 T2: 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(S&: *this, Loc, LHS, RHS,
12719 /*isError*/IsError: false);
12720 } else {
12721 // Invalid
12722 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS, /*isError*/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(T: 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(E: LHS.get(), Type: RHSType, CK: Kind);
12740 else
12741 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: 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(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
12758 return computeResultTy();
12759 }
12760 if (RHSType->isNullPtrType()) {
12761 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: 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(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
12773 return computeResultTy();
12774 }
12775 if (RHSIsNull && LHSType->isPointerType()) {
12776 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: 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(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
12786 return computeResultTy();
12787 }
12788 if (!IsOrdered && LHSType->isNullPtrType() &&
12789 (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
12790 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: 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>(Val: DC))
12805 DC = DC->getParent();
12806 if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: DC)) {
12807 if (CTSD->isInStdNamespace() &&
12808 llvm::StringSwitch<bool>(CTSD->getName())
12809 .Cases(S0: "less", S1: "less_equal", S2: "greater", S3: "greater_equal", Value: true)
12810 .Default(Value: false)) {
12811 if (RHSType->isNullPtrType())
12812 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
12813 else
12814 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: 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(S&: *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(T1: lpointee, T2: 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(E: RHS.get(), Type: LHSType, CK: 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>()
12854 ->getPointeeType()->isVoidType())
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(E: LHS.get(), Type: RHSType,
12863 CK: RHSType->isPointerType() ? CK_BitCast
12864 : CK_AnyPointerToBlockPointerCast);
12865 else
12866 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
12867 CK: 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(T1: LHSType, T2: RHSType)) {
12882 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
12883 /*isError*/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(castRange: SourceRange(), castType: RHSType, op&: E,
12892 CCK: CheckedConversionKind::Implicit);
12893 LHS = ImpCastExprToType(E, Type: RHSType,
12894 CK: RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12895 }
12896 else {
12897 Expr *E = RHS.get();
12898 if (getLangOpts().ObjCAutoRefCount)
12899 CheckObjCConversion(castRange: SourceRange(), castType: LHSType, op&: E,
12900 CCK: CheckedConversionKind::Implicit,
12901 /*Diagnose=*/true,
12902 /*DiagnoseCFAudited=*/false, Opc);
12903 RHS = ImpCastExprToType(E, Type: LHSType,
12904 CK: LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
12905 }
12906 return computeResultTy();
12907 }
12908 if (LHSType->isObjCObjectPointerType() &&
12909 RHSType->isObjCObjectPointerType()) {
12910 if (!Context.areComparableObjCPointerTypes(LHS: LHSType, RHS: RHSType))
12911 diagnoseDistinctPointerComparison(S&: *this, Loc, LHS, RHS,
12912 /*isError*/IsError: false);
12913 if (isObjCObjectLiteral(E&: LHS) || isObjCObjectLiteral(E&: RHS))
12914 diagnoseObjCLiteralComparison(S&: *this, Loc, LHS, RHS, Opc);
12915
12916 if (LHSIsNull && !RHSIsNull)
12917 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: CK_BitCast);
12918 else
12919 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: CK_BitCast);
12920 return computeResultTy();
12921 }
12922
12923 if (!IsOrdered && LHSType->isBlockPointerType() &&
12924 RHSType->isBlockCompatibleObjCPointerType(ctx&: Context)) {
12925 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType,
12926 CK: CK_BlockPointerToObjCPointerCast);
12927 return computeResultTy();
12928 } else if (!IsOrdered &&
12929 LHSType->isBlockCompatibleObjCPointerType(ctx&: Context) &&
12930 RHSType->isBlockPointerType()) {
12931 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
12932 CK: 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(E: LHS.get(), Type: RHSType,
12969 CK: LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
12970 else
12971 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType,
12972 CK: 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(E: RHS.get(), Type: LHSType, CK: CK_NullToPointer);
12980 return computeResultTy();
12981 }
12982 if (!IsOrdered && LHSIsNull
12983 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
12984 LHS = ImpCastExprToType(E: LHS.get(), Type: RHSType, CK: 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(E: LHS.get(), Type: RHSType, CK: CK_NullToPointer);
12999 return computeResultTy();
13000 }
13001
13002 if (LHSType->isQueueT() && RHSIsNull) {
13003 RHS = ImpCastExprToType(E: RHS.get(), Type: LHSType, CK: 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.
13016QualType Sema::GetSignedVectorType(QualType V) {
13017 const VectorType *VTy = V->castAs<VectorType>();
13018 unsigned TypeSize = Context.getTypeSize(T: VTy->getElementType());
13019
13020 if (isa<ExtVectorType>(Val: VTy)) {
13021 if (VTy->isExtVectorBoolType())
13022 return Context.getExtVectorType(VectorType: Context.BoolTy, NumElts: VTy->getNumElements());
13023 if (TypeSize == Context.getTypeSize(Context.CharTy))
13024 return Context.getExtVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements());
13025 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13026 return Context.getExtVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements());
13027 if (TypeSize == Context.getTypeSize(Context.IntTy))
13028 return Context.getExtVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements());
13029 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13030 return Context.getExtVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements());
13031 if (TypeSize == Context.getTypeSize(Context.LongTy))
13032 return Context.getExtVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements());
13033 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
13034 "Unhandled vector element size in vector compare");
13035 return Context.getExtVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements());
13036 }
13037
13038 if (TypeSize == Context.getTypeSize(Context.Int128Ty))
13039 return Context.getVectorType(VectorType: Context.Int128Ty, NumElts: VTy->getNumElements(),
13040 VecKind: VectorKind::Generic);
13041 if (TypeSize == Context.getTypeSize(Context.LongLongTy))
13042 return Context.getVectorType(VectorType: Context.LongLongTy, NumElts: VTy->getNumElements(),
13043 VecKind: VectorKind::Generic);
13044 if (TypeSize == Context.getTypeSize(Context.LongTy))
13045 return Context.getVectorType(VectorType: Context.LongTy, NumElts: VTy->getNumElements(),
13046 VecKind: VectorKind::Generic);
13047 if (TypeSize == Context.getTypeSize(Context.IntTy))
13048 return Context.getVectorType(VectorType: Context.IntTy, NumElts: VTy->getNumElements(),
13049 VecKind: VectorKind::Generic);
13050 if (TypeSize == Context.getTypeSize(Context.ShortTy))
13051 return Context.getVectorType(VectorType: Context.ShortTy, NumElts: VTy->getNumElements(),
13052 VecKind: VectorKind::Generic);
13053 assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
13054 "Unhandled vector element size in vector compare");
13055 return Context.getVectorType(VectorType: Context.CharTy, NumElts: VTy->getNumElements(),
13056 VecKind: VectorKind::Generic);
13057}
13058
13059QualType Sema::GetSignedSizelessVectorType(QualType V) {
13060 const BuiltinType *VTy = V->castAs<BuiltinType>();
13061 assert(VTy->isSizelessBuiltinType() && "expected sizeless type");
13062
13063 const QualType ETy = V->getSveEltType(Ctx: Context);
13064 const auto TypeSize = Context.getTypeSize(T: ETy);
13065
13066 const QualType IntTy = Context.getIntTypeForBitwidth(DestWidth: TypeSize, Signed: true);
13067 const llvm::ElementCount VecSize = Context.getBuiltinVectorTypeInfo(VecTy: VTy).EC;
13068 return Context.getScalableVectorType(EltTy: IntTy, NumElts: 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.
13075QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
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*/ IsCompAssign: false,
13087 /*AllowBothBool*/ true,
13088 /*AllowBoolConversions*/ getLangOpts().ZVector,
13089 /*AllowBooleanOperation*/ AllowBoolOperation: 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()) {
13103 case LangOptions::AltivecSrcCompatKind::Mixed:
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() ==
13107 VectorKind::AltiVecVector)
13108 return Context.getLogicalOperationType();
13109 else
13110 Diag(Loc, diag::warn_deprecated_altivec_src_compat);
13111 break;
13112 case LangOptions::AltivecSrcCompatKind::GCC:
13113 // For GCC we always return the vector type.
13114 break;
13115 case LangOptions::AltivecSrcCompatKind::XL:
13116 return Context.getLogicalOperationType();
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(S&: *this, Loc, LHS: LHS.get(), RHS: 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: LHS.get(), RHS: RHS.get(), Opcode: Opc);
13130 }
13131
13132 // Return a signed type for the vector.
13133 return GetSignedVectorType(V: vType);
13134}
13135
13136QualType Sema::CheckSizelessVectorCompareOperands(ExprResult &LHS,
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.
13147 QualType vType = CheckSizelessVectorOperands(
13148 LHS, RHS, Loc, /*isCompAssign*/ IsCompAssign: false, OperationKind: 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(S&: *this, Loc, LHS: LHS.get(), RHS: 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: LHS.get(), RHS: RHS.get(), Opcode: 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(V: 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>(Val: XorLHS.get());
13192 const auto *RHSInt = dyn_cast<IntegerLiteral>(Val: XorRHS.get());
13193
13194 if (!LHSInt)
13195 return;
13196 if (!RHSInt) {
13197 // Check negative literals.
13198 if (const auto *UO = dyn_cast<UnaryOperator>(Val: XorRHS.get())) {
13199 UnaryOperatorKind Opc = UO->getOpcode();
13200 if (Opc != UO_Minus && Opc != UO_Plus)
13201 return;
13202 RHSInt = dyn_cast<IntegerLiteral>(Val: 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
13220 CharSourceRange ExprRange = CharSourceRange::getCharRange(
13221 B: LHSInt->getBeginLoc(), E: S.getLocForEndOfToken(Loc: RHSInt->getLocation()));
13222 llvm::StringRef ExprStr =
13223 Lexer::getSourceText(Range: ExprRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
13224
13225 CharSourceRange XorRange =
13226 CharSourceRange::getCharRange(B: Loc, E: S.getLocForEndOfToken(Loc));
13227 llvm::StringRef XorStr =
13228 Lexer::getSourceText(Range: XorRange, SM: S.getSourceManager(), LangOpts: S.getLangOpts());
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 Range: CharSourceRange::getTokenRange(LHSInt->getSourceRange()),
13235 SM: S.getSourceManager(), LangOpts: S.getLangOpts()));
13236 std::string RHSStr = std::string(Lexer::getSourceText(
13237 Range: CharSourceRange::getTokenRange(RHSInt->getSourceRange()),
13238 SM: S.getSourceManager(), LangOpts: 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(Prefix: "0b") || LHSStrRef.starts_with(Prefix: "0B") ||
13252 RHSStrRef.starts_with(Prefix: "0b") || RHSStrRef.starts_with(Prefix: "0B") ||
13253 LHSStrRef.starts_with(Prefix: "0x") || LHSStrRef.starts_with(Prefix: "0X") ||
13254 RHSStrRef.starts_with(Prefix: "0x") || RHSStrRef.starts_with(Prefix: "0X") ||
13255 (LHSStrRef.size() > 1 && LHSStrRef.starts_with(Prefix: "0")) ||
13256 (RHSStrRef.size() > 1 && RHSStrRef.starts_with(Prefix: "0")) ||
13257 LHSStrRef.contains(C: '\'') || RHSStrRef.contains(C: '\''))
13258 return;
13259
13260 bool SuggestXor =
13261 S.getLangOpts().CPlusPlus || S.getPreprocessor().isMacroDefined(Id: "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(Amt: 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)
13283 << FixItHint::CreateReplacement(
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(val: 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
13299QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
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, IsCompAssign: false,
13304 /*AllowBothBool*/ true,
13305 /*AllowBoolConversions*/ false,
13306 /*AllowBooleanOperation*/ AllowBoolOperation: false,
13307 /*ReportInvalid*/ false);
13308 if (vType.isNull())
13309 return InvalidOperands(Loc, LHS, RHS);
13310 if (getLangOpts().OpenCL &&
13311 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13312 vType->hasFloatingRepresentation())
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>(Val: vType->getAs<VectorType>())))
13319 return InvalidLogicalVectorOperands(Loc, LHS, RHS);
13320
13321 return GetSignedVectorType(V: LHS.get()->getType());
13322}
13323
13324QualType Sema::CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
13325 SourceLocation Loc,
13326 bool IsCompAssign) {
13327 if (!IsCompAssign) {
13328 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13329 if (LHS.isInvalid())
13330 return QualType();
13331 }
13332 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
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(T1: LHSType, T2: RHSType))
13346 return Context.getCommonSugaredType(X: LHSType, Y: 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(E: RHS.get(), Ty: LHSMatType->getElementType());
13354 if (!RHS.isInvalid())
13355 return LHSType;
13356
13357 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13358 }
13359
13360 if (!LHSMatType && RHSMatType) {
13361 LHS = tryConvertExprToType(E: LHS.get(), Ty: RHSMatType->getElementType());
13362 if (!LHS.isInvalid())
13363 return RHSType;
13364 return InvalidOperands(Loc, LHS&: OriginalLHS, RHS&: OriginalRHS);
13365 }
13366
13367 return InvalidOperands(Loc, LHS, RHS);
13368}
13369
13370QualType Sema::CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
13371 SourceLocation Loc,
13372 bool IsCompAssign) {
13373 if (!IsCompAssign) {
13374 LHS = DefaultFunctionArrayLvalueConversion(E: LHS.get());
13375 if (LHS.isInvalid())
13376 return QualType();
13377 }
13378 RHS = DefaultFunctionArrayLvalueConversion(E: RHS.get());
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))
13391 return Context.getCommonSugaredType(
13392 X: LHS.get()->getType().getUnqualifiedType(),
13393 Y: RHS.get()->getType().getUnqualifiedType());
13394
13395 QualType LHSELTy = LHSMatType->getElementType(),
13396 RHSELTy = RHSMatType->getElementType();
13397 if (!Context.hasSameType(T1: LHSELTy, T2: RHSELTy))
13398 return InvalidOperands(Loc, LHS, RHS);
13399
13400 return Context.getConstantMatrixType(
13401 ElementType: Context.getCommonSugaredType(X: LHSELTy, Y: RHSELTy),
13402 NumRows: LHSMatType->getNumRows(), NumColumns: RHSMatType->getNumColumns());
13403 }
13404 return CheckMatrixElementwiseOperands(LHS, RHS, Loc, IsCompAssign);
13405}
13406
13407static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc) {
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
13421inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
13422 SourceLocation Loc,
13423 BinaryOperatorKind Opc) {
13424 checkArithmeticNull(S&: *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() &&
13434 RHS.get()->getType()->hasIntegerRepresentation())
13435 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
13436 /*AllowBothBool*/ true,
13437 /*AllowBoolConversions*/ getLangOpts().ZVector,
13438 /*AllowBooleanOperation*/ AllowBoolOperation: 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() &&
13446 RHS.get()->getType()->hasIntegerRepresentation())
13447 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13448 OperationKind: ACK_BitwiseOp);
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() &&
13455 RHS.get()->getType()->hasIntegerRepresentation())
13456 return CheckSizelessVectorOperands(LHS, RHS, Loc, IsCompAssign,
13457 OperationKind: ACK_BitwiseOp);
13458 return InvalidOperands(Loc, LHS, RHS);
13459 }
13460
13461 if (Opc == BO_And)
13462 diagnoseLogicalNotOnLHSofCheck(S&: *this, LHS, RHS, Loc, Opc);
13463
13464 if (LHS.get()->getType()->hasFloatingRepresentation() ||
13465 RHS.get()->getType()->hasFloatingRepresentation())
13466 return InvalidOperands(Loc, LHS, RHS);
13467
13468 ExprResult LHSResult = LHS, RHSResult = RHS;
13469 QualType compType = UsualArithmeticConversions(
13470 LHS&: LHSResult, RHS&: RHSResult, Loc, ACK: 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(S&: *this, XorLHS: LHS, XorRHS: 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]
13485inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
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>(Val: HS.get())) {
13496 const auto *ECDHS = dyn_cast<EnumConstantDecl>(Val: 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>(Val&: LHSTy);
13509 const auto *RHSATy = dyn_cast<ArrayType>(Val&: 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(Result&: EVResult, Ctx: 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 ? "&" : "|")
13538 << FixItHint::CreateReplacement(
13539 SourceRange(Loc, getLocForEndOfToken(Loc)),
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)
13544 << FixItHint::CreateRemoval(
13545 SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
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(E: LHS.get());
13562 if (LHS.isInvalid())
13563 return QualType();
13564
13565 RHS = UsualUnaryConversions(E: 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.
13582 ExprResult LHSRes = PerformContextuallyConvertToBool(From: LHS.get());
13583 if (LHSRes.isInvalid())
13584 return InvalidOperands(Loc, LHS, RHS);
13585 LHS = LHSRes;
13586
13587 ExprResult RHSRes = PerformContextuallyConvertToBool(From: RHS.get());
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>(Val: E);
13600 if (!ME) return false;
13601 if (!isa<FieldDecl>(Val: ME->getMemberDecl())) return false;
13602 ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
13603 Val: ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
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?
13611enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
13612static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
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>(Val: E);
13618 if (!DRE) return NCCK_None;
13619 if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
13620
13621 // The declaration must be a variable which is not declared 'const'.
13622 VarDecl *var = dyn_cast<VarDecl>(Val: 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>(Val: 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>(Val: 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 {
13658 ConstFunction,
13659 ConstVariable,
13660 ConstMember,
13661 ConstMethod,
13662 NestedConstMember,
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
13687 E = E->IgnoreImplicit()->IgnoreParenImpCasts();
13688 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
13689 NextIsDereference = ME->isArrow();
13690 const ValueDecl *VD = ME->getMemberDecl();
13691 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Val: 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>(Val: 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>(Val: E)) {
13729 E = ASE->getBase()->IgnoreParenImpCasts();
13730 continue;
13731 } else if (const ExtVectorElementExpr *EVE =
13732 dyn_cast<ExtVectorElementExpr>(Val: E)) {
13733 E = EVE->getBase()->IgnoreParenImpCasts();
13734 continue;
13735 }
13736 break;
13737 }
13738
13739 if (const CallExpr *CE = dyn_cast<CallExpr>(Val: E)) {
13740 // Function calls
13741 const FunctionDecl *FD = CE->getDirectCallee();
13742 if (FD && !IsTypeModifiable(Ty: FD->getReturnType(), IsDereference)) {
13743 if (!DiagnosticEmitted) {
13744 S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
13745 << ConstFunction << FD;
13746 DiagnosticEmitted = true;
13747 }
13748 S.Diag(FD->getReturnTypeSourceRange().getBegin(),
13749 diag::note_typecheck_assign_const)
13750 << ConstFunction << FD << FD->getReturnType()
13751 << FD->getReturnTypeSourceRange();
13752 }
13753 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
13754 // Point to variable declaration.
13755 if (const ValueDecl *VD = DRE->getDecl()) {
13756 if (!IsTypeModifiable(Ty: 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>(Val: E)) {
13767 if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
13768 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: 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
13789enum OriginalExprKind {
13790 OEK_Variable,
13791 OEK_Member,
13792 OEK_LValue
13793};
13794
13795static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
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(x: 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>(Val: E))
13845 DiagnoseRecursiveConstFields(S, VD: ME->getMemberDecl(), Ty: RTy, Loc,
13846 Range, OEK: OEK_Member, DiagnosticEmitted&: DiagEmitted);
13847 else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E))
13848 DiagnoseRecursiveConstFields(S, VD: DRE->getDecl(), Ty: RTy, Loc,
13849 Range, OEK: OEK_Variable, DiagnosticEmitted&: DiagEmitted);
13850 else
13851 DiagnoseRecursiveConstFields(S, VD: nullptr, Ty: RTy, Loc,
13852 Range, OEK: OEK_LValue, DiagnosticEmitted&: 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.
13859static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
13860 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
13861
13862 S.CheckShadowingDeclModification(E, Loc);
13863
13864 SourceLocation OrigLoc = Loc;
13865 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(Ctx&: S.Context,
13866 Loc: &Loc);
13867 if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
13868 IsLV = Expr::MLV_InvalidMessageExpression;
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
13875 case Expr::MLV_ConstQualified:
13876 // Use a specialized diagnostic when we're assigning to an object
13877 // from an enclosing function or block.
13878 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
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>(Val: E->IgnoreParenCasts());
13890 if (declRef && isa<VarDecl>(Val: declRef->getDecl())) {
13891 VarDecl *var = cast<VarDecl>(Val: 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() ||
13897 !var->getTypeSourceInfo()->getType().isConstQualified())) {
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;
13935 case Expr::MLV_ConstAddrSpace:
13936 DiagnoseConstAssignment(S, E, Loc);
13937 return true;
13938 case Expr::MLV_ConstQualifiedField:
13939 DiagnoseRecursiveConstFields(S, E, Loc);
13940 return true;
13941 case Expr::MLV_ArrayType:
13942 case Expr::MLV_ArrayTemporary:
13943 DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
13944 NeedType = true;
13945 break;
13946 case Expr::MLV_NotObjectType:
13947 DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
13948 NeedType = true;
13949 break;
13950 case Expr::MLV_LValueCast:
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");
13955 case Expr::MLV_InvalidExpression:
13956 case Expr::MLV_MemberFunction:
13957 case Expr::MLV_ClassTemporary:
13958 DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
13959 break;
13960 case Expr::MLV_IncompleteType:
13961 case Expr::MLV_IncompleteVoidType:
13962 return S.RequireCompleteType(Loc, E->getType(),
13963 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
13964 case Expr::MLV_DuplicateVectorComponents:
13965 DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
13966 break;
13967 case Expr::MLV_NoSetterProperty:
13968 llvm_unreachable("readonly properties should be processed differently");
13969 case Expr::MLV_InvalidMessageExpression:
13970 DiagID = diag::err_readonly_message_assignment;
13971 break;
13972 case Expr::MLV_SubObjCPropertySetting:
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) {
13990 if (Sema.inTemplateInstantiation())
13991 return;
13992 if (Sema.isUnevaluatedContext())
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>(Val: LHSExpr);
14001 MemberExpr *MR = dyn_cast<MemberExpr>(Val: RHSExpr);
14002 if (ML && MR) {
14003 if (!(isa<CXXThisExpr>(Val: ML->getBase()) && isa<CXXThisExpr>(Val: 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>(Val: LHSExpr);
14022 ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(Val: RHSExpr);
14023 if (OL && OR && OL->getDecl() == OR->getDecl()) {
14024 DeclRefExpr *RL = dyn_cast<DeclRefExpr>(Val: OL->getBase()->IgnoreImpCasts());
14025 DeclRefExpr *RR = dyn_cast<DeclRefExpr>(Val: 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
14032QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
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(E: LHSExpr, Loc, S&: *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(Ext: "cl_khr_fp16", LO: 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, RHSExpr: RHSCheck, Loc, Sema&: *this);
14067
14068 QualType LHSTy(LHSType);
14069 ConvTy = CheckSingleAssignmentConstraints(LHSType: LHSTy, CallerRHS&: 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(Ty: LHSType) &&
14075 RHSType->isObjCObjectPointerType()) ||
14076 (Context.isObjCNSObjectType(Ty: 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>(Val: RHSCheck))
14089 RHSCheck = ICE->getSubExpr();
14090 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: 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(Offset: 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(Offset: 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>(Val: InnerLHS);
14112 if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
14113 checkRetainCycles(receiver: LHSExpr, argument: RHS.get());
14114 }
14115
14116 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
14117 LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
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()))
14129 getCurFunction()->markSafeWeakUse(E: RHS.get());
14130
14131 } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
14132 checkUnsafeExprAssigns(Loc, LHS: LHSExpr, RHS: RHS.get());
14133 }
14134 }
14135 } else {
14136 // Compound assignment "x += y"
14137 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
14138 }
14139
14140 if (DiagnoseAssignmentResult(ConvTy, Loc, DstType: LHSType, SrcType: RHSType,
14141 SrcExpr: RHS.get(), Action: AA_Assigning))
14142 return QualType();
14143
14144 CheckForNullPointerDereference(S&: *this, E: 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(Elt: 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>(Val: 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>(Val: E))
14186 return CE->getCallReturnType(Ctx: 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.
14193void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
14194 // No warnings in macros
14195 if (Loc.isMacroID())
14196 return;
14197
14198 // Don't warn in template instantiations.
14199 if (inTemplateInstantiation())
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
14211 ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
14212 : Scope::ContinueScope | Scope::BreakScope;
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>(Val: 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(E: LHS, Context))
14229 return;
14230
14231 Diag(Loc, diag::warn_comma_operator);
14232 Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
14233 << LHS->getSourceRange()
14234 << FixItHint::CreateInsertion(LHS->getBeginLoc(),
14235 LangOpts.CPlusPlus ? "static_cast<void>("
14236 : "(void)(")
14237 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
14238 ")");
14239}
14240
14241// C99 6.5.17
14242static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
14243 SourceLocation Loc) {
14244 LHS = S.CheckPlaceholderExpr(E: LHS.get());
14245 RHS = S.CheckPlaceholderExpr(E: 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(E: 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) {
14262 RHS = S.DefaultFunctionArrayLvalueConversion(E: RHS.get());
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: 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.
14278static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
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, Loc: OpLoc, Operand: 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, Loc: OpLoc, Operand: Op) ||
14319 checkArithmeticOnObjCPointer(S, opLoc: OpLoc, op: 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()) {
14326 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
14327 if (PR.isInvalid()) return QualType();
14328 return CheckIncrementDecrementOperand(S, Op: 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() !=
14334 VectorKind::AltiVecBool)) {
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(E: Op, Loc: 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.
14383static ValueDecl *getPrimaryDecl(Expr *E) {
14384 switch (E->getStmtClass()) {
14385 case Stmt::DeclRefExprClass:
14386 return cast<DeclRefExpr>(Val: 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>(Val: E)->isArrow())
14392 return nullptr;
14393 // Otherwise, the expression refers to a part of the base
14394 return getPrimaryDecl(E: cast<MemberExpr>(Val: 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>(Val: E)->getBase();
14399 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Val: 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>(Val: E);
14407
14408 switch(UO->getOpcode()) {
14409 case UO_Real:
14410 case UO_Imag:
14411 case UO_Extension:
14412 return getPrimaryDecl(E: UO->getSubExpr());
14413 default:
14414 return nullptr;
14415 }
14416 }
14417 case Stmt::ParenExprClass:
14418 return getPrimaryDecl(E: cast<ParenExpr>(Val: 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>(Val: E)->getSubExpr());
14423 case Stmt::CXXUuidofExprClass:
14424 return cast<CXXUuidofExpr>(Val: 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.
14443static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
14444 Expr *E, unsigned Type) {
14445 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
14446}
14447
14448bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc,
14449 const Expr *Op,
14450 const CXXMethodDecl *MD) {
14451 const auto *DRE = cast<DeclRefExpr>(Val: 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.
14483QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
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>(Val: 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>(Val: E);
14495 if (isa<UnresolvedMemberExpr>(Val: Ovl))
14496 if (!ResolveSingleFunctionTemplateSpecialization(ovl: 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(E: 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>(Val: 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>(Val: 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(E: op);
14551
14552 if (auto *FD = dyn_cast_or_null<FunctionDecl>(Val: dcl))
14553 if (!checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true,
14554 Loc: op->getBeginLoc()))
14555 return QualType();
14556
14557 Expr::LValueClassification lval = op->ClassifyLValue(Ctx&: Context);
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(T: op->getType(), Temporary: OrigOp.get(), BoundToLvalueReference: true);
14570 } else if (isa<ObjCSelectorExpr>(Val: op)) {
14571 return Context.getPointerType(T: 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>(Val: op)) {
14578 Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
14579 << OrigOp.get()->getSourceRange();
14580 return QualType();
14581 }
14582 DeclRefExpr *DRE = cast<DeclRefExpr>(Val: op);
14583 CXXMethodDecl *MD = cast<CXXMethodDecl>(Val: DRE->getDecl());
14584
14585 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: OrigOp.get(), MD);
14586
14587 QualType MPTy = Context.getMemberPointerType(
14588 T: op->getType(), Cls: Context.getTypeDeclType(MD->getParent()).getTypePtr());
14589 // Under the MS ABI, lock down the inheritance model now.
14590 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14591 (void)isCompleteType(Loc: OpLoc, T: 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>(Val: 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>(Val: op)) {
14606 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Val: DRE->getDecl()))
14607 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc, Op: 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>(Val: 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 &&
14626 !getLangOpts().CPlusPlus) {
14627 AddressOfError = AO_Register_Variable;
14628 }
14629 } else if (isa<MSPropertyDecl>(Val: dcl)) {
14630 AddressOfError = AO_Property_Expansion;
14631 } else if (isa<FunctionTemplateDecl>(Val: dcl)) {
14632 return Context.OverloadTy;
14633 } else if (isa<FieldDecl>(Val: dcl) || isa<IndirectFieldDecl>(Val: 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>(Val: op) && cast<DeclRefExpr>(Val: 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>(Val: Ctx)->isAnonymousStructOrUnion())
14648 Ctx = Ctx->getParent();
14649
14650 QualType MPTy = Context.getMemberPointerType(
14651 T: op->getType(),
14652 Cls: Context.getTypeDeclType(cast<RecordDecl>(Val: Ctx)).getTypePtr());
14653 // Under the MS ABI, lock down the inheritance model now.
14654 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14655 (void)isCompleteType(Loc: OpLoc, T: MPTy);
14656 return MPTy;
14657 }
14658 }
14659 } else if (!isa<FunctionDecl, NonTypeTemplateParmDecl, BindingDecl,
14660 MSGuidDecl, UnnamedGlobalConstantDecl>(Val: dcl))
14661 llvm_unreachable("Unknown/unexpected decl type");
14662 }
14663
14664 if (AddressOfError != AO_No_Error) {
14665 diagnoseAddressOfInvalidType(S&: *this, Loc: OpLoc, E: op, Type: 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())
14678 return Context.getObjCObjectPointerType(OIT: op->getType());
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(rhs: op);
14696
14697 return Context.getPointerType(T: op->getType());
14698}
14699
14700static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
14701 const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Exp);
14702 if (!DRE)
14703 return;
14704 const Decl *D = DRE->getDecl();
14705 if (!D)
14706 return;
14707 const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: 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(Ptr: Param);
14715}
14716
14717/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14718static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
14719 SourceLocation OpLoc,
14720 bool IsAfterAmp = false) {
14721 if (Op->isTypeDependent())
14722 return S.Context.DependentTy;
14723
14724 ExprResult ConvResult = S.UsualUnaryConversions(E: Op);
14725 if (ConvResult.isInvalid())
14726 return QualType();
14727 Op = ConvResult.get();
14728 QualType OpTy = Op->getType();
14729 QualType Result;
14730
14731 if (isa<CXXReinterpretCastExpr>(Val: Op)) {
14732 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
14733 S.CheckCompatibleReinterpretCast(SrcType: OpOrigType, DestType: OpTy, /*IsDereference*/true,
14734 Range: Op->getSourceRange());
14735 }
14736
14737 if (const PointerType *PT = OpTy->getAs<PointerType>())
14738 {
14739 Result = PT->getPointeeType();
14740 }
14741 else if (const ObjCObjectPointerType *OPT =
14742 OpTy->getAs<ObjCObjectPointerType>())
14743 Result = OPT->getPointeeType();
14744 else {
14745 ExprResult PR = S.CheckPlaceholderExpr(E: Op);
14746 if (PR.isInvalid()) return QualType();
14747 if (PR.get() != Op)
14748 return CheckIndirectionOperand(S, Op: 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) {
14781 BinaryOperatorKind Opc;
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
14821static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
14822 tok::TokenKind Kind) {
14823 UnaryOperatorKind Opc;
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 *
14842Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned) {
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>(Val: SelfAssigned))
14853 return nullptr;
14854 const auto *Method =
14855 dyn_cast_or_null<CXXMethodDecl>(Val: getCurFunctionDecl(AllowLambda: 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) {
14879 if (S.inTemplateInstantiation())
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>(Val: LHSExpr);
14888 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(Val: 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 =
14910 S.getSelfAssignmentClassMemberCandidate(SelfAssigned: RHSDecl))
14911 Diag << 1 << SelfAssignField
14912 << FixItHint::CreateInsertion(InsertionLoc: LHSDeclRef->getBeginLoc(), Code: "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.
14919static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
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
14928 if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
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>(Val: 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>(Val: Ex)) {
14949 Selector S = ME->getSelector();
14950 StringRef SelArg0 = S.getNameForSlot(argIndex: 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
14960static NamedDecl *getDeclFromExpr(Expr *E) {
14961 if (!E)
14962 return nullptr;
14963 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E))
14964 return DRE->getDecl();
14965 if (auto *ME = dyn_cast<MemberExpr>(Val: E))
14966 return ME->getMemberDecl();
14967 if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(Val: 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.
14975static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
14976 BinaryOperatorKind Opc, QualType ResultTy,
14977 ExprValueKind VK, ExprObjectKind OK,
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(V: BinOpResTy);
14995
14996 if (IsCompAssign)
14997 return CompoundAssignOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
14998 ResTy: ResultTy, VK, OK, opLoc: OpLoc, FPFeatures,
14999 CompLHSType: BinOpResTy, CompResultType: BinOpResTy);
15000
15001 LHS = convertVector(LHS.get(), Context.FloatTy, S);
15002 auto *BO = BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc,
15003 ResTy: BinOpResTy, VK, OK, opLoc: OpLoc, FPFeatures);
15004 return convertVector(BO, ResultTy->castAs<VectorType>()->getElementType(), S);
15005}
15006
15007static std::pair<ExprResult, ExprResult>
15008CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
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(ER: LHS);
15016 RHS = S.CorrectDelayedTyposInExpr(
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(x&: LHS, y&: 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 ||
15034 Ctx.getTargetInfo().useFP16ConversionIntrinsics())
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.
15058ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
15059 BinaryOperatorKind Opc,
15060 Expr *LHSExpr, Expr *RHSExpr) {
15061 if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(Val: 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().
15068 InitializationKind Kind = InitializationKind::CreateDirectList(
15069 RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
15070 InitializedEntity Entity =
15071 InitializedEntity::InitializeTemporary(Type: LHSExpr->getType());
15072 InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
15073 ExprResult Init = InitSeq.Perform(S&: *this, Entity, Kind, Args: 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
15084 ExprValueKind VK = VK_PRValue;
15085 ExprObjectKind OK = OK_Ordinary;
15086 bool ConvertHalfVec = false;
15087
15088 std::tie(args&: LHS, args&: RHS) = CorrectDelayedTyposInBinOp(S&: *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(Loc: 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(Loc: OpLoc, LHS, RHS);
15113 return ExprError();
15114 }
15115 }
15116
15117 checkTypeSupport(Ty: LHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15118 checkTypeSupport(Ty: RHSExpr->getType(), Loc: OpLoc, /*ValueDecl*/ D: nullptr);
15119
15120 switch (Opc) {
15121 case BO_Assign:
15122 ResultTy = CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: 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(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15130 DiagnoseSelfMove(LHSExpr: LHS.get(), RHSExpr: 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>(Val: RHS.get()->IgnoreParens()))
15146 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: LHS.get()->IgnoreParens()))
15147 if (auto *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()))
15148 if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
15149 BE->getBlockDecl()->setCanAvoidCopyToHeap();
15150
15151 if (LHS.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15152 checkNonTrivialCUnion(QT: LHS.get()->getType(), Loc: LHS.get()->getExprLoc(),
15153 UseContext: NTCUC_Assignment, NonTrivialKind: NTCUK_Copy);
15154 }
15155 RecordModifiableNonNullParam(S&: *this, Exp: LHS.get());
15156 break;
15157 case BO_PtrMemD:
15158 case BO_PtrMemI:
15159 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
15160 isIndirect: Opc == BO_PtrMemI);
15161 break;
15162 case BO_Mul:
15163 case BO_Div:
15164 ConvertHalfVec = true;
15165 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: false,
15166 IsDiv: Opc == BO_Div);
15167 break;
15168 case BO_Rem:
15169 ResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc);
15170 break;
15171 case BO_Add:
15172 ConvertHalfVec = true;
15173 ResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc);
15174 break;
15175 case BO_Sub:
15176 ConvertHalfVec = true;
15177 ResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc);
15178 break;
15179 case BO_Shl:
15180 case BO_Shr:
15181 ResultTy = CheckShiftOperands(LHS, RHS, Loc: 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, Loc: OpLoc, Opc);
15189 break;
15190 case BO_EQ:
15191 case BO_NE:
15192 ConvertHalfVec = true;
15193 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15194 break;
15195 case BO_Cmp:
15196 ConvertHalfVec = true;
15197 ResultTy = CheckCompareOperands(LHS, RHS, Loc: OpLoc, Opc);
15198 assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
15199 break;
15200 case BO_And:
15201 checkObjCPointerIntrospection(S&: *this, L&: LHS, R&: RHS, OpLoc);
15202 [[fallthrough]];
15203 case BO_Xor:
15204 case BO_Or:
15205 ResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15206 break;
15207 case BO_LAnd:
15208 case BO_LOr:
15209 ConvertHalfVec = true;
15210 ResultTy = CheckLogicalOperands(LHS, RHS, Loc: OpLoc, Opc);
15211 break;
15212 case BO_MulAssign:
15213 case BO_DivAssign:
15214 ConvertHalfVec = true;
15215 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true,
15216 IsDiv: Opc == BO_DivAssign);
15217 CompLHSTy = CompResultTy;
15218 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15219 ResultTy =
15220 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15221 break;
15222 case BO_RemAssign:
15223 CompResultTy = CheckRemainderOperands(LHS, RHS, Loc: OpLoc, IsCompAssign: true);
15224 CompLHSTy = CompResultTy;
15225 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15226 ResultTy =
15227 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15228 break;
15229 case BO_AddAssign:
15230 ConvertHalfVec = true;
15231 CompResultTy = CheckAdditionOperands(LHS, RHS, Loc: OpLoc, Opc, CompLHSTy: &CompLHSTy);
15232 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15233 ResultTy =
15234 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15235 break;
15236 case BO_SubAssign:
15237 ConvertHalfVec = true;
15238 CompResultTy = CheckSubtractionOperands(LHS, RHS, Loc: OpLoc, CompLHSTy: &CompLHSTy);
15239 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15240 ResultTy =
15241 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15242 break;
15243 case BO_ShlAssign:
15244 case BO_ShrAssign:
15245 CompResultTy = CheckShiftOperands(LHS, RHS, Loc: OpLoc, Opc, IsCompAssign: true);
15246 CompLHSTy = CompResultTy;
15247 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15248 ResultTy =
15249 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15250 break;
15251 case BO_AndAssign:
15252 case BO_OrAssign: // fallthrough
15253 DiagnoseSelfAssignment(S&: *this, LHSExpr: LHS.get(), RHSExpr: RHS.get(), OpLoc, IsBuiltin: true);
15254 [[fallthrough]];
15255 case BO_XorAssign:
15256 CompResultTy = CheckBitwiseOperands(LHS, RHS, Loc: OpLoc, Opc);
15257 CompLHSTy = CompResultTy;
15258 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
15259 ResultTy =
15260 CheckAssignmentOperands(LHSExpr: LHS.get(), RHS, Loc: OpLoc, CompoundType: CompResultTy, Opc);
15261 break;
15262 case BO_Comma:
15263 ResultTy = CheckCommaOperands(S&: *this, LHS, RHS, Loc: 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(OpRequiresConversion: ConvertHalfVec, Ctx&: Context, E0: LHS.get(), E1: RHS.get());
15283
15284 // Check for array bounds violations for both sides of the BinaryOperator
15285 CheckArrayAccess(E: LHS.get());
15286 CheckArrayAccess(E: RHS.get());
15287
15288 if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(Val: LHS.get()->IgnoreParenCasts())) {
15289 NamedDecl *ObjectSetClass = LookupSingleName(S: TUScope,
15290 Name: &Context.Idents.get(Name: "object_setClass"),
15291 Loc: SourceLocation(), NameKind: LookupOrdinaryName);
15292 if (ObjectSetClass && isa<ObjCIsaExpr>(Val: LHS.get())) {
15293 SourceLocation RHSLocEnd = getLocForEndOfToken(Loc: RHS.get()->getEndLoc());
15294 Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
15295 << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
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>(Val: LHS.get()->IgnoreParenCasts()))
15306 DiagnoseDirectIsaAccess(S&: *this, OIRE, AssignLoc: OpLoc, RHS: RHS.get());
15307
15308 // Opc is not a compound assignment if CompResultTy is null.
15309 if (CompResultTy.isNull()) {
15310 if (ConvertHalfVec)
15311 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: false,
15312 OpLoc, FPFeatures: CurFPFeatureOverrides());
15313 return BinaryOperator::Create(C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy,
15314 VK, OK, opLoc: OpLoc, FPFeatures: CurFPFeatureOverrides());
15315 }
15316
15317 // Handle compound assignments.
15318 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
15319 OK_ObjCProperty) {
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(E: LHS.get()).get()->getType();
15329
15330 if (ConvertHalfVec)
15331 return convertHalfVecBinOp(S&: *this, LHS, RHS, Opc, ResultTy, VK, OK, IsCompAssign: true,
15332 OpLoc, FPFeatures: CurFPFeatureOverrides());
15333
15334 return CompoundAssignOperator::Create(
15335 C: Context, lhs: LHS.get(), rhs: RHS.get(), opc: Opc, ResTy: ResultTy, VK, OK, opLoc: OpLoc,
15336 FPFeatures: CurFPFeatureOverrides(), CompLHSType: CompLHSTy, CompResultType: 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".
15343static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
15344 SourceLocation OpLoc, Expr *LHSExpr,
15345 Expr *RHSExpr) {
15346 BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(Val: LHSExpr);
15347 BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(Val: 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)
15378 << BinaryOperator::getOpcodeStr(Opc),
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
15386EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
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;
15391 SuggestParentheses(Self, Bop->getOperatorLoc(),
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.
15398static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
15399 Expr *LHSExpr, Expr *RHSExpr) {
15400 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: 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>(Val: Bop->getLHS()->IgnoreParenImpCasts()))
15405 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop);
15406 } else if (Bop->getOpcode() == BO_LOr) {
15407 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Val: 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>(Val: RBop->getRHS()->IgnoreParenImpCasts()))
15412 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: S, OpLoc, Bop: RBop);
15413 }
15414 }
15415 }
15416}
15417
15418/// Look for '&&' in the right hand of a '||' expr.
15419static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
15420 Expr *LHSExpr, Expr *RHSExpr) {
15421 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: 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>(Val: Bop->getRHS()->IgnoreParenImpCasts()))
15426 return EmitDiagnosticForLogicalAndInLogicalOr(Self&: 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.
15434static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
15435 SourceLocation OpLoc, Expr *SubExpr) {
15436 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: 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
15449static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
15450 Expr *SubExpr, StringRef Shift) {
15451 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(Val: 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
15463static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
15464 Expr *LHSExpr, Expr *RHSExpr) {
15465 CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(Val: LHSExpr);
15466 if (!OCE)
15467 return;
15468
15469 FunctionDecl *FD = OCE->getDirectCallee();
15470 if (!FD || !FD->isOverloadedOperator())
15471 return;
15472
15473 OverloadedOperatorKind Kind = FD->getOverloadedOperator();
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);
15480 SuggestParentheses(S, OCE->getOperatorLoc(),
15481 S.PDiag(diag::note_precedence_silence)
15482 << (Kind == OO_LessLess ? "<<" : ">>"),
15483 OCE->getSourceRange());
15484 SuggestParentheses(
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.
15491static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
15492 SourceLocation OpLoc, Expr *LHSExpr,
15493 Expr *RHSExpr){
15494 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15495 if (BinaryOperator::isBitwiseOp(Opc))
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(S&: Self, Opc, OpLoc, SubExpr: LHSExpr);
15502 DiagnoseBitwiseOpInBitwiseOp(S&: Self, Opc, OpLoc, SubExpr: 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(S&: Self, OpLoc, LHSExpr, RHSExpr);
15509 DiagnoseLogicalAndInLogicalOrRHS(S&: Self, OpLoc, LHSExpr, RHSExpr);
15510 }
15511
15512 if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Ctx: Self.getASTContext()))
15513 || Opc == BO_Shr) {
15514 StringRef Shift = BinaryOperator::getOpcodeStr(Op: Opc);
15515 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: LHSExpr, Shift);
15516 DiagnoseAdditionInShift(S&: Self, OpLoc, SubExpr: RHSExpr, Shift);
15517 }
15518
15519 // Warn on overloaded shift operators and comparisons, such as:
15520 // cout << 5 == 4;
15521 if (BinaryOperator::isComparisonOp(Opc))
15522 DiagnoseShiftCompare(S&: Self, OpLoc, LHSExpr, RHSExpr);
15523}
15524
15525// Binary Operators. 'Tok' is the token for the operator.
15526ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
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(Self&: *this, Opc, OpLoc: TokLoc, LHSExpr, RHSExpr);
15535
15536 return BuildBinOp(S, OpLoc: TokLoc, Opc, LHSExpr, RHSExpr);
15537}
15538
15539void Sema::LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
15540 UnresolvedSetImpl &Functions) {
15541 OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
15542 if (OverOp != OO_None && OverOp != OO_Equal)
15543 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
15544
15545 // In C++20 onwards, we may have a second operator to look up.
15546 if (getLangOpts().CPlusPlus20) {
15547 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: OverOp))
15548 LookupOverloadedOperatorName(Op: ExtraOp, S, Functions);
15549 }
15550}
15551
15552/// Build an overloaded binary operator expression in the given scope.
15553static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
15554 BinaryOperatorKind Opc,
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, LHSExpr: LHS, RHSExpr: RHS, OpLoc, IsBuiltin: 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(LHSExpr: LHS, RHSExpr: RHS, Loc: OpLoc, Sema&: 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(S: Sc, OpLoc, Opc, Functions);
15583
15584 // Build the (potentially-overloaded, potentially-dependent)
15585 // binary operation.
15586 return S.CreateOverloadedBinOp(OpLoc, Opc, Fns: Functions, LHS, RHS);
15587}
15588
15589ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
15590 BinaryOperatorKind Opc,
15591 Expr *LHSExpr, Expr *RHSExpr) {
15592 ExprResult LHS, RHS;
15593 std::tie(args&: LHS, args&: RHS) = CorrectDelayedTyposInBinOp(S&: *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 &&
15609 BinaryOperator::isAssignmentOp(Opc))
15610 return checkPseudoObjectAssignment(S, OpLoc, Opcode: Opc, LHS: LHSExpr, RHS: 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(E: RHSExpr);
15620 if (resolvedRHS.isInvalid()) return ExprError();
15621 RHSExpr = resolvedRHS.get();
15622
15623 if (RHSExpr->isTypeDependent() ||
15624 RHSExpr->getType()->isOverloadableType())
15625 return BuildOverloadedBinOp(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: 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>(Val: LHSExpr);
15638 if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
15639 llvm::any_of(Range: OE->decls(), P: [](NamedDecl *ND) {
15640 return isa<FunctionTemplateDecl>(Val: 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(E: 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(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: 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(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: RHSExpr);
15672
15673 ExprResult resolvedRHS = CheckPlaceholderExpr(E: 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(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: 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(S&: *this, Sc: S, OpLoc, Opc, LHS: LHSExpr, RHS: 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.");
15696 if (BinaryOperator::isCompoundAssignmentOp(Opc))
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.
15700 return CompoundAssignOperator::Create(
15701 C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc,
15702 ResTy: LHSExpr->getType().getUnqualifiedType(), VK: VK_PRValue, OK: OK_Ordinary,
15703 opLoc: OpLoc, FPFeatures: 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(C: Context, lhs: LHSExpr, rhs: RHSExpr, opc: Opc, ResTy: ResultType,
15728 VK: VK_PRValue, OK: OK_Ordinary, opLoc: OpLoc,
15729 FPFeatures: CurFPFeatureOverrides());
15730 }
15731
15732 // Build a built-in binary operation.
15733 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
15734}
15735
15736static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
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(T: Ctx.IntTy);
15744}
15745
15746ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
15747 UnaryOperatorKind Opc, Expr *InputExpr,
15748 bool IsAfterAmp) {
15749 ExprResult Input = InputExpr;
15750 ExprValueKind VK = VK_PRValue;
15751 ExprObjectKind OK = OK_Ordinary;
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(S&: *this, Op: Input.get(), VK, OK,
15783 OpLoc,
15784 IsInc: Opc == UO_PreInc ||
15785 Opc == UO_PostInc,
15786 IsPrefix: Opc == UO_PreInc ||
15787 Opc == UO_PreDec);
15788 CanOverflow = isOverflowingIntegerType(Ctx&: Context, T: resultType);
15789 break;
15790 case UO_AddrOf:
15791 resultType = CheckAddressOfOperand(OrigOp&: Input, OpLoc);
15792 CheckAddressOfNoDeref(E: InputExpr);
15793 RecordModifiableNonNullParam(S&: *this, Exp: InputExpr);
15794 break;
15795 case UO_Deref: {
15796 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
15797 if (Input.isInvalid()) return ExprError();
15798 resultType =
15799 CheckIndirectionOperand(S&: *this, Op: Input.get(), VK, OpLoc, IsAfterAmp);
15800 break;
15801 }
15802 case UO_Plus:
15803 case UO_Minus:
15804 CanOverflow = Opc == UO_Minus &&
15805 isOverflowingIntegerType(Ctx&: Context, T: Input.get()->getType());
15806 Input = UsualUnaryConversions(E: 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(OpRequiresConversion: true, Ctx&: Context, E0: 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() !=
15826 VectorKind::AltiVecBool))
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(E: 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).
15867 Input = DefaultFunctionArrayLvalueConversion(E: Input.get());
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(E: Input.get(), Type: Context.FloatTy, CK: CK_FloatingCast).get();
15874 resultType = Context.FloatTy;
15875 }
15876
15877 // WebAsembly tables can't be used in unary expressions.
15878 if (resultType->isPointerType() &&
15879 resultType->getPointeeType().isWebAssemblyReferenceType()) {
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(T: 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(E: Input.get(), Type: Context.BoolTy,
15892 CK: ScalarTypeToBooleanCastKind(ScalarTy: 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 &&
15903 Context.getLangOpts().getOpenCLCompatibleVersion() < 120) {
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(V: 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(V: 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(S&: *this, V&: Input, Loc: OpLoc, IsReal: 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(E: 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(E: Input.get());
15969
15970 auto *UO =
15971 UnaryOperator::Create(C: Context, input: Input.get(), opc: Opc, type: resultType, VK, OK,
15972 l: OpLoc, CanOverflow, FPFeatures: CurFPFeatureOverrides());
15973
15974 if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
15975 !isa<ArrayType>(UO->getType().getDesugaredType(Context)) &&
15976 !isUnevaluatedContext())
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.
15988bool Sema::isQualifiedMemberAccess(Expr *E) {
15989 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: 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>(Val: VD) || isa<IndirectFieldDecl>(Val: VD))
15998 return true;
15999 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: VD))
16000 return Method->isImplicitObjectMemberFunction();
16001
16002 return false;
16003 }
16004
16005 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Val: 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
16025ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
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 &&
16033 UnaryOperator::isIncrementDecrementOp(Op: Opc))
16034 return checkPseudoObjectIncDec(S, OpLoc, Opcode: Opc, Op: Input);
16035
16036 // extension is always a builtin operator.
16037 if (Opc == UO_Extension)
16038 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: 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, InputExpr: Input);
16047
16048 // Anything else needs to be handled now.
16049 ExprResult Result = CheckPlaceholderExpr(E: Input);
16050 if (Result.isInvalid()) return ExprError();
16051 Input = Result.get();
16052 }
16053
16054 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
16055 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
16056 !(Opc == UO_AddrOf && isQualifiedMemberAccess(E: Input))) {
16057 // Find all of the overloaded operators visible from this point.
16058 UnresolvedSet<16> Functions;
16059 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
16060 if (S && OverOp != OO_None)
16061 LookupOverloadedOperatorName(Op: OverOp, S, Functions);
16062
16063 return CreateOverloadedUnaryOp(OpLoc, Opc, Fns: Functions, input: Input);
16064 }
16065
16066 return CreateBuiltinUnaryOp(OpLoc, Opc, InputExpr: Input, IsAfterAmp);
16067}
16068
16069// Unary Operators. 'Tok' is the token for the operator.
16070ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op,
16071 Expr *Input, bool IsAfterAmp) {
16072 return BuildUnaryOp(S, OpLoc, Opc: ConvertTokenKindToUnaryOpcode(Kind: Op), Input,
16073 IsAfterAmp);
16074}
16075
16076/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
16077ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
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(Elt: Res);
16086
16087 return Res;
16088}
16089
16090void Sema::ActOnStartStmtExpr() {
16091 PushExpressionEvaluationContext(NewContext: ExprEvalContexts.back().Context);
16092 // Make sure we diagnose jumping into a statement expression.
16093 setFunctionHasBranchProtectedScope();
16094}
16095
16096void Sema::ActOnStmtExprError() {
16097 // Note that function is also called by TreeTransform when leaving a
16098 // StmtExpr scope without rebuilding anything.
16099
16100 DiscardCleanupsInEvaluationContext();
16101 PopExpressionEvaluationContext();
16102}
16103
16104ExprResult Sema::ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
16105 SourceLocation RPLoc) {
16106 return BuildStmtExpr(LPLoc, SubStmt, RPLoc, TemplateDepth: getTemplateDepth(S));
16107}
16108
16109ExprResult Sema::BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
16110 SourceLocation RPLoc, unsigned TemplateDepth) {
16111 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
16112 CompoundStmt *Compound = cast<CompoundStmt>(Val: SubStmt);
16113
16114 if (hasAnyUnrecoverableErrorsInThisFunction())
16115 DiscardCleanupsInEvaluationContext();
16116 assert(!Cleanup.exprNeedsCleanups() &&
16117 "cleanups within StmtExpr not correctly bound!");
16118 PopExpressionEvaluationContext();
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>(Val: 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(E: ResStmtExpr);
16145 return ResStmtExpr;
16146}
16147
16148ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
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.
16154 ER = DefaultFunctionArrayConversion(E: ER.get());
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>(Val: E);
16169 if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
16170 return Cast->getSubExpr();
16171
16172 // FIXME: Provide a better location for the initialization.
16173 return PerformCopyInitialization(
16174 Entity: InitializedEntity::InitializeStmtExprResult(
16175 ReturnLoc: E->getBeginLoc(), Type: E->getType().getUnqualifiedType()),
16176 EqualLoc: SourceLocation(), Init: E);
16177}
16178
16179ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
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;
16203 SmallVector<OffsetOfNode, 4> Comps;
16204 SmallVector<Expr*, 4> Exprs;
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(T: 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(E: 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(Elt: OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
16232 Exprs.push_back(Elt: 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(Elt: 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>(Val: 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(Loc: OC.LocStart, Derived: CurrentType, Base: 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(Elt: OffsetOfNode(B.Base));
16328 }
16329
16330 if (IndirectMemberDecl) {
16331 for (auto *FI : IndirectMemberDecl->chain()) {
16332 assert(isa<FieldDecl>(FI));
16333 Comps.push_back(Elt: OffsetOfNode(OC.LocStart,
16334 cast<FieldDecl>(Val: FI), OC.LocEnd));
16335 }
16336 } else
16337 Comps.push_back(Elt: OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
16338
16339 CurrentType = MemberDecl->getType().getNonReferenceType();
16340 }
16341
16342 return OffsetOfExpr::Create(C: Context, type: Context.getSizeType(), OperatorLoc: BuiltinLoc, tsi: TInfo,
16343 comps: Comps, exprs: Exprs, RParenLoc);
16344}
16345
16346ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
16347 SourceLocation BuiltinLoc,
16348 SourceLocation TypeLoc,
16349 ParsedType ParsedArgTy,
16350 ArrayRef<OffsetOfComponent> Components,
16351 SourceLocation RParenLoc) {
16352
16353 TypeSourceInfo *ArgTInfo;
16354 QualType ArgTy = GetTypeFromParser(Ty: ParsedArgTy, TInfo: &ArgTInfo);
16355 if (ArgTy.isNull())
16356 return ExprError();
16357
16358 if (!ArgTInfo)
16359 ArgTInfo = Context.getTrivialTypeSourceInfo(T: ArgTy, Loc: TypeLoc);
16360
16361 return BuildBuiltinOffsetOf(BuiltinLoc, TInfo: ArgTInfo, Components, RParenLoc);
16362}
16363
16364
16365ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
16366 Expr *CondExpr,
16367 Expr *LHSExpr, Expr *RHSExpr,
16368 SourceLocation RPLoc) {
16369 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
16370
16371 ExprValueKind VK = VK_PRValue;
16372 ExprObjectKind OK = OK_Ordinary;
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);
16380 ExprResult CondICE = VerifyIntegerConstantExpression(
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) {
16405 BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: CaretLoc);
16406
16407 if (LangOpts.CPlusPlus) {
16408 MangleNumberingContext *MCtx;
16409 Decl *ManglingContextDecl;
16410 std::tie(args&: MCtx, args&: ManglingContextDecl) =
16411 getCurrentMangleNumberContext(DC: Block->getDeclContext());
16412 if (MCtx) {
16413 unsigned ManglingNumber = MCtx->getManglingNumber(BD: Block);
16414 Block->setBlockMangling(Number: ManglingNumber, Ctx: ManglingContextDecl);
16415 }
16416 }
16417
16418 PushBlockScope(BlockScope: CurScope, Block);
16419 CurContext->addDecl(Block);
16420 if (CurScope)
16421 PushDeclContext(CurScope, Block);
16422 else
16423 CurContext = Block;
16424
16425 getCurBlock()->HasImplicitReturnType = true;
16426
16427 // Enter a new evaluation context to insulate the block from any
16428 // cleanups from the enclosing full-expression.
16429 PushExpressionEvaluationContext(
16430 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated);
16431}
16432
16433void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
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(D&: 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(Loc: CaretLoc, T: Sig, UPPC: UPPC_Block)) {
16446 // Drop the parameters.
16447 FunctionProtoType::ExtProtoInfo EPI;
16448 EPI.HasTrailingReturn = false;
16449 EPI.TypeQuals.addConst();
16450 T = Context.getFunctionType(ResultTy: Context.DependentTy, Args: std::nullopt, EPI);
16451 Sig = Context.getTrivialTypeSourceInfo(T);
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()
16464 .getAsAdjusted<FunctionProtoTypeLoc>())) {
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(T: Result.getType(), Size);
16476 Sig->getTypeLoc().initializeFullCopy(Other: 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>(Val: Fn) && cast<FunctionProtoType>(Val: 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.
16503 SmallVector<ParmVarDecl*, 8> Params;
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(Elt: 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()) {
16520 ParmVarDecl *Param = BuildParmVarDeclForTypedef(
16521 CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
16522 Params.push_back(Elt: Param);
16523 }
16524 }
16525
16526 // Set the parameters on the block decl.
16527 if (!Params.empty()) {
16528 CurBlock->TheDecl->setParams(Params);
16529 CheckParmsForFunctionDef(Parameters: CurBlock->TheDecl->parameters(),
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.
16556 DiscardCleanupsInEvaluationContext();
16557 PopExpressionEvaluationContext();
16558
16559 // Pop off CurBlock, handle nested blocks.
16560 PopDeclContext();
16561 PopFunctionScopeInfo();
16562}
16563
16564/// ActOnBlockStmtExpr - This is called when the body of a block statement
16565/// literal was successfully completed. ^(int x){...}
16566ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
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.
16573 if (hasAnyUnrecoverableErrorsInThisFunction())
16574 DiscardCleanupsInEvaluationContext();
16575 assert(!Cleanup.exprNeedsCleanups() &&
16576 "cleanups within block not correctly bound!");
16577 PopExpressionEvaluationContext();
16578
16579 BlockScopeInfo *BSI = cast<BlockScopeInfo>(Val: FunctionScopes.back());
16580 BlockDecl *BD = BSI->TheDecl;
16581
16582 if (BSI->HasImplicitReturnType)
16583 deduceClosureReturnType(*BSI);
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(noReturn: true);
16598
16599 // Turn protoless block types into nullary block types.
16600 if (isa<FunctionNoProtoType>(Val: FTy)) {
16601 FunctionProtoType::ExtProtoInfo EPI;
16602 EPI.ExtInfo = Ext;
16603 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: 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>(Val: FTy);
16614 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
16615 EPI.TypeQuals = Qualifiers();
16616 EPI.ExtInfo = Ext;
16617 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: FPT->getParamTypes(), EPI);
16618 }
16619
16620 // If we don't have a function type, just build one from nothing.
16621 } else {
16622 FunctionProtoType::ExtProtoInfo EPI;
16623 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(noReturn: NoReturn);
16624 BlockTy = Context.getFunctionType(ResultTy: RetTy, Args: std::nullopt, EPI);
16625 }
16626
16627 DiagnoseUnusedParameters(Parameters: BD->parameters());
16628 BlockTy = Context.getBlockPointerType(T: BlockTy);
16629
16630 // If needed, diagnose invalid gotos and switches in the block.
16631 if (getCurFunction()->NeedsScopeChecking() &&
16632 !PP.isCodeCompletionEnabled())
16633 DiagnoseInvalidJumps(cast<CompoundStmt>(Val: Body));
16634
16635 BD->setBody(cast<CompoundStmt>(Val: Body));
16636
16637 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
16638 DiagnoseUnguardedAvailabilityViolations(BD);
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
16647 if (RetTy.hasNonTrivialToPrimitiveDestructCUnion() ||
16648 RetTy.hasNonTrivialToPrimitiveCopyCUnion())
16649 checkNonTrivialCUnion(QT: RetTy, Loc: BD->getCaretLocation(), UseContext: NTCUC_FunctionReturn,
16650 NonTrivialKind: NTCUK_Destruct|NTCUK_Copy);
16651
16652 PopDeclContext();
16653
16654 // Set the captured variables on the block.
16655 SmallVector<BlockDecl::Capture, 4> Captures;
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>(Val: 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>(Val: Var))
16672 FinalizeVarWithDestructor(VD: Var, DeclInitType: Record);
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?
16679 EnterExpressionEvaluationContext EvalContext(
16680 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16681
16682 SourceLocation Loc = Cap.getLocation();
16683
16684 ExprResult Result = BuildDeclarationNameExpr(
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()) {
16692 Result = ImpCastExprToType(E: Result.get(),
16693 Type: Result.get()->getType().withConst(),
16694 CK: CK_NoOp, VK: VK_LValue);
16695 }
16696
16697 if (!Result.isInvalid()) {
16698 Result = PerformCopyInitialization(
16699 Entity: InitializedEntity::InitializeBlock(BlockVarLoc: Var->getLocation(),
16700 Type: Cap.getCaptureType()),
16701 EqualLoc: Loc, Init: 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>(Val: Result.get())->getConstructor()
16709 ->isTrivial()) {
16710 Result = MaybeCreateExprWithCleanups(SubExpr: Result);
16711 CopyExpr = Result.get();
16712 }
16713 }
16714 }
16715
16716 BlockDecl::Capture NewCap(Var, Cap.isBlockCapture(), Cap.isNested(),
16717 CopyExpr);
16718 Captures.push_back(Elt: NewCap);
16719 }
16720 BD->setCaptures(Context, Captures, CapturesCXXThis: BSI->CXXThisCaptureIndex != 0);
16721
16722 // Pop the block scope now but keep it alive to the end of this function.
16723 AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
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(Elt: Result->getBlockDecl());
16733 Cleanup.setExprNeedsCleanups(true);
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) {
16740 setFunctionHasBranchProtectedScope();
16741 break;
16742 }
16743 }
16744 }
16745
16746 if (getCurFunction())
16747 getCurFunction()->addBlock(BD);
16748
16749 if (BD->isInvalidDecl())
16750 return CreateRecoveryExpr(Begin: Result->getBeginLoc(), End: Result->getEndLoc(),
16751 SubExprs: {Result}, T: Result->getType());
16752 return Result;
16753}
16754
16755ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
16756 SourceLocation RPLoc) {
16757 TypeSourceInfo *TInfo;
16758 GetTypeFromParser(Ty, TInfo: &TInfo);
16759 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
16760}
16761
16762ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
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>(Val: CurContext)) {
16771 CUDAFunctionTarget T = CUDA().IdentifyTarget(D: F);
16772 if (T == CUDAFunctionTarget::Global || T == CUDAFunctionTarget::Device ||
16773 T == CUDAFunctionTarget::HostDevice)
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.)
16786 if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
16787 Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
16788 QualType MSVaListType = Context.getBuiltinMSVaListType();
16789 if (Context.hasSameType(T1: MSVaListType, T2: E->getType())) {
16790 if (CheckForModifiableLvalue(E, Loc: BuiltinLoc, S&: *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(T: VaListType);
16804 // Make sure the input expression also decays appropriately.
16805 ExprResult Result = UsualUnaryConversions(E);
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.
16812 InitializedEntity Entity = InitializedEntity::InitializeParameter(
16813 Context, Type: Context.getLValueReferenceType(T: VaListType), Consumed: false);
16814 ExprResult Init = PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: E);
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, Loc: BuiltinLoc, S&: *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
16840 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
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(T: TInfo->getType())) {
16859 PromoteType = Context.getPromotedIntegerType(PromotableType: 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(T1: PromoteType, T2: 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(T: UnderlyingType)
16898 : Context.getCorrespondingUnsignedType(T: UnderlyingType);
16899 if (Context.typesAreCompatible(T1: PromoteType, T2: UnderlyingType,
16900 /*CompareUnqualified*/ true))
16901 PromoteType = QualType();
16902 }
16903 }
16904 if (TInfo->getType()->isSpecificBuiltinType(K: BuiltinType::Float))
16905 PromoteType = Context.DoubleTy;
16906 if (!PromoteType.isNull())
16907 DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
16908 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
16909 << TInfo->getType()
16910 << PromoteType
16911 << TInfo->getTypeLoc().getSourceRange());
16912 }
16913
16914 QualType T = TInfo->getType().getNonLValueExprType(Context);
16915 return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
16916}
16917
16918ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
16919 // The type of __null will be int or long, depending on the size of
16920 // pointers on the target.
16921 QualType Ty;
16922 unsigned pw = Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default);
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
16936static CXXRecordDecl *LookupStdSourceLocationImpl(Sema &S, SourceLocation Loc) {
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(Name: "source_location"),
16942 Loc, Sema::LookupOrdinaryName);
16943 if (S.LookupQualifiedName(ResultSL, Std)) {
16944 if (auto *SLDecl = ResultSL.getAsSingle<RecordDecl>()) {
16945 LookupResult ResultImpl(S, &S.PP.getIdentifierTable().get(Name: "__impl"),
16946 Loc, Sema::LookupOrdinaryName);
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() !=
16974 S.Context.getPointerType(S.Context.CharTy.withConst()))
16975 break;
16976 Count++;
16977 } else if (Name == "_M_function_name") {
16978 if (F->getType() !=
16979 S.Context.getPointerType(S.Context.CharTy.withConst()))
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
17003ExprResult Sema::ActOnSourceLocExpr(SourceLocIdentKind Kind,
17004 SourceLocation BuiltinLoc,
17005 SourceLocation RPLoc) {
17006 QualType ResultTy;
17007 switch (Kind) {
17008 case SourceLocIdentKind::File:
17009 case SourceLocIdentKind::FileName:
17010 case SourceLocIdentKind::Function:
17011 case SourceLocIdentKind::FuncSig: {
17012 QualType ArrTy = Context.getStringLiteralArrayType(EltTy: Context.CharTy, Length: 0);
17013 ResultTy =
17014 Context.getPointerType(ArrTy->getAsArrayTypeUnsafe()->getElementType());
17015 break;
17016 }
17017 case SourceLocIdentKind::Line:
17018 case SourceLocIdentKind::Column:
17019 ResultTy = Context.UnsignedIntTy;
17020 break;
17021 case SourceLocIdentKind::SourceLocStruct:
17022 if (!StdSourceLocationImplDecl) {
17023 StdSourceLocationImplDecl =
17024 LookupStdSourceLocationImpl(S&: *this, Loc: BuiltinLoc);
17025 if (!StdSourceLocationImplDecl)
17026 return ExprError();
17027 }
17028 ResultTy = Context.getPointerType(
17029 T: Context.getRecordType(Decl: StdSourceLocationImplDecl).withConst());
17030 break;
17031 }
17032
17033 return BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext: CurContext);
17034}
17035
17036ExprResult Sema::BuildSourceLocExpr(SourceLocIdentKind Kind, QualType ResultTy,
17037 SourceLocation BuiltinLoc,
17038 SourceLocation RPLoc,
17039 DeclContext *ParentContext) {
17040 return new (Context)
17041 SourceLocExpr(Context, Kind, ResultTy, BuiltinLoc, RPLoc, ParentContext);
17042}
17043
17044bool Sema::CheckConversionToObjCLiteral(QualType DstType, Expr *&Exp,
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>(Val: SrcExpr))
17059 if (OV->getSourceExpr())
17060 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
17061
17062 if (auto *SL = dyn_cast<StringLiteral>(Val: 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(AtLoc: SL->getBeginLoc(), S: SL).get();
17073 }
17074 return true;
17075 }
17076
17077 if ((isa<IntegerLiteral>(Val: SrcExpr) || isa<CharacterLiteral>(Val: SrcExpr) ||
17078 isa<FloatingLiteral>(Val: SrcExpr) || isa<ObjCBoolLiteralExpr>(Val: SrcExpr) ||
17079 isa<CXXBoolLiteralExpr>(Val: SrcExpr)) &&
17080 !SrcExpr->isNullPointerConstant(
17081 Ctx&: getASTContext(), NPC: Expr::NPC_NeverValueDependent)) {
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(AtLoc: SrcExpr->getBeginLoc(), Number: SrcExpr).get();
17090 if (NumLit)
17091 Exp = NumLit;
17092 }
17093 return true;
17094 }
17095
17096 return false;
17097}
17098
17099static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
17100 const Expr *SrcExpr) {
17101 if (!DstType->isFunctionPointerType() ||
17102 !SrcExpr->getType()->isFunctionType())
17103 return false;
17104
17105 auto *DRE = dyn_cast<DeclRefExpr>(Val: SrcExpr->IgnoreParenImpCasts());
17106 if (!DRE)
17107 return false;
17108
17109 auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl());
17110 if (!FD)
17111 return false;
17112
17113 return !S.checkAddressOfFunctionIsAvailable(Function: FD,
17114 /*Complain=*/true,
17115 Loc: SrcExpr->getBeginLoc());
17116}
17117
17118bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
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(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *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(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17159 MayHaveConvFixit = true;
17160 break;
17161 case IncompatibleFunctionPointerStrict:
17162 DiagKind =
17163 diag::warn_typecheck_convert_incompatible_function_pointer_strict;
17164 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17165 MayHaveConvFixit = true;
17166 break;
17167 case IncompatibleFunctionPointer:
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(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17175 MayHaveConvFixit = true;
17176 break;
17177 case IncompatiblePointer:
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(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *this);
17190 } else if (CheckInferredResultType) {
17191 SrcType = SrcType.getUnqualifiedType();
17192 DstType = DstType.getUnqualifiedType();
17193 }
17194 MayHaveConvFixit = true;
17195 break;
17196 case IncompatiblePointerSign:
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;
17204 case FunctionVoidPointer:
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;
17212 case IncompatiblePointerDiscardsQualifiers: {
17213 // Perform array-to-pointer decay if necessary.
17214 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(T: 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 }
17231 case CompatiblePointerDiscardsQualifiers:
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 &&
17242 IsStringLiteralToNonConstPointerConversion(From: SrcExpr, ToType: DstType))
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;
17252 case IncompatibleNestedPointerQualifiers:
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;
17260 case IncompatibleNestedPointerAddressSpaceMismatch:
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;
17268 case IncompatibleBlockPointer:
17269 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
17270 isInvalid = true;
17271 break;
17272 case IncompatibleObjCQualifiedId: {
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 =
17281 DstType->castAs<ObjCObjectPointerType>()->getInterfaceType())
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 =
17292 SrcType->castAs<ObjCObjectPointerType>()->getInterfaceType())
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 }
17303 case IncompatibleVectors:
17304 if (getLangOpts().CPlusPlus) {
17305 DiagKind = diag::err_incompatible_vectors;
17306 isInvalid = true;
17307 } else {
17308 DiagKind = diag::warn_incompatible_vectors;
17309 }
17310 break;
17311 case IncompatibleObjCWeakRef:
17312 DiagKind = diag::err_arc_weak_unavailable_assign;
17313 isInvalid = true;
17314 break;
17315 case Incompatible:
17316 if (maybeDiagnoseAssignmentToFunction(S&: *this, DstType, SrcExpr)) {
17317 if (Complained)
17318 *Complained = true;
17319 return true;
17320 }
17321
17322 DiagKind = diag::err_typecheck_convert_incompatible;
17323 ConvHints.tryToFixConversion(FromExpr: SrcExpr, FromQTy: SrcType, ToQTy: DstType, S&: *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:
17341 case AA_Passing_CFAudited:
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(DiagID: 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(K: BuiltinType::Char_S) ||
17363 Type->isSpecificBuiltinType(K: 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(PDiag&: FDiag, FromType: SecondType, ToType: 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)
17388 NoteAllOverloadCandidates(OverloadExpr::find(E: SrcExpr).Expression,
17389 FirstType, /*TakingAddress=*/true);
17390
17391 if (CheckInferredResultType)
17392 EmitRelatedResultTypeNote(E: SrcExpr);
17393
17394 if (Action == AA_Returning && ConvTy == IncompatiblePointer)
17395 EmitRelatedResultTypeNoteForReturn(destType: DstType);
17396
17397 if (Complained)
17398 *Complained = true;
17399 return isInvalid;
17400}
17401
17402ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
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
17420ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
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
17439Sema::SemaDiagnosticBuilder
17440Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema &S, SourceLocation Loc,
17441 QualType T) {
17442 return diagnoseNotICE(S, Loc);
17443}
17444
17445Sema::SemaDiagnosticBuilder
17446Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc) {
17447 return S.Diag(Loc, diag::ext_expr_not_ice) << S.LangOpts.CPlusPlus;
17448}
17449
17450ExprResult
17451Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
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(Loc: DiagLoc, FromE: E,
17510 Converter&: 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>(Val: E))
17519 return ExprError();
17520 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
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(S&: *this, Loc: DiagLoc, T: 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.
17538 if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Ctx: Context)) {
17539 if (Result)
17540 *Result = E->EvaluateKnownConstIntCheckOverflow(Ctx: Context);
17541 if (!isa<ConstantExpr>(Val: E))
17542 E = Result ? ConstantExpr::Create(Context, E, Result: APValue(*Result))
17543 : ConstantExpr::Create(Context, E);
17544 return E;
17545 }
17546
17547 Expr::EvalResult EvalResult;
17548 SmallVector<PartialDiagnosticAt, 8> Notes;
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(Result&: EvalResult, Ctx: Context, /*isConstantContext*/ InConstantContext: true) &&
17555 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
17556
17557 if (!isa<ConstantExpr>(Val: E))
17558 E = ConstantExpr::Create(Context, E, Result: 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(S&: *this, Loc: 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(S&: *this, Loc: 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
17645ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
17646 assert(isUnevaluatedContext() &&
17647 "Should only transform unevaluated expressions");
17648 ExprEvalContexts.back().Context =
17649 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
17650 if (isUnevaluatedContext())
17651 return E;
17652 return TransformToPE(*this).TransformExpr(E);
17653}
17654
17655TypeSourceInfo *Sema::TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo) {
17656 assert(isUnevaluatedContext() &&
17657 "Should only transform unevaluated expressions");
17658 ExprEvalContexts.back().Context =
17659 ExprEvalContexts[ExprEvalContexts.size() - 2].Context;
17660 if (isUnevaluatedContext())
17661 return TInfo;
17662 return TransformToPE(*this).TransformType(TInfo);
17663}
17664
17665void
17666Sema::PushExpressionEvaluationContext(
17667 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
17668 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17669 ExprEvalContexts.emplace_back(Args&: NewContext, Args: ExprCleanupObjects.size(), Args&: Cleanup,
17670 Args&: LambdaContextDecl, Args&: 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 =
17676 ExprEvalContexts[ExprEvalContexts.size() - 2]
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(LHS&: MaybeODRUseExprs, RHS&: ExprEvalContexts.back().SavedMaybeODRUseExprs);
17693}
17694
17695void
17696Sema::PushExpressionEvaluationContext(
17697 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
17698 ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
17699 Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
17700 PushExpressionEvaluationContext(NewContext, LambdaContextDecl: 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>(Val: PossibleDeref)) {
17708 if (E->getOpcode() == UO_Deref)
17709 return CheckPossibleDeref(S, PossibleDeref: E->getSubExpr());
17710 } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(Val: PossibleDeref)) {
17711 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
17712 } else if (const auto *E = dyn_cast<MemberExpr>(Val: PossibleDeref)) {
17713 return CheckPossibleDeref(S, PossibleDeref: E->getBase());
17714 } else if (const auto E = dyn_cast<DeclRefExpr>(Val: 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
17732void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
17733 for (const Expr *E : Rec.PossibleDerefs) {
17734 const DeclRefExpr *DeclRef = CheckPossibleDeref(S&: *this, PossibleDeref: 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.
17752void Sema::CheckUnusedVolatileAssignment(Expr *E) {
17753 if (!E->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20)
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>(Val: E->IgnoreParenImpCasts())) {
17760 if (BO->getOpcode() == BO_Assign) {
17761 auto &LHSs = ExprEvalContexts.back().VolatileAssignmentLHSs;
17762 llvm::erase(C&: LHSs, V: BO->getLHS());
17763 }
17764 }
17765}
17766
17767void Sema::MarkExpressionAsImmediateEscalating(Expr *E) {
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>(Val: E->IgnoreImplicit());
17773 Call && Call->getCallee()) {
17774 if (auto *DeclRef =
17775 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
17776 DeclRef->setIsImmediateEscalating(true);
17777 } else if (auto *Ctr = dyn_cast<CXXConstructExpr>(Val: E->IgnoreImplicit())) {
17778 Ctr->setIsImmediateEscalating(true);
17779 } else if (auto *DeclRef = dyn_cast<DeclRefExpr>(Val: E->IgnoreImplicit())) {
17780 DeclRef->setIsImmediateEscalating(true);
17781 } else {
17782 assert(false && "expected an immediately escalating expression");
17783 }
17784 if (FunctionScopeInfo *FI = getCurFunction())
17785 FI->FoundImmediateEscalatingExpression = true;
17786}
17787
17788ExprResult Sema::CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl) {
17789 if (isUnevaluatedContext() || !E.isUsable() || !Decl ||
17790 !Decl->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
17791 isCheckingDefaultArgumentOrInitializer() ||
17792 RebuildingImmediateInvocation || isImmediateFunctionContext())
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>(Val: E.get()->IgnoreImplicit()))
17800 if (auto *DeclRef =
17801 dyn_cast<DeclRefExpr>(Val: Call->getCallee()->IgnoreImplicit()))
17802 ExprEvalContexts.back().ReferenceToConsteval.erase(Ptr: 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 = [&]() {
17811 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
17812 Expr::EvalResult Eval;
17813 Eval.Diag = &Notes;
17814 bool Res = E.get()->EvaluateAsConstantExpr(
17815 Result&: Eval, Ctx: getASTContext(), Kind: 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()) {
17826 MarkExpressionAsImmediateEscalating(E: E.get());
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.
17846 E = ExprWithCleanups::Create(C: getASTContext(), subexpr: E.get(),
17847 CleanupsHaveSideEffects: Cleanup.cleanupsHaveSideEffects(), objects: {});
17848 }
17849
17850 ConstantExpr *Res = ConstantExpr::Create(
17851 Context: getASTContext(), E: E.get(),
17852 Storage: ConstantExpr::getStorageKind(T: Decl->getReturnType().getTypePtr(),
17853 Context: getASTContext()),
17854 /*IsImmediateInvocation*/ true);
17855 if (Cached.hasValue())
17856 Res->MoveIntoResult(Value&: Cached, Context: 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(Args&: Res, Args: 0);
17861 return Res;
17862}
17863
17864static void EvaluateAndDiagnoseImmediateInvocation(
17865 Sema &SemaRef, Sema::ImmediateInvocationCandidate Candidate) {
17866 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
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()) {
17873 SemaRef.FailedImmediateInvocations.insert(Ptr: CE);
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 =
17892 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
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())
17898 SemaRef.DiagnoseImmediateEscalatingReason(FD);
17899 for (auto &Note : Notes)
17900 SemaRef.Diag(Note.first, Note.second);
17901 return;
17902 }
17903 CE->MoveIntoResult(Value&: Eval.Val, Context: SemaRef.getASTContext());
17904}
17905
17906static void RemoveNestedImmediateInvocation(
17907 Sema &SemaRef, Sema::ExpressionEvaluationContextRecord &Rec,
17908 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator It) {
17909 struct ComplexRemove : TreeTransform<ComplexRemove> {
17910 using Base = TreeTransform<ComplexRemove>;
17911 llvm::SmallPtrSetImpl<DeclRefExpr *> &DRSet;
17912 SmallVector<Sema::ImmediateInvocationCandidate, 4> &IISet;
17913 SmallVector<Sema::ImmediateInvocationCandidate, 4>::reverse_iterator
17914 CurrentII;
17915 ComplexRemove(Sema &SemaRef, llvm::SmallPtrSetImpl<DeclRefExpr *> &DR,
17916 SmallVector<Sema::ImmediateInvocationCandidate, 4> &II,
17917 SmallVector<Sema::ImmediateInvocationCandidate,
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(first: CurrentII, last: IISet.rend(),
17922 pred: [E](Sema::ImmediateInvocationCandidate Elem) {
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(Ptr: 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(Ptr: 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>(Val: Init))
17959 if (CE->isImmediateInvocation())
17960 RemoveImmediateInvocation(E: CE);
17961 return Base::TransformInitializer(Init, NotCopyInit);
17962 }
17963 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
17964 DRSet.erase(Ptr: 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,
17981 Rec.ImmediateInvocationCandidates, It);
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()) {
17997 Res = SemaRef.MaybeCreateExprWithCleanups(SubExpr: Res);
17998 It->getPointer()->setSubExpr(Res.get());
17999 }
18000}
18001
18002static void
18003HandleImmediateInvocations(Sema &SemaRef,
18004 Sema::ExpressionEvaluationContextRecord &Rec) {
18005 if ((Rec.ImmediateInvocationCandidates.size() == 0 &&
18006 Rec.ReferenceToConsteval.size() == 0) ||
18007 SemaRef.RebuildingImmediateInvocation)
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 ||
18016 !SemaRef.FailedImmediateInvocations.empty()) {
18017
18018 /// Prevent sema calls during the tree transform from adding pointers that
18019 /// are already in the sets.
18020 llvm::SaveAndRestore DisableIITracking(
18021 SemaRef.RebuildingImmediateInvocation, true);
18022
18023 /// Prevent diagnostic during tree transfrom as they are duplicates
18024 Sema::TentativeAnalysisScope DisableDiag(SemaRef);
18025
18026 for (auto It = Rec.ImmediateInvocationCandidates.rbegin();
18027 It != Rec.ImmediateInvocationCandidates.rend(); It++)
18028 if (!It->getInt())
18029 RemoveNestedImmediateInvocation(SemaRef, Rec, It);
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(Ptr: E);
18037 return DRSet.size();
18038 }
18039 } Visitor(Rec.ReferenceToConsteval);
18040 Visitor.TraverseStmt(
18041 S: Rec.ImmediateInvocationCandidates.front().getPointer()->getSubExpr());
18042 }
18043 for (auto CE : Rec.ImmediateInvocationCandidates)
18044 if (!CE.getInt())
18045 EvaluateAndDiagnoseImmediateInvocation(SemaRef, Candidate: CE);
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>(Val: DR->getDecl());
18053 const NamedDecl *ND = FD;
18054 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: 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 ==
18066 Sema::ExpressionEvaluationContext::PotentiallyEvaluated ||
18067 Rec.Context ==
18068 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed;
18069 if (SemaRef.inTemplateInstantiation() && IsPotentiallyEvaluated)
18070 ImmediateEscalating = Rec.InImmediateEscalatingFunctionContext;
18071
18072 if (!Rec.InImmediateEscalatingFunctionContext ||
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 =
18078 SemaRef.InnermostDeclarationWithDelayedImmediateInvocations()) {
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())
18084 SemaRef.DiagnoseImmediateEscalatingReason(FD);
18085
18086 } else {
18087 SemaRef.MarkExpressionAsImmediateEscalating(DR);
18088 }
18089 }
18090}
18091
18092void Sema::PopExpressionEvaluationContext() {
18093 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
18094 unsigned NumTypos = Rec.NumTypos;
18095
18096 if (!Rec.Lambdas.empty()) {
18097 using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
18098 if (!getLangOpts().CPlusPlus20 &&
18099 (Rec.ExprContext == ExpressionKind::EK_TemplateArgument ||
18100 Rec.isUnevaluated() ||
18101 (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17))) {
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];
18129 if (getLangOpts().CPlusPlus23 && Rec.InLifetimeExtendingContext &&
18130 PrevRecord.InLifetimeExtendingContext &&
18131 !Rec.ForRangeLifetimeExtendTemps.empty()) {
18132 PrevRecord.ForRangeLifetimeExtendTemps.append(
18133 RHS: Rec.ForRangeLifetimeExtendTemps);
18134 }
18135
18136 WarnOnPendingNoDerefs(Rec);
18137 HandleImmediateInvocations(SemaRef&: *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()) {
18151 ExprCleanupObjects.erase(CS: ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
18152 CE: ExprCleanupObjects.end());
18153 Cleanup = Rec.ParentCleanup;
18154 CleanupVarDeclMarking();
18155 std::swap(LHS&: MaybeODRUseExprs, RHS&: Rec.SavedMaybeODRUseExprs);
18156 // Otherwise, merge the contexts together.
18157 } else {
18158 Cleanup.mergeFrom(Rhs: Rec.ParentCleanup);
18159 MaybeODRUseExprs.insert(Start: Rec.SavedMaybeODRUseExprs.begin(),
18160 End: 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
18170void Sema::DiscardCleanupsInEvaluationContext() {
18171 ExprCleanupObjects.erase(
18172 CS: ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
18173 CE: ExprCleanupObjects.end());
18174 Cleanup.reset();
18175 MaybeODRUseExprs.clear();
18176}
18177
18178ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
18179 ExprResult Result = CheckPlaceholderExpr(E);
18180 if (Result.isInvalid())
18181 return ExprError();
18182 E = Result.get();
18183 if (!E->getType()->isVariablyModifiedType())
18184 return E;
18185 return TransformToPotentiallyEvaluated(E);
18186}
18187
18188/// Are we in a context that is potentially constant evaluated per C++20
18189/// [expr.const]p12?
18190static bool isPotentiallyConstantEvaluatedContext(Sema &SemaRef) {
18191 /// C++2a [expr.const]p12:
18192 // An expression or conversion is potentially constant evaluated if it is
18193 switch (SemaRef.ExprEvalContexts.back().Context) {
18194 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18195 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18196
18197 // -- a manifestly constant-evaluated expression,
18198 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18199 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
18200 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18201 // -- a potentially-evaluated expression,
18202 case Sema::ExpressionEvaluationContext::UnevaluatedList:
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
18211 case Sema::ExpressionEvaluationContext::Unevaluated:
18212 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
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.
18221static bool funcHasParameterSizeMangling(Sema &S, FunctionDecl *FD) {
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.
18255static void CheckCompleteParameterTypesForMangler(Sema &S, FunctionDecl *FD,
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) {
18313 case Sema::ExpressionEvaluationContext::Unevaluated:
18314 case Sema::ExpressionEvaluationContext::UnevaluatedList:
18315 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
18316 return OdrUseContext::None;
18317
18318 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
18319 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
18320 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
18321 Result = OdrUseContext::Used;
18322 break;
18323
18324 case Sema::ExpressionEvaluationContext::DiscardedStatement:
18325 Result = OdrUseContext::FormallyOdrUsed;
18326 break;
18327
18328 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
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
18335 if (SemaRef.CurContext->isDependentContext())
18336 return OdrUseContext::Dependent;
18337
18338 return Result;
18339}
18340
18341static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
18342 if (!Func->isConstexpr())
18343 return false;
18344
18345 if (Func->isImplicitlyInstantiable() || !Func->isUserProvided())
18346 return true;
18347 auto *CCD = dyn_cast<CXXConstructorDecl>(Val: 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)
18353void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
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(SemaRef&: *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>(Val: Func))
18380 if (Constructor->isDefaultConstructor())
18381 OdrUse = OdrUseContext::FormallyOdrUsed;
18382 if (isa<CXXDestructorDecl>(Val: 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 =
18391 isPotentiallyConstantEvaluatedContext(SemaRef&: *this) &&
18392 isImplicitlyDefinableConstexprFunction(Func);
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()))
18428 checkSpecializationReachability(Loc, Func);
18429
18430 if (getLangOpts().CUDA)
18431 CUDA().CheckCall(Loc, Callee: Func);
18432
18433 // If we need a definition, try to create one.
18434 if (NeedDefinition && !Func->getBody()) {
18435 runWithSufficientStackSpace(Loc, Fn: [&] {
18436 if (CXXConstructorDecl *Constructor =
18437 dyn_cast<CXXConstructorDecl>(Val: 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(CurrentLocation: Loc, Constructor);
18445 } else if (Constructor->isCopyConstructor()) {
18446 DefineImplicitCopyConstructor(CurrentLocation: Loc, Constructor);
18447 } else if (Constructor->isMoveConstructor()) {
18448 DefineImplicitMoveConstructor(CurrentLocation: Loc, Constructor);
18449 }
18450 } else if (Constructor->getInheritedConstructor()) {
18451 DefineInheritingConstructor(UseLoc: Loc, Constructor);
18452 }
18453 } else if (CXXDestructorDecl *Destructor =
18454 dyn_cast<CXXDestructorDecl>(Val: Func)) {
18455 Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
18456 if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
18457 if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
18458 return;
18459 DefineImplicitDestructor(CurrentLocation: Loc, Destructor);
18460 }
18461 if (Destructor->isVirtual() && getLangOpts().AppleKext)
18462 MarkVTableUsed(Loc, Class: Destructor->getParent());
18463 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: 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(CurrentLocation: Loc, MethodDecl);
18470 else if (MethodDecl->isMoveAssignmentOperator())
18471 DefineImplicitMoveAssignment(CurrentLocation: Loc, MethodDecl);
18472 }
18473 } else if (isa<CXXConversionDecl>(Val: MethodDecl) &&
18474 MethodDecl->getParent()->isLambda()) {
18475 CXXConversionDecl *Conversion =
18476 cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
18477 if (Conversion->isLambdaToBlockPointerConversion())
18478 DefineImplicitLambdaToBlockPointerConversion(CurrentLoc: Loc, Conv: Conversion);
18479 else
18480 DefineImplicitLambdaToFunctionPointerConversion(CurrentLoc: Loc, Conv: Conversion);
18481 } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
18482 MarkVTableUsed(Loc, Class: MethodDecl->getParent());
18483 }
18484
18485 if (Func->isDefaulted() && !Func->isDeleted()) {
18486 DefaultedComparisonKind DCK = getDefaultedComparisonKind(FD: Func);
18487 if (DCK != DefaultedComparisonKind::None)
18488 DefineDefaultedComparison(Loc, FD: Func, DCK);
18489 }
18490
18491 // Implicit instantiation of function templates and member functions of
18492 // class templates.
18493 if (Func->isImplicitlyInstantiable()) {
18494 TemplateSpecializationKind TSK =
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())
18517 PendingLocalImplicitInstantiations.push_back(
18518 std::make_pair(x&: Func, y&: 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, Function: Func);
18524 else {
18525 Func->setInstantiationIsPending(true);
18526 PendingInstantiations.push_back(
18527 std::make_pair(x&: Func, y&: PointOfInstantiation));
18528 // Notify the consumer that a function was implicitly instantiated.
18529 Consumer.HandleCXXImplicitFunctionInstantiation(D: Func);
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>(Val: Func)) {
18546 EnterExpressionEvaluationContext EvalContext(
18547 *this,
18548 Constructor->isImmediateFunction()
18549 ? ExpressionEvaluationContext::ImmediateFunctionContext
18550 : ExpressionEvaluationContext::PotentiallyEvaluated,
18551 Constructor);
18552 for (CXXCtorInitializer *Init : Constructor->inits()) {
18553 if (Init->isInClassMemberInitializer())
18554 runWithSufficientStackSpace(Loc: Init->getSourceLocation(), Fn: [&]() {
18555 MarkDeclarationsReferencedInExpr(E: 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>();
18570 if (FPT && isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType()))
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 &&
18577 !getASTContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: Func))
18578 CUDA().RecordImplicitHostDeviceFuncUsedByDevice(FD: Func);
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(x: Func->getCanonicalDecl(), y&: Loc));
18586 else if (Func->getMostRecentDecl()->isInlined() &&
18587 !LangOpts.GNUInline &&
18588 !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
18589 UndefinedButUsed.insert(std::make_pair(x: Func->getCanonicalDecl(), y&: Loc));
18590 else if (isExternalWithNoLinkageType(Func))
18591 UndefinedButUsed.insert(std::make_pair(x: Func->getCanonicalDecl(), y&: 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.
18597 if (funcHasParameterSizeMangling(S&: *this, FD: Func))
18598 CheckCompleteParameterTypesForMangler(S&: *this, FD: Func, Loc);
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.
18606 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
18607 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: Func)) {
18608 CXXRecordDecl *Parent = Dtor->getParent();
18609 if (Parent->getNumVBases() > 0 && !Dtor->getBody())
18610 CheckCompleteDestructorVariant(CurrentLocation: Loc, Dtor);
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
18626MarkVarDeclODRUsed(ValueDecl *V, SourceLocation Loc, Sema &SemaRef,
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
18633 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
18634 (!Var->isExternallyVisible() || Var->isInline() ||
18635 SemaRef.isExternalWithNoLinkageType(Var)) &&
18636 !(Var->isStaticDataMember() && Var->hasInit())) {
18637 SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
18638 if (old.isInvalid())
18639 old = Loc;
18640 }
18641 QualType CaptureType, DeclRefType;
18642 if (SemaRef.LangOpts.OpenMP)
18643 SemaRef.OpenMP().tryCaptureOpenMPLambdas(V);
18644 SemaRef.tryCaptureVariable(Var: V, Loc, Kind: Sema::TryCapture_Implicit,
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>(Val: SemaRef.CurContext);
18651 auto VarTarget = SemaRef.CUDA().IdentifyTarget(D: Var);
18652 auto UserTarget = SemaRef.CUDA().IdentifyTarget(D: 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);
18664 SemaRef.targetDiag(Var->getLocation(),
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())
18684 SemaRef.getASTContext().CUDADeviceVarODRUsedByHost.insert(V: Var);
18685 else if (SemaRef.LangOpts.GPURelocatableDeviceCode &&
18686 (!FD || (!FD->getDescribedFunctionTemplate() &&
18687 SemaRef.getASTContext().GetGVALinkageForFunction(FD) ==
18688 GVA_StrongExternal)))
18689 SemaRef.getASTContext().CUDAExternalDeviceDeclODRUsedByHost.insert(Var);
18690 }
18691 }
18692
18693 V->markUsed(SemaRef.Context);
18694}
18695
18696void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl *Capture,
18697 SourceLocation Loc,
18698 unsigned CapturingScopeIndex) {
18699 MarkVarDeclODRUsed(V: Capture, Loc, SemaRef&: *this, FunctionScopeIndexToStopAt: &CapturingScopeIndex);
18700}
18701
18702void diagnoseUncapturableValueReferenceOrBinding(Sema &S, SourceLocation loc,
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>(Val: var) &&
18710 isa<TranslationUnitDecl>(Val: 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>(Val: var) ? 1 : 0;
18724 unsigned ContextKind = 3; // unknown
18725 if (isa<CXXMethodDecl>(Val: VarDC) &&
18726 cast<CXXRecordDecl>(Val: VarDC->getParent())->isLambda()) {
18727 ContextKind = 2;
18728 } else if (isa<FunctionDecl>(Val: VarDC)) {
18729 ContextKind = 0;
18730 } else if (isa<BlockDecl>(Val: 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
18743static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI,
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(Val: 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>(Val: CSI) &&
18765 !cast<LambdaScopeInfo>(Val: CSI)->lambdaCaptureShouldBeConst()) &&
18766 !(isa<CapturedRegionScopeInfo>(Val: CSI) &&
18767 cast<CapturedRegionScopeInfo>(Val: 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.
18776static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC,
18777 ValueDecl *Var,
18778 SourceLocation Loc,
18779 const bool Diagnose,
18780 Sema &S) {
18781 if (isa<BlockDecl>(Val: DC) || isa<CapturedDecl>(Val: DC) || isLambdaCallOperator(DC))
18782 return getLambdaAwareParentOfDeclContext(DC);
18783
18784 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
18785 if (Underlying) {
18786 if (Underlying->hasLocalStorage() && Diagnose)
18787 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
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.
18795static bool isVariableCapturable(CapturingScopeInfo *CSI, ValueDecl *Var,
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>(Val: CSI);
18803 bool IsLambda = isa<LambdaScopeInfo>(Val: 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>(Val: 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>(Val: Var)) {
18858 if (!IsLambda || !S.getLangOpts().CPlusPlus) {
18859 if (Diagnose)
18860 diagnoseUncapturableValueReferenceOrBinding(S, loc: Loc, var: Var);
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.
18875static bool captureInBlock(BlockScopeInfo *BSI, ValueDecl *Var,
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 &&
18896 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
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>() &&
18912 PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
18913 !S.Context.hasDirectOwnershipQualifier(Ty: 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(D: 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.
18943static bool captureInCapturedRegion(
18944 CapturedRegionScopeInfo *RSI, ValueDecl *Var, SourceLocation Loc,
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(D: 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(D: Var, Level: RSI->OpenMPLevel,
18966 OpenMPCaptureLevel: RSI->OpenMPCaptureLevel);
18967 }
18968
18969 if (ByRef)
18970 CaptureType = S.Context.getLValueReferenceType(T: 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.
18983static bool captureInLambda(LambdaScopeInfo *LSI, ValueDecl *Var,
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() &&
18999 CaptureType.getNonReferenceType().isWebAssemblyReferenceType()) {
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(T: 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 &&
19037 CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
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() &&
19051 S.RequireCompleteSizedType(
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
19085static bool canCaptureVariableByCopy(ValueDecl *Var,
19086 const ASTContext &Context) {
19087 // Offer a Copy fix even if the type is dependent.
19088 if (Var->getType()->isDependentType())
19089 return true;
19090 QualType T = Var->getType().getNonReferenceType();
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.
19111static void buildLambdaCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI,
19112 ValueDecl *Var) {
19113 assert(LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None);
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, Context: 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(Range&: LSI->Captures, P: [](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 =
19152 LSI->IntroducerRange.getBegin().getLocWithOffset(Offset: 1);
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
19160 ? LSI->getCXXThisCapture().isCopyCapture()
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(Range&: LSI->Captures, P: [](Capture &C) {
19165 return !C.isThisCapture() && !C.isInitCapture() && C.isCopyCapture();
19166 })) {
19167 FixBuffer.assign(Refs: {"=", 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(Range&: LSI->Captures, P: [](Capture &C) {
19177 return !C.isInitCapture() && C.isReferenceCapture() &&
19178 !C.isThisCapture();
19179 })) {
19180 FixBuffer.assign(Refs: {"&", Separator});
19181 Sema.Diag(DefaultInsertLoc, diag::note_lambda_default_capture_fixit)
19182 << /*reference*/ 1
19183 << FixItHint::CreateInsertion(DefaultInsertLoc, FixBuffer);
19184 }
19185}
19186
19187bool Sema::tryCaptureVariable(
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>(Val: Var);
19204 if (VD) {
19205 if (VD->isInitCapture())
19206 VarDC = VarDC->getParent();
19207 } else {
19208 VD = Var->getPotentiallyDecomposedVarDecl();
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) {
19219 DC = getLambdaAwareParentOfDeclContext(DC);
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(D: Var, /*CheckScopeInfo=*/true,
19229 StopAt: MaxFunctionScopesIndex)))
19230 return true;
19231
19232 if (isa<VarDecl>(Val: 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 Val: 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>(Val: 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, Loc: ExprLoc,
19276 Diagnose: BuildAndDiagnose, S&: *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>(Val: FSI);
19290
19291 // Check whether we've already captured it.
19292 if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, SubCapturesAreNested&: Nested, CaptureType,
19293 DeclRefType)) {
19294 CSI->getCapture(Var).markUsed(IsODRUse: 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>(Val: 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.
19309 if (isGenericLambdaCallOperatorSpecialization(DC)) {
19310 if (BuildAndDiagnose) {
19311 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
19312 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
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(Sema&: *this, LSI, Var);
19317 } else
19318 diagnoseUncapturableValueReferenceOrBinding(S&: *this, loc: ExprLoc, var: Var);
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>(Val: Var))
19329 QTy = PVD->getOriginalType();
19330 captureVariablyModifiedType(Context, T: QTy, CSI);
19331 }
19332
19333 if (getLangOpts().OpenMP) {
19334 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: 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>(Val: 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>(Val: Var))
19357 QTy = PVD->getOriginalType();
19358 for (int I = 1,
19359 E = OpenMP().getNumberOfConstructScopes(Level: RSI->OpenMPLevel);
19360 I < E; ++I) {
19361 auto *OuterRSI = cast<CapturedRegionScopeInfo>(
19362 Val: 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 D: Var, Level: RSI->OpenMPLevel, CaptureLevel: 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 Level: 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(T: 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>(Val: CSI);
19406 if (LSI->Lambda) {
19407 Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
19408 buildLambdaCaptureFixit(Sema&: *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>(Val: 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, Loc: ExprLoc, Diagnose: BuildAndDiagnose, S&: *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>(Val: CSI)) {
19453 Invalid = !captureInBlock(BSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
19454 DeclRefType, Nested, S&: *this, Invalid);
19455 Nested = true;
19456 } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(Val: CSI)) {
19457 Invalid = !captureInCapturedRegion(
19458 RSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType, DeclRefType, RefersToCapturedVariable: Nested,
19459 Kind, /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
19460 Nested = true;
19461 } else {
19462 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: CSI);
19463 Invalid =
19464 !captureInLambda(LSI, Var, Loc: ExprLoc, BuildAndDiagnose, CaptureType,
19465 DeclRefType, RefersToCapturedVariable: Nested, Kind, EllipsisLoc,
19466 /*IsTopScope*/ I == N - 1, S&: *this, Invalid);
19467 Nested = true;
19468 }
19469
19470 if (Invalid && !BuildAndDiagnose)
19471 return true;
19472 }
19473 return Invalid;
19474}
19475
19476bool Sema::tryCaptureVariable(ValueDecl *Var, SourceLocation Loc,
19477 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
19478 QualType CaptureType;
19479 QualType DeclRefType;
19480 return tryCaptureVariable(Var, ExprLoc: Loc, Kind, EllipsisLoc,
19481 /*BuildAndDiagnose=*/true, CaptureType,
19482 DeclRefType, FunctionScopeIndexToStopAt: nullptr);
19483}
19484
19485bool Sema::NeedToCaptureVariable(ValueDecl *Var, SourceLocation Loc) {
19486 QualType CaptureType;
19487 QualType DeclRefType;
19488 return !tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCapture_Implicit, EllipsisLoc: SourceLocation(),
19489 /*BuildAndDiagnose=*/false, CaptureType,
19490 DeclRefType, FunctionScopeIndexToStopAt: nullptr);
19491}
19492
19493QualType Sema::getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc) {
19494 QualType CaptureType;
19495 QualType DeclRefType;
19496
19497 // Determine whether we can capture this variable.
19498 if (tryCaptureVariable(Var, ExprLoc: Loc, Kind: TryCapture_Implicit, EllipsisLoc: SourceLocation(),
19499 /*BuildAndDiagnose=*/false, CaptureType,
19500 DeclRefType, FunctionScopeIndexToStopAt: 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.
19537static ExprResult rebuildPotentialResultsAsNonOdrUsed(Sema &S, Expr *E,
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, E: 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>(Val: 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(C: 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(X: E);
19608 if (LambdaScopeInfo *LSI = S.getCurLambda())
19609 LSI->markVariableExprAsNonODRUsed(CapturingVarExpr: 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>(Val: 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>(Val: 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>(Val: 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(S: nullptr, base: LHS, lbLoc: LBracketLoc, ArgExprs: RHS,
19658 rbLoc: ASE->getRBracketLoc());
19659 }
19660
19661 case Expr::MemberExprClass: {
19662 auto *ME = cast<MemberExpr>(Val: E);
19663 // -- If e is a class member access expression [...] naming a non-static
19664 // data member...
19665 if (isa<FieldDecl>(Val: ME->getMemberDecl())) {
19666 ExprResult Base = Rebuild(ME->getBase());
19667 if (!Base.isUsable())
19668 return Base;
19669 return MemberExpr::Create(
19670 C: S.Context, Base: Base.get(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
19671 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(),
19672 MemberDecl: ME->getMemberDecl(), FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(),
19673 TemplateArgs: CopiedTemplateArgs(ME), T: ME->getType(), VK: ME->getValueKind(),
19674 OK: ME->getObjectKind(), NOUR: 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 C: S.Context, Base: ME->getBase(), IsArrow: ME->isArrow(), OperatorLoc: ME->getOperatorLoc(),
19689 QualifierLoc: ME->getQualifierLoc(), TemplateKWLoc: ME->getTemplateKeywordLoc(), MemberDecl: ME->getMemberDecl(),
19690 FoundDecl: ME->getFoundDecl(), MemberNameInfo: ME->getMemberNameInfo(), TemplateArgs: CopiedTemplateArgs(ME),
19691 T: ME->getType(), VK: ME->getValueKind(), OK: ME->getObjectKind(), NOUR);
19692 }
19693
19694 case Expr::BinaryOperatorClass: {
19695 auto *BO = cast<BinaryOperator>(Val: 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(S: nullptr, OpLoc: BO->getOperatorLoc(), Opc: BO->getOpcode(),
19714 LHSExpr: LHS, RHSExpr: RHS);
19715 }
19716
19717 // -- If e has the form (e1)...
19718 case Expr::ParenExprClass: {
19719 auto *PE = cast<ParenExpr>(Val: E);
19720 ExprResult Sub = Rebuild(PE->getSubExpr());
19721 if (!Sub.isUsable())
19722 return Sub;
19723 return S.ActOnParenExpr(L: PE->getLParen(), R: PE->getRParen(), E: 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>(Val: 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(QuestionLoc: CO->getQuestionLoc(), ColonLoc: CO->getColonLoc(),
19743 CondExpr: CO->getCond(), LHSExpr: LHS.get(), RHSExpr: RHS.get());
19744 }
19745
19746 // [Clang extension]
19747 // -- If e has the form __extension__ e1...
19748 case Expr::UnaryOperatorClass: {
19749 auto *UO = cast<UnaryOperator>(Val: 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(S: nullptr, OpLoc: UO->getOperatorLoc(), Opc: UO_Extension,
19756 Input: 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>(Val: 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(Elt: AssocExpr.get());
19773 AnyChanged = true;
19774 } else {
19775 AssocExprs.push_back(Elt: 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 KeyLoc: GSE->getGenericLoc(), DefaultLoc: GSE->getDefaultLoc(),
19787 RParenLoc: GSE->getRParenLoc(), PredicateIsExpr: IsExpr, ControllingExprOrType: ExOrTy,
19788 Types: GSE->getAssocTypeSourceInfos(), Exprs: 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>(Val: 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(BuiltinLoc: CE->getBuiltinLoc(), CondExpr: CE->getCond(), LHSExpr: LHS.get(),
19815 RHSExpr: RHS.get(), RPLoc: CE->getRParenLoc());
19816 }
19817
19818 // Step through non-syntactic nodes.
19819 case Expr::ConstantExprClass: {
19820 auto *CE = cast<ConstantExpr>(Val: E);
19821 ExprResult Sub = Rebuild(CE->getSubExpr());
19822 if (!Sub.isUsable())
19823 return Sub;
19824 return ConstantExpr::Create(Context: S.Context, E: 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>(Val: 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(E: Sub.get(), Type: ICE->getType(), CK: ICE->getCastKind(),
19843 VK: ICE->getValueKind(), BasePath: &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
19860ExprResult Sema::CheckLValueToRValueConversionOperand(Expr *E) {
19861 // Check whether the operand is or contains an object of non-trivial C union
19862 // type.
19863 if (E->getType().isVolatileQualified() &&
19864 (E->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
19865 E->getType().hasNonTrivialToPrimitiveCopyCUnion()))
19866 checkNonTrivialCUnion(QT: E->getType(), Loc: E->getExprLoc(),
19867 UseContext: Sema::NTCUC_LValueToRValueVolatile,
19868 NonTrivialKind: NTCUK_Destruct|NTCUK_Copy);
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
19876 ExprResult Result =
19877 rebuildPotentialResultsAsNonOdrUsed(S&: *this, E, NOUR: NOUR_Constant);
19878 if (Result.isInvalid())
19879 return ExprError();
19880 return Result.get() ? Result : E;
19881}
19882
19883ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
19884 Res = CorrectDelayedTyposInExpr(ER: 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.
19893 return CheckLValueToRValueConversionOperand(E: Res.get());
19894}
19895
19896void Sema::CleanupVarDeclMarking() {
19897 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19898 // call.
19899 MaybeODRUseExprSet LocalMaybeODRUseExprs;
19900 std::swap(LHS&: LocalMaybeODRUseExprs, RHS&: MaybeODRUseExprs);
19901
19902 for (Expr *E : LocalMaybeODRUseExprs) {
19903 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
19904 MarkVarDeclODRUsed(cast<VarDecl>(Val: DRE->getDecl()),
19905 DRE->getLocation(), *this);
19906 } else if (auto *ME = dyn_cast<MemberExpr>(Val: E)) {
19907 MarkVarDeclODRUsed(cast<VarDecl>(Val: ME->getMemberDecl()), ME->getMemberLoc(),
19908 *this);
19909 } else if (auto *FP = dyn_cast<FunctionParmPackExpr>(Val: 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
19921static void DoMarkPotentialCapture(Sema &SemaRef, SourceLocation Loc,
19922 ValueDecl *Var, Expr *E) {
19923 VarDecl *VD = Var->getPotentiallyDecomposedVarDecl();
19924 if (!VD)
19925 return;
19926
19927 const bool RefersToEnclosingScope =
19928 (SemaRef.CurContext != VD->getDeclContext() &&
19929 VD->getDeclContext()->isFunctionOrMethod() && VD->hasLocalStorage());
19930 if (RefersToEnclosingScope) {
19931 LambdaScopeInfo *const LSI =
19932 SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19933 if (LSI && (!LSI->CallOperator ||
19934 !LSI->CallOperator->Encloses(DC: 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() ||
19947 !VD->isUsableInConstantExpressions(C: SemaRef.Context))
19948 LSI->addPotentialCapture(VarExpr: E->IgnoreParens());
19949 }
19950 }
19951}
19952
19953static void DoMarkVarDeclReferenced(
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();
19965 TemplateSpecializationKind TSK = MSI ? MSI->getTemplateSpecializationKind()
19966 : Var->getTemplateSpecializationKind();
19967
19968 OdrUseContext OdrUse = isOdrUseContext(SemaRef);
19969 bool UsableInConstantExpr =
19970 Var->mightBeUsableInConstantExpressions(C: SemaRef.Context);
19971
19972 if (Var->isLocalVarDeclOrParm() && !Var->hasExternalStorage()) {
19973 RefsMinusAssignments.insert(KV: {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>(Val: Var))
19995 SemaRef.checkSpecializationVisibility(Loc, 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(Kind: 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 =
20006 TSK == TSK_ImplicitInstantiation ||
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(Loc: PointOfInstantiation, Fn: [&] {
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>(Val: E))
20032 DRE->setDecl(DRE->getDecl());
20033 else if (auto *ME = dyn_cast_or_null<MemberExpr>(Val: E))
20034 ME->setMemberDecl(ME->getMemberDecl());
20035 } else if (FirstInstantiation) {
20036 SemaRef.PendingInstantiations
20037 .push_back(std::make_pair(x&: Var, y&: PointOfInstantiation));
20038 } else {
20039 bool Inserted = false;
20040 for (auto &I : SemaRef.SavedPendingInstantiations) {
20041 auto Iter = llvm::find_if(
20042 Range&: I, P: [Var](const Sema::PendingImplicitInstantiation &P) {
20043 return P.first == Var;
20044 });
20045 if (Iter != I.end()) {
20046 SemaRef.PendingInstantiations.push_back(x: *Iter);
20047 I.erase(position: 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>(Val: Var) && !Inserted)
20059 SemaRef.PendingInstantiations
20060 .push_back(std::make_pair(x&: Var, y&: 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>(Val: E))
20085 if (DRE->isNonOdrUse())
20086 return;
20087 if (MemberExpr *ME = dyn_cast_or_null<MemberExpr>(Val: 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) ||
20096 SemaRef.isUnevaluatedContext()) &&
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.
20108 if (E && Var->isUsableInConstantExpressions(C: SemaRef.Context))
20109 SemaRef.MaybeODRUseExprs.insert(X: 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
20124static void DoMarkBindingDeclReferenced(Sema &SemaRef, SourceLocation Loc,
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;
20134 SemaRef.tryCaptureVariable(BD, Loc, Sema::TryCapture_Implicit,
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.
20147void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
20148 DoMarkVarDeclReferenced(SemaRef&: *this, Loc, Var, E: 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]),
20156static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
20157 Sema &SemaRef, ValueDecl *D, Expr *E) {
20158 auto *ID = dyn_cast<DeclRefExpr>(Val: 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(C&: SemaRef.FunctionScopes)) {
20168 auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Val: 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 Set: IsDependent, Context: SemaRef.getASTContext());
20199}
20200
20201static void
20202MarkExprReferenced(Sema &SemaRef, SourceLocation Loc, Decl *D, Expr *E,
20203 bool MightBeOdrUse,
20204 llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
20205 if (SemaRef.OpenMP().isInOpenMPDeclareTargetContext())
20206 SemaRef.OpenMP().checkDeclIsAllowedInOpenMPTarget(E, D);
20207
20208 if (VarDecl *Var = dyn_cast<VarDecl>(Val: D)) {
20209 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E, RefsMinusAssignments);
20210 if (SemaRef.getLangOpts().CPlusPlus)
20211 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
20212 Var, E);
20213 return;
20214 }
20215
20216 if (BindingDecl *Decl = dyn_cast<BindingDecl>(Val: D)) {
20217 DoMarkBindingDeclReferenced(SemaRef, Loc, BD: Decl, E);
20218 if (SemaRef.getLangOpts().CPlusPlus)
20219 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef,
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>(Val: E);
20228 if (!ME)
20229 return;
20230 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ME->getMemberDecl());
20231 if (!MD)
20232 return;
20233 // Only attempt to devirtualize if this is truly a virtual call.
20234 bool IsVirtualCall = MD->isVirtual() &&
20235 ME->performsVirtualDispatch(LO: SemaRef.getLangOpts());
20236 if (!IsVirtualCall)
20237 return;
20238
20239 // If it's possible to devirtualize the call, mark the called function
20240 // referenced.
20241 CXXMethodDecl *DM = MD->getDevirtualizedMethod(
20242 Base: ME->getBase(), IsAppleKext: 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.
20251void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
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>(Val: E->getDecl()))
20257 if (Method->isVirtual() &&
20258 !Method->getDevirtualizedMethod(Base, IsAppleKext: getLangOpts().AppleKext))
20259 OdrUse = false;
20260
20261 if (auto *FD = dyn_cast<FunctionDecl>(Val: E->getDecl())) {
20262 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
20263 !isImmediateFunctionContext() &&
20264 !isCheckingDefaultArgumentOrInitializer() &&
20265 FD->isImmediateFunction() && !RebuildingImmediateInvocation &&
20266 !FD->isDependentContext())
20267 ExprEvalContexts.back().ReferenceToConsteval.insert(Ptr: E);
20268 }
20269 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse,
20270 RefsMinusAssignments);
20271}
20272
20273/// Perform reference-marking and odr-use handling for a MemberExpr.
20274void Sema::MarkMemberReferenced(MemberExpr *E) {
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;
20282 if (E->performsVirtualDispatch(LO: getLangOpts())) {
20283 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: 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,
20290 RefsMinusAssignments);
20291}
20292
20293/// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
20294void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr *E) {
20295 for (VarDecl *VD : *E)
20296 MarkExprReferenced(*this, E->getParameterPackLocation(), VD, E, true,
20297 RefsMinusAssignments);
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.
20304void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
20305 bool MightBeOdrUse) {
20306 if (MightBeOdrUse) {
20307 if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
20308 MarkVariableReferenced(Loc, Var: VD);
20309 return;
20310 }
20311 }
20312 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
20313 MarkFunctionReferenced(Loc, Func: 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:
20332 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
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.
20344 EnterExpressionEvaluationContext Evaluated(
20345 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
20346 if (Arg.getKind() == TemplateArgument::Declaration) {
20347 if (Decl *D = Arg.getAsDecl())
20348 S.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse: true);
20349 } else if (Arg.getKind() == TemplateArgument::Expression) {
20350 S.MarkDeclarationsReferencedInExpr(E: Arg.getAsExpr(), SkipLocalVariables: false);
20351 }
20352 }
20353
20354 return Inherited::TraverseTemplateArgument(Arg);
20355}
20356
20357void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
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;
20369 ArrayRef<const Expr *> StopAt;
20370
20371 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables,
20372 ArrayRef<const Expr *> StopAt)
20373 : Inherited(S), SkipLocalVariables(SkipLocalVariables), StopAt(StopAt) {}
20374
20375 void visitUsedDecl(SourceLocation Loc, Decl *D) {
20376 S.MarkFunctionReferenced(Loc, Func: cast<FunctionDecl>(Val: D));
20377 }
20378
20379 void Visit(Expr *E) {
20380 if (llvm::is_contained(Range&: StopAt, Element: 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>(Val: 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?
20401 S.MarkDeclRefReferenced(E);
20402 }
20403
20404 void VisitMemberExpr(MemberExpr *E) {
20405 S.MarkMemberReferenced(E);
20406 Visit(E: 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.
20417void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
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]; }
20428bool Sema::DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
20429 const PartialDiagnostic &PD) {
20430 if (!Stmts.empty() && getCurFunctionOrMethodDecl()) {
20431 if (!FunctionScopes.empty())
20432 FunctionScopes.back()->PossiblyUnreachableDiags.push_back(
20433 Elt: 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 Val: 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.
20471bool Sema::DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
20472 const PartialDiagnostic &PD) {
20473
20474 if (ExprEvalContexts.back().isDiscardedStatementContext())
20475 return false;
20476
20477 switch (ExprEvalContexts.back().Context) {
20478 case ExpressionEvaluationContext::Unevaluated:
20479 case ExpressionEvaluationContext::UnevaluatedList:
20480 case ExpressionEvaluationContext::UnevaluatedAbstract:
20481 case ExpressionEvaluationContext::DiscardedStatement:
20482 // The argument will never be evaluated, so don't complain.
20483 break;
20484
20485 case ExpressionEvaluationContext::ConstantEvaluated:
20486 case ExpressionEvaluationContext::ImmediateFunctionContext:
20487 // Relevant diagnostics should be produced by constant evaluation.
20488 break;
20489
20490 case ExpressionEvaluationContext::PotentiallyEvaluated:
20491 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
20492 return DiagIfReachable(Loc, Stmts, PD);
20493 }
20494
20495 return false;
20496}
20497
20498bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
20499 const PartialDiagnostic &PD) {
20500 return DiagRuntimeBehavior(
20501 Loc, Stmts: Statement ? llvm::ArrayRef(Statement) : std::nullopt, PD);
20502}
20503
20504bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
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 ==
20512 ExpressionEvaluationContextRecord::EK_Decltype) {
20513 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(Elt: 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, T: 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.
20547void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
20548 SourceLocation Loc;
20549
20550 unsigned diagnostic = diag::warn_condition_is_assignment;
20551 bool IsOrAssign = false;
20552
20553 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(Val: 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>(Val: 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>(Val: 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>(Val: E))
20581 return DiagnoseAssignmentAsCondition(E: POE->getSyntacticForm());
20582 else {
20583 // Not an assignment.
20584 return;
20585 }
20586
20587 Diag(Loc, diagnostic) << E->getSourceRange();
20588
20589 SourceLocation Open = E->getBeginLoc();
20590 SourceLocation Close = getLocForEndOfToken(Loc: E->getSourceRange().getEnd());
20591 Diag(Loc, diag::note_condition_assign_silence)
20592 << FixItHint::CreateInsertion(Open, "(")
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.
20605void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
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>(Val: E))
20617 if (opE->getOpcode() == BO_EQ &&
20618 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Ctx&: 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
20632ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
20633 bool IsConstexpr) {
20634 DiagnoseAssignmentAsCondition(E);
20635 if (ParenExpr *parenE = dyn_cast<ParenExpr>(Val: E))
20636 DiagnoseEqualityWithExtraParens(ParenE: parenE);
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(CondExpr: E, IsConstexpr); // C++ 6.4p4
20645
20646 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
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, CC: Loc);
20658 }
20659
20660 return E;
20661}
20662
20663Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
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) {
20673 case ConditionKind::Boolean:
20674 Cond = CheckBooleanCondition(Loc, E: SubExpr);
20675 break;
20676
20677 case ConditionKind::ConstexprIf:
20678 Cond = CheckBooleanCondition(Loc, E: SubExpr, IsConstexpr: true);
20679 break;
20680
20681 case ConditionKind::Switch:
20682 Cond = CheckSwitchCondition(SwitchLoc: Loc, Cond: SubExpr);
20683 break;
20684 }
20685 if (Cond.isInvalid()) {
20686 Cond = CreateRecoveryExpr(Begin: SubExpr->getBeginLoc(), End: SubExpr->getEndLoc(),
20687 SubExprs: {SubExpr}, T: PreferredConditionType(K: 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(Arg: Cond.get(), CC: Loc);
20693 if (!FullExpr.get())
20694 return ConditionError();
20695
20696 return ConditionResult(*this, nullptr, FullExpr,
20697 CK == ConditionKind::ConstexprIf);
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(T: 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>(Val: VD)) return VisitExpr(E);
20756
20757 E->setType(VD->getType());
20758
20759 assert(E->isPRValue());
20760 if (S.getLangOpts().CPlusPlus &&
20761 !(isa<CXXMethodDecl>(Val: VD) &&
20762 cast<CXXMethodDecl>(Val: VD)->isInstance()))
20763 E->setValueKind(VK_LValue);
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.
20780static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
20781 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
20782 if (Result.isInvalid()) return ExprError();
20783 return S.DefaultFunctionArrayConversion(E: 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>(Val: 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(expr: 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));
20914 E->setValueKind(Expr::getValueKindForType(DestType));
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>(Val: 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(N: E->getNumArgs());
20943 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
20944 ArgTypes.push_back(Elt: S.Context.getReferenceQualifiedType(e: E->getArg(Arg: 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());
20995 E->setValueKind(Expr::getValueKindForType(DestType));
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>(Val: 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(E: Result.get(), Type, CK: CK_FunctionToPointerDecay,
21050 VK: 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>(Val: FnType);
21065 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E);
21066 if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
21067 SourceLocation Loc = FD->getLocation();
21068 FunctionDecl *NewFD = FunctionDecl::Create(
21069 S.Context, FD->getDeclContext(), Loc, Loc,
21070 FD->getNameInfo().getName(), DestType, FD->getTypeSourceInfo(),
21071 SC_None, S.getCurFPFeatures().isFPConstrained(),
21072 false /*isInlineSpecified*/, FD->hasPrototype(),
21073 /*ConstexprKind*/ ConstexprSpecKind::Unspecified);
21074
21075 if (FD->getQualifier())
21076 NewFD->setQualifierInfo(FD->getQualifierLoc());
21077
21078 SmallVector<ParmVarDecl*, 16> Params;
21079 for (const auto &AI : FT->param_types()) {
21080 ParmVarDecl *Param =
21081 S.BuildParmVarDeclForTypedef(FD, Loc, AI);
21082 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
21083 Params.push_back(Elt: Param);
21084 }
21085 NewFD->setParams(Params);
21086 DRE->setDecl(NewFD);
21087 VD = DRE->getDecl();
21088 }
21089 }
21090
21091 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: FD))
21092 if (MD->isInstance()) {
21093 ValueKind = VK_PRValue;
21094 Type = S.Context.BoundMemberTy;
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>(Val: 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.
21128ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
21129 Expr *CastExpr, CastKind &CastKind,
21130 ExprValueKind &VK, CXXCastPath &Path) {
21131 // The type we're casting to must be either void or complete.
21132 if (!CastType->isVoidType() &&
21133 RequireCompleteType(TypeRange.getBegin(), CastType,
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
21148ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
21149 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
21150}
21151
21152ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
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>(Val: arg->IgnoreParens());
21157 if (!castArg) {
21158 ExprResult result = DefaultArgumentPromotion(E: arg);
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 =
21170 InitializedEntity::InitializeParameter(Context, Type: paramType,
21171 /*consumed*/ Consumed: false);
21172 return PerformCopyInitialization(Entity: entity, EqualLoc: callLoc, Init: arg);
21173}
21174
21175static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
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>(Val: 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>(Val: E)) {
21191 loc = ref->getLocation();
21192 d = ref->getDecl();
21193 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(Val: E)) {
21194 loc = mem->getMemberLoc();
21195 d = mem->getMemberDecl();
21196 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(Val: 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.
21220ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
21221 if (!Context.isDependenceAllowed()) {
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.
21225 ExprResult Result = CorrectDelayedTyposInExpr(E);
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;
21240 if (ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr&: Result, DoFunctionPointerConversion: false))
21241 return Result;
21242
21243 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21244 // leaves Result unchanged on failure.
21245 Result = E;
21246 if (resolveAndFixAddressOfSingleOverloadCandidate(SrcExpr&: Result))
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>(Val: BME)) {
21262 PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
21263 } else if (const auto *ME = dyn_cast<MemberExpr>(Val: BME)) {
21264 if (ME->getMemberNameInfo().getName().getNameKind() ==
21265 DeclarationName::CXXDestructorName)
21266 PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
21267 }
21268 tryToRecoverWithCall(E&: result, PD,
21269 /*complain*/ ForceComplain: true);
21270 return result;
21271 }
21272
21273 // ARC unbridged casts.
21274 case BuiltinType::ARCUnbridgedCast: {
21275 Expr *realCast = stripARCUnbridgedCast(e: E);
21276 diagnoseARCUnbridgedCast(e: realCast);
21277 return realCast;
21278 }
21279
21280 // Expressions of unknown type.
21281 case BuiltinType::UnknownAny:
21282 return diagnoseUnknownAnyExpr(S&: *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>(Val: E->IgnoreParenImpCasts());
21291 if (DRE) {
21292 auto *FD = cast<FunctionDecl>(Val: DRE->getDecl());
21293 unsigned BuiltinID = FD->getBuiltinID();
21294 if (BuiltinID == Builtin::BI__noop) {
21295 E = ImpCastExprToType(E, Type: Context.getPointerType(FD->getType()),
21296 CK: CK_BuiltinFnToFnPtr)
21297 .get();
21298 return CallExpr::Create(Ctx: Context, Fn: E, /*Args=*/{}, Ty: Context.IntTy,
21299 VK: VK_PRValue, RParenLoc: SourceLocation(),
21300 FPFeatures: FPOptionsOverride());
21301 }
21302
21303 if (Context.BuiltinInfo.isInStdNamespace(ID: 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(),
21308 getLangOpts().CPlusPlus20
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.
21316 InstantiateFunctionDefinition(PointOfInstantiation: E->getBeginLoc(), Function: FD,
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(Other: DRE->getQualifierLoc());
21324 TemplateArgumentListInfo TemplateArgs;
21325 DRE->copyTemplateArgumentsInto(List&: 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
21383bool Sema::CheckCaseExpression(Expr *E) {
21384 if (E->isTypeDependent())
21385 return true;
21386 if (E->isValueDependent() || E->isIntegerConstantExpr(Ctx: Context))
21387 return E->getType()->isIntegralOrEnumerationType();
21388 return false;
21389}
21390
21391/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
21392ExprResult
21393Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
21394 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
21395 "Unknown Objective-C Boolean value!");
21396 QualType BoolT = Context.ObjCBuiltinBoolTy;
21397 if (!Context.getBOOLDecl()) {
21398 LookupResult Result(*this, &Context.Idents.get(Name: "BOOL"), OpLoc,
21399 Sema::LookupOrdinaryName);
21400 if (LookupName(R&: Result, S: getCurScope()) && Result.isSingleResult()) {
21401 NamedDecl *ND = Result.getFoundDecl();
21402 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(Val: 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
21412ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
21413 llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
21414 SourceLocation RParen) {
21415 auto FindSpecVersion =
21416 [&](StringRef Platform) -> std::optional<VersionTuple> {
21417 auto Spec = llvm::find_if(Range&: AvailSpecs, P: [&](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(Range&: AvailSpecs, P: [&](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)).
21439 if (FunctionScopeInfo *Context = getCurFunctionAvailabilityContext())
21440 Context->HasPotentialAvailabilityViolations = true;
21441
21442 return new (Context)
21443 ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
21444}
21445
21446ExprResult Sema::CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
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.
21457 T = Context.DependentTy;
21458
21459 return RecoveryExpr::Create(Ctx&: Context, T, BeginLoc: Begin, EndLoc: End, SubExprs);
21460}
21461

source code of clang/lib/Sema/SemaExpr.cpp